How to preserve matlab struct when accessing in python?
When I need to load data into Python from MATLAB that 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 with scipy.io.loadmat
. I can then assemble these into there own variables, or if needed, repackage them into a dictionary. The use of the exec
command may not be appropriate in all cases, but if you are just trying to processes data it 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')
Found this tutorial about matlab struct and python
http://docs.scipy.org/doc/scipy/reference/tutorial/io.html