How to create Matlab matrix array from scipy.io?

Consider the following Matlab code:

pmod(1).name{1} = 'regressor1'; pmod(1).param{1} = [1 2 4 5 6]; pmod(1).poly{1} = 1; pmod(2).name{1} = 'regressor2-1'; pmod(2).param{1} = [1 3 5 7]; pmod(2).poly{1} = 1; 

This creates an array of structures. Each array structure contains three fields of type cell . Thus, we have the following hierarchy in pmod :

 pmod // struct array | *- struct | | | *- cell // contains 1 or more strings | *- cell // contains 1 or more arrays | *- cell // contains 1 or more arrays | *- struct [...] 

I am trying to use scipy.io to create the above data structures in Python so that they can be loaded into Matlab (this hierarchy is required by SPM ).

Creating a structure is straightforward, since scipy.io.savemat saves any dict whose keys are of type str as a Matlab structure:

 from scipy.io import savemat struct = { 'field1': 1, 'field2': 2, } savemat('/tmp/p.mat', {'a_struct': struct}) 

However, trying to generalize this to an array of structures, I ended up in the following road block:

 struct_array = [struct, struct] savemat('/tmp/p.mat', {'s_array': struct_array}) 

It does not behave as expected; when loading p.mat in Matlab, I get an array of 1x2 cells, not a struct array.

How to create an array of structures using scipy.io ?

Notes:

  • I tried savemat('/tmp/p.mat', np.array(struct_array)) and savemat('/tmp/p.mat', np.array(struct_array, dtype=object)) , to no avail.
+5
source share
1 answer

You can use np.core.records.fromarrays to build an array of records that is roughly equivalent to the MATLAB structure and will be converted to the MATLAB structure using scip.io.savemat .

 from numpy.core.records import fromarrays from scipy.io import savemat myrec = fromarrays([[1, 10], [2, 20]], names=['field1', 'field2']) savemat('p.mat', {'myrec': myrec}) 

When opened in MATLAB this gives:

 >> load('p.mat') >> myrec myrec = 1x2 struct array with fields: field1 field2 
+3
source

Source: https://habr.com/ru/post/1234019/


All Articles