Skip to content

Instantly share code, notes, and snippets.

@ahwillia
Created October 17, 2020 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahwillia/bda4e270478d369479aa6ecb7decf80a to your computer and use it in GitHub Desktop.
Save ahwillia/bda4e270478d369479aa6ecb7decf80a to your computer and use it in GitHub Desktop.
Helper function for loading nested MATLAB structs into python
import scipy.io as spio
import numpy as np
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 = spio.loadmat(filename, struct_as_record=False, squeeze_me=True)
# convert to numpy
for key in data:
data[key] = _mat_to_dict(data[key])
return data
def _mat_to_dict(obj):
'''
A recursive function which constructs nested dictionaries from matlab
structs
'''
# if obj is a struct, recursively construct dict
if isinstance(obj, spio.matlab.mio5_params.mat_struct):
dest = {}
for strg in obj._fieldnames:
elem = obj.__dict__[strg]
dest[strg] = _mat_to_dict(elem)
return dest
# recursive call to convert struct arrays
elif isinstance(obj, np.ndarray) and len(obj) > 0 and type(obj[0]) == spio.matlab.mio5_params.mat_struct:
return np.array([_mat_to_dict(elem) for elem in obj])
# base case
else:
return obj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment