python处理matlab的mat数据

python 和matlab是2个常用的实验室平台工具,在一些应用下,这2个不同平台下的数据会打交道,因此如何读取和保存显得尤为重要,这里需要用到python的第三方平台下的scipy模块。

先用下面这个命令检查是否下载好scipy

import scipy

如果报错,用python install scipy 或者 conda install scipy 下载安装

需要用到scipy中的输入输出类中的loadmat 和savemat方法:
 

import scipy.io as sio

sio.loadmat(file_name, mdict=None, appendmat=True, **kwargs)
sio.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

x = np.ones((3,3))

x
Out[86]: 
array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]])

sio.savemat('f.mat',x)
Traceback (most recent call last):

  File "<ipython-input-87-d739bc03c885>", line 1, in <module>
    sio.savemat('f.mat',x)

下面介绍一个简单的保存 导入例子:


import scipy.io as sio
import numpy as np

x = np.ones((3,3))

x
Out[86]: 
array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]])

sio.savemat('f.mat',{"x":x})



myMat =sio.loadmat('f.mat')

print(myMat) #输出为字典
{'__header__': b'MATLAB 5.0 MAT-file Platform: nt, Created on: Fri Aug 21 16:29:37 2020', '__version__': '1.0', '__globals__': [], 'x': array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]])}

#以保存名为key,输出list value
print(myMat['x'])
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]

如果想把python数据保存为mat数据,则需要cell格式数据,而python没有实现cell,因此需要用到numpy模块,可以看这篇博客。

猜你喜欢

转载自blog.csdn.net/qq_39463175/article/details/108149649