问题
I am trying to create a file to be read in a matlab enviroment. The structure in matlab looks like this
trx(1) =
x: [1×1500 double]
y: [1×1500 double]
a: [1×1500 double]
b: [1×1500 double]
theta: [1×1500 double]
firstframe: 1
endframe: 1500
nframes: 1500
off: 0
trx(2) =
x: [1×751 double]
y: [1×751 double]
a: [1×751 double]
b: [1×751 double]
theta: [1×751 double]
firstframe: 750
endframe: 1500
nframes: 751
off: -749
So naturally I created a python dictionary with the required fields and create a list, then used savemat. However when I loaded in matlab I only get cell arrays. I also tried using this but the problem is that not all of the fields are arrays with the same shapes for example 'firstframe' is an int. Then when I used fromarrays() but it complains because the shape does not match.
I am trying now to convert a dictionary to an structured array, but have not found anything related. And also trying to create a numpy record that allows different shapes for the arrays. Any light very welcome
回答1:
In Octave
M =
scalar structure containing the fields:
x =
1 2 3 4
y =
5 6 7 8
one = 1
two =
1 2
>> save -7 struct.mat M
In Ipython:
In [450]: dat = io.loadmat('struct.mat')
In [451]: dat
Out[451]:
{'__header__': b'MATLAB 5.0 MAT-file, written by Octave 4.2.2, 2019-02-08 18:49:49 UTC',
'__version__': '1.0',
'__globals__': [],
'M': array([[(array([[1., 2., 3., 4.]]), array([[5., 6., 7., 8.]]), array([[1.]]), array([[1., 2.]]))]],
dtype=[('x', 'O'), ('y', 'O'), ('one', 'O'), ('two', 'O')])}
Here M
is (1,1) structured array, with all fields being object
dtype. That way they can each have their own shape. The scalar is a (1,1) matrix.
来源:https://stackoverflow.com/questions/54598286/how-to-save-a-list-of-python-dictionaries-as-an-array-of-matlab-structured-array