python中读写和存储matlab的.mat数据文件

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’)]

  • 13
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值