一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

python读取和保存mat文件代码方法示例

时间:2021-08-25 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下python读取和保存mat文件代码方法示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

一、mat文件

mat数据格式是Matlab的数据存储的标准格式。在Matlab中主要使用load()函数导入一个mat文件,使用save()函数保存一个mat文件。对于文件

load('data.mat')
save('data_1.mat','A')

其中,'A'表示要保存的内容。

二、python中读取mat文件

在python中可以使用scipy.io中的函数loadmat()读取mat文件,函数savemat保存文件。

1、读取文件

如上例:

#coding:UTF-8
'''
Created on 2015年5月12日
@author: zhaozhiyong
'''
 
import scipy.io as scio
 
dataFile = 'E://data.mat'
data = scio.loadmat(dataFile)

注意,读取出来的data是字典格式,可以通过函数type(data)查看。

print type(data)

结果显示

找到mat文件中的矩阵:

print data['A']

结果显示

[[ 0. 0. 0. 0. 0. 0. 0.

0. 0. 0. 0. 0. 0. 0.

。。。。。。。。。。。

0. 0. 0. 0. 0. 0. 0.

0.36470588 0.90196078 0.99215686 0.99607843 0.99215686 0.99215686

0.78431373 0.0627451 0. 0. 0. 0. 0.

0. 0. 0. 0. 0. 0. 0.

。。。。。。。。。。。。

0.94117647 0.22745098 0. 0. 0. 0. 0.

0. 0. 0. 0. 0. 0. 0.

0. 0. 0. 0. 0. 0. 0.

0. 0. 0. 0. 0. 0.30196078

。。。。。。。

0. 0. 0. 0. 0. 0. 0.

0. 0. 0. 0. 0. 0. 0. ]]

格式为:

即为numpy中的矩阵格式。

2、保存文件

将这里的data['A']矩阵重新保存到一个新的文件dataNew.mat中:

dataNew = 'E://dataNew.mat'
scio.savemat(dataNew, {'A':data['A']})

注意:是以字典的形式保存。

热门栏目