Access array contents from a .mat file loaded using Scipy.io.loadmat - python Access array contents from a .mat file loaded using Scipy.io.loadmat - python python python

Access array contents from a .mat file loaded using Scipy.io.loadmat - python


I've run into a similar issue with a fairly complex mat file at our company. I'm still getting my head wrapped around the scipy IO module, but here is what we found.

When you access matfile['sensors'] it returns a scipy.io.matlab.mio5_params.mat_struct object, which we can use to access the contents below. When you print it, it looks like a flat array, but you can still access the dict to get at the individual components. So you could run something like this to start accessing the components:

from scipy.io import loadmatmatfile = loadmat('myfile.mat', squeeze_me=True, struct_as_record=False)matfile['sensors'].sensor1.channels.channel1.name

In your case you want to be able to iterate over the elements in the structure, which you can do if you access the _fieldnames property of the mat_struct object. From there you can just loop over the field names and access them with getattr:

for field in matfile['sensors']._fieldnames:    # getattr will return the value for the given key    print getattr(matfile['sensors'], field)

This is at least allowing us to access the deeply nested elements without having to alter our mat files.


The solution I resorted to was to simplify the MATLAB structure. I eliminated nested structures. Each data set resides in a single file and I used python to loop over all the files of a particular type in the specified directory. (http://bogdan.org.ua/2007/08/12/python-iterate-and-read-all-files-in-a-directory-folder.html, if you would like to see an example of that.)

Importing the flat matlab structure results in a dictionary where the matlab variable names are the keys. Strings come in as arrays of shape (1,) --> [ string ], and numbers come in as arrays of shape (N, M) --> [[ numbers ]].

I still have to learn a bit more about the numpy arrays.