Marco Solbiati
Marco Solbiati

Reputation: 123

Create Matlab struct in Python

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?

Upvotes: 2

Views: 3408

Answers (1)

mfitzp
mfitzp

Reputation: 15545

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

Upvotes: 1

Related Questions