Created
March 10, 2017 17:29
-
-
Save usmcamp0811/a7a1cd114766447c8bd233235ddad8c2 to your computer and use it in GitHub Desktop.
First... MATLAB sucks!
Second... This is some code I found on Stackoverflow that converts .mat files to python dictionaries..
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scipy.io as spio | |
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) | |
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], spio.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, spio.matlab.mio5_params.mat_struct): | |
dict[strg] = _todict(elem) | |
elif isinstance(elem,np.ndarray): | |
dict[strg] = _tolist(elem) | |
else: | |
dict[strg] = elem | |
return dict | |
def _tolist(ndarray): | |
''' | |
A recursive function which constructs lists from cellarrays | |
(which are loaded as numpy ndarrays), recursing into the elements | |
if they contain matobjects. | |
''' | |
elem_list = [] | |
for sub_elem in ndarray: | |
if isinstance(sub_elem, spio.matlab.mio5_params.mat_struct): | |
elem_list.append(_todict(sub_elem)) | |
elif isinstance(sub_elem,np.ndarray): | |
elem_list.append(_tolist(sub_elem)) | |
else: | |
elem_list.append(sub_elem) | |
return elem_list | |
if __name__ == "__main__": | |
wObs = '/media/mcamp/ExoHDD/miniC2BMC/wObjs.mat' | |
wObs = loadmat(wObs) | |
#follow this pattern for all field names in the .mat file | |
for r in range(len(wObs['wObjs'])): | |
print(wObs['wObjs'][r].name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment