2

I have a problem: I want to create a Matlab like struct in Python. The struct I need to create has two fields: "val" and "sl". It has to be a 1x2 struct. The "val" field needs to have two 3x3 matrices inside (e.g A and B), while the "sl" field needs to have two values inside (e.g 137 and 159). The final struct should be like this:

val    sl
3x3   137
3x3   159

In Matlab the code is: struct(1).val=A;struct(1).sl=137;struct(2).val=B;struct(2).sl=159 In python I've tried hval = fromarrays([[A, B], [137, 159]], names=['val', 'sl']) but it gives me this error: File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/core/records.py", line 608, in fromarrays raise ValueError("array-shape mismatch in array %d" % k)

ValueError: array-shape mismatch in array 1 Does anyone know how to solve this problem?

1
  • Is there a reason this needs to be a record? Normally in Python you would use a pandas.DataFrame for this. Commented Jan 7, 2016 at 12:18

1 Answer 1

1

It doesn't appear as though you can store ndarray as an element of a record, as the fields need to have the same dimensions. It looks as though adding a 3x3 array to the val field makes the dimensions of that field 2x3x3, rather than being stored as a discrete array.

However, you can emulate the same sort of structure using Python dict and list types as follows:

struct = {
   'val': [A, B],
   'sl': [137, 138]
}

You could now access these elements as follows (note the argument order is different):

struct['val'][0] # = A
struct['sl'][1] # 138

To keep the order invert the dict/list structure:

struct = [
    {'val': A, 'sl': B},
    {'val': 137, 'sl': 138},
]

struct[0]['val']  # A
struct[1]['sl'] # 138
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.