Skip to content

Instantly share code, notes, and snippets.

@PeterMinin
Last active May 17, 2017 13:05
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 PeterMinin/d3ce4cd8b6d0fbabf19ed735355f92fd to your computer and use it in GitHub Desktop.
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.
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