Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve matlab struct when accessing 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 struct

    >> 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 easy as data2.LON, etc.. It's not as trivial in python. It give me several option though like

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 is possible to preserve the same structure in python? If not, how to best access the data? The present python code that I am using is very difficult to work with.

Thanks

like image 678
mikeP Avatar asked Aug 14 '12 14:08

mikeP


1 Answers

this will return the mat structure as a dictionary

def _check_keys( dict):
"""
checks if entries in dictionary are mat-objects. If yes
todict is called to change them to nested dictionaries
"""
for key in dict:
    if isinstance(dict[key], sio.matlab.mio5_params.mat_struct):
        dict[key] = _todict(dict[key])
return dict


def _todict(matobj):
    """
    A recursive function which constructs from matobjects nested dictionaries
    """
    dict = {}
    for strg in matobj._fieldnames:
        elem = matobj.__dict__[strg]
        if isinstance(elem, sio.matlab.mio5_params.mat_struct):
            dict[strg] = _todict(elem)
        else:
            dict[strg] = elem
    return dict


def loadmat(filename):
    """
    this function should be called instead of direct scipy.io .loadmat
    as it cures the problem of not properly recovering python dictionaries
    from mat files. It calls the function check keys to cure all entries
    which are still mat-objects
    """
    data = sio.loadmat(filename, struct_as_record=False, squeeze_me=True)
    return _check_keys(data)
like image 72
idan357 Avatar answered Oct 13 '22 00:10

idan357