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

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


当前回答

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文件。

其他回答

读取文件

import scipy.io
mat = scipy.io.loadmat(file_name)

检查MAT变量的类型

print(type(mat))
#OUTPUT - <class 'dict'>

字典中的键是MATLAB变量,值是分配给这些变量的对象。

也可以使用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文件。

在我自己努力解决这个问题并尝试其他库(我不得不说mat4py也是一个很好的库,但有一些限制)之后,我构建了这个库(“matdata2py”),它可以处理大多数变量类型,对我来说最重要的是“字符串”类型。.mat文件需要保存在-V7.3版本中。我希望这对社区有用。

安装:

pip install matdata2py

如何使用这个库:

import matdata2py as mtp

加载Matlab数据文件:

Variables_output = mtp.loadmatfile(file_Name, StructsExportLikeMatlab = True, ExportVar2PyEnv = False)
print(Variables_output.keys()) # with ExportVar2PyEnv = False the variables are as elements of the Variables_output dictionary. 

使用ExportVar2PyEnv = True,你可以分别看到每个变量作为与Mat文件中保存的同名的python变量。

国旗的描述

StructsExportLikeMatlab = True/False结构导出为字典格式(False)或类似于Matlab的基于点的格式(True)

ExportVar2PyEnv = True/False将单个字典中的所有变量导出(True)或作为单独的单独变量导出到python环境中(False)

首先将.mat文件保存为:

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

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

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