Read .mat files in Python


Question

Is it possible to read binary MATLAB .mat files in Python?

I've seen that SciPy has alleged support for reading .mat files, but I'm unsuccessful with it. I installed SciPy version 0.7.0, and I can't find the loadmat() method.

1
325
7/24/2019 9:26:57 AM

Accepted Answer

An import is required, import scipy.io...

import scipy.io
mat = scipy.io.loadmat('file.mat')
442
7/24/2019 8:23:04 PM

Neither scipy.io.savemat, nor scipy.io.loadmat work for MATLAB arrays version 7.3. But the good part is that MATLAB version 7.3 files are hdf5 datasets. So they can be read using a number of tools, including NumPy.

For Python, you will need the h5py extension, which requires HDF5 on your system.

import numpy as np
import h5py
f = h5py.File('somefile.mat','r')
data = f.get('data/variable1')
data = np.array(data) # For converting to a NumPy array

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon