How to save matlab structure when accessed in python?

I have a mat file that I accessed using

from scipy import io mat = io.loadmat('example.mat') 

From matlab, example.mat contains the following structure

  >> load example.mat >> data1 data1 = LAT: [53x1 double] LON: [53x1 double] TIME: [53x1 double] units: {3x1 cell} >> data2 data2 = LAT: [100x1 double] LON: [100x1 double] TIME: [100x1 double] units: {3x1 cell} 

In Matlab, I can access data as easily as data2.LON, etc. This is not so trivial in python. This gives me several options, although it seems

 mat.clear mat.get mat.iteritems mat.keys mat.setdefault mat.viewitems mat.copy mat.has_key mat.iterkeys mat.pop mat.update mat.viewkeys mat.fromkeys mat.items mat.itervalues mat.popitem mat.values mat.viewvalues 

Is it possible to keep the same structure in python? If not, what is the best way to access data? The existing Python code that I use is very difficult to work with.

thanks

+7
source share
3 answers

Found this tutorial about matlab struct and python

http://docs.scipy.org/doc/scipy/reference/tutorial/io.html

+6
source

(!) In the case of nested structures stored in *.mat files, it is necessary to check whether the elements in the dictionary that io.loadmat are Matlab structures. For example, if in Matlab

 >> thisStruct ans = var1: [1x1 struct] var2: 3.5 >> thisStruct.var1 ans = subvar1: [1x100 double] subvar2: [32x233 double] 

Then use the code by changing the nested structures (e.g. dictionaries) in scipy.io.loadmat

0
source

When I need to load data in Python from MATLAB, which is stored in an array of structs {strut_1, struct_2}, I extract a list of keys and values ​​from the object that I load using scipy.io.loadmat . Then I can assemble them into my own variables or, if necessary, repack them into a dictionary. Using the exec command may not be acceptable in all cases, but if you're just trying to process the data, this works well.

 # Load the data into Python D= sio.loadmat('data.mat') # build a list of keys and values for each entry in the structure vals = D['results'][0,0] #<-- set the array you want to access. keys = D['results'][0,0].dtype.descr # Assemble the keys and values into variables with the same name as that used in MATLAB for i in range(len(keys)): key = keys[i][0] val = np.squeeze(vals[key][0][0]) # squeeze is used to covert matlat (1,n) arrays into numpy (1,) arrays. exec(key + '=val') 
0
source

All Articles