Skip to content

Instantly share code, notes, and snippets.

@psycharo-zz
Created May 15, 2014 17:05
Show Gist options
  • Select an option

  • Save psycharo-zz/59c5c8e78e9e76dd8997 to your computer and use it in GitHub Desktop.

Select an option

Save psycharo-zz/59c5c8e78e9e76dd8997 to your computer and use it in GitHub Desktop.
loading matlab matrices
def loadmat(filename):
'''
this function should be called instead of direct spio.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)
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment