Last active
May 17, 2017 13:05
-
-
Save PeterMinin/d3ce4cd8b6d0fbabf19ed735355f92fd to your computer and use it in GitHub Desktop.
A function for reading .mat files from MATLAB v7.3+ in Python. Doesn't support all MATLAB types yet.
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 h5py | |
import numpy as np | |
def convert_item(item, file): | |
cls = item.attrs['MATLAB_class'].decode('utf-8') | |
if cls == 'char': | |
return ''.join(map(chr, item)) | |
elif cls == 'uint8': | |
return np.array(item, dtype=np.uint8) | |
elif cls == 'double': | |
return np.array(item) | |
elif cls == 'cell': | |
res = np.empty(item.shape, dtype='O') | |
for ind in np.ndindex(*item.shape): | |
res[ind] = convert_item(file[item[ind]], file) | |
return res | |
else: | |
raise RuntimeError('Unsupported MATLAB class: {}'.format(cls)) | |
def read_mat(filename): | |
data_file = h5py.File(filename) | |
return {key: convert_item(data_file[key], data_file) for key in data_file.keys() if key != '#refs#'} | |
data = read_mat('data.mat') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment