sicpy.io提供了两个函数loadmat和savemat, 可以用于读取和存储.mat格式文件,非常方便。此外,该模块还提供了whosmat函数,用于列出mat文件中的变量信息。
函数 | 描述 |
---|---|
loadmat(file_name[, mdict, appendmat]) | 读取.mat 文件 |
savemat(file_name, mdict[, appendmat, …]) | Save a dictionary of names and arrays into a MATLAB-style .mat file. |
whosmat(file_name[, appendmat]) | List variables inside a MATLAB file. |
一、 loadmat
loadmat用于载入.mat 格式文件,接口调用方式
scipy.io.loadmat(file_name, mdict=None, appendmat=True, **kwargs)
返回值为dict类型。
函数支持v4 (Level 1.0), v6, v7 至 7.2 格式的.mat 文件。如需读取V7.3格式的.mat 文件,需要加载HDF5 库,因为SciPy 未实现HDF5 / 7.3接口。
使用实例
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)
print(type(mat_contents))
print(sorted(mat_contents.keys()))
print(mat_contents['testdouble'])
二、savemat
savemat函数用于保存.mat 文件,函数调用方式如下
scipy.io.savemat(file_name, mdict, appendmat=True, format=‘5’, long_field_names=False, do_compression=False, oned_as=‘row’)
import scipy.io as sio
import numpy as np
a = np.arange(20)
mdic = {"a": a, "label": "experiment"}
print(mdic)
sio.savemat("matlab_matrix.mat", mdic)
三、whosmat
whosmat用于查看.mat文件中的变量信息。接口如下:
scipy.io.whosmat(file_name, appendmat=True, **kwargs)
from io import BytesIO
import numpy as np
from scipy.io import savemat, whosmat
a = np.array([[10, 20, 30], [11, 21, 31]], dtype=np.int32)
b = np.geomspace(1, 10, 5)
f = BytesIO()
savemat(f, {'a': a, 'b': b})
# Each tuple in the output list gives the name, shape and data type of the array in f.
whosmat(f)
输出结果如下:
[(‘a’, (2, 3), ‘int32’), (‘b’, (1, 5), ‘double’)]