是否可以在Python中读取二进制MATLAB .mat文件?

我看到SciPy声称支持读取.mat文件,但我没有成功。我安装了SciPy 0.7.0版本,但找不到loadmat()方法。


当前回答

安装了MATLAB 2014b或更新版本后,可以使用MATLAB for Python引擎:

import matlab.engine
eng = matlab.engine.start_matlab()
content = eng.load("example.mat", nargout=1)

其他回答

首先将.mat文件保存为:

save('test.mat', '-v7')

之后,在Python中,使用常用的loadmat函数:

import scipy.io as sio
test = sio.loadmat('test.mat')

安装了MATLAB 2014b或更新版本后,可以使用MATLAB for Python引擎:

import matlab.engine
eng = matlab.engine.start_matlab()
content = eng.load("example.mat", nargout=1)

也可以使用hdf5storage库。关于matlab版本支持的详细信息,这里是官方文档。

import hdf5storage

label_file = "./LabelTrain.mat"
out = hdf5storage.loadmat(label_file) 

print(type(out)) # <class 'dict'>
from os.path import dirname, join as pjoin
import scipy.io as sio
data_dir = pjoin(dirname(sio.__file__), 'matlab', 'tests', 'data')
mat_fname = pjoin(data_dir, 'testdouble_7.4_GLNX86.mat')
mat_contents = sio.loadmat(mat_fname)

你可以使用上面的代码来读取Python中默认保存的.mat文件。

Scipy可以很好地加载.mat文件。 我们可以使用get()函数将其转换为numpy数组。

mat = scipy.io.loadmat('point05m_matrix.mat')

x = mat.get("matrix")
print(type(x))
print(len(x))

plt.imshow(x, extent=[0,60,0,55], aspect='auto')
plt.show()