欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【Python】(较简单)使用scipy.io.loadmat读取.mat文件中的数据部分

程序员文章站 2022-06-11 15:20:22
...

Python使用Scipy库中的io.loadmat读取.mat文件,并获取数据部分

读取方法很简单,只需要使用scipy.io库即可,Python代码入下:

import scipy.io as sio

yFile = 'y2.mat'    #相对路径
datay=sio.loadmat(yFile)

print datay

此时输出的datay是一个字典格式的输出,如下:

{‘y’: array([[10.56991 ],
[ 8.777489 ],
[ 7.78356 ],
…,
[ 2.188018 ],
[ 0.8057049],
[ 3.876159 ]]), ‘version’: ‘1.0’, ‘header’: ‘MATLAB 5.0 MAT-file, Platform: PCWIN64, Created on: Tue Apr 21 19:55:25 2020’, ‘globals’: [‘y’]}

此时若要获取其中的数据部分y,则可直接输出datay[‘y’],同时也可输出其格式(或类型)以验证其输出的正确性,如下:

import scipy.io as sio

yFile = 'y2.mat'   #相对路径
datay=sio.loadmat(yFile)

print datay
print datay['y'],datay['y'].shape

如果想要读取.mat文件中的多个数据,同样也很简单,只需注意与.mat文件中的数据命名对应即可。代码如下:

import scipy.io as sio

datafile='C:\\Users\\ASUS\\Desktop\yAll.mat'   #绝对路径
dataAll=sio.loadmat(datafile)
print dataAll
print dataAll['y'],'\n',dataAll['data'],dataAll['y'].shape,dataAll['data'].shape

此时源.mat文件读取如下:

{‘y’: array([[10.56991 ],
[ 8.777489 ],
[ 7.78356 ],
…,
[ 2.188018 ],
[ 0.8057049],
[ 3.876159 ]]), ‘version’: ‘1.0’, ‘data’: array([[1.55666670e-02, 4.67866667e-01, 9.86170000e+00],
[2.03883870e-02, 4.78300000e-01, 1.11255000e+01],
[1.87500000e-02, 4.51200000e-01, 1.09451000e+01],
…,
[4.64663800e-03, 1.68412833e+00, 1.79000000e+00],
[4.96423500e-03, 1.96910772e+00, 1.98000000e+00],
[7.01694900e-03, 9.04650847e-01, 3.80000000e+00]]), ‘header’: ‘MATLAB 5.0 MAT-file, Platform: PCWIN64, Created on: Tue Apr 21 21:35:44 2020’, ‘globals’: [‘data’, ‘y’]}

获取到的数据输出如下:

[[10.56991 ]
[ 8.777489 ]
[ 7.78356 ]

[ 2.188018 ]
[ 0.8057049]
[ 3.876159 ]]
[[1.55666670e-02 4.67866667e-01 9.86170000e+00]
[2.03883870e-02 4.78300000e-01 1.11255000e+01]
[1.87500000e-02 4.51200000e-01 1.09451000e+01]

[4.64663800e-03 1.68412833e+00 1.79000000e+00]
[4.96423500e-03 1.96910772e+00 1.98000000e+00]
[7.01694900e-03 9.04650847e-01 3.80000000e+00]] (8429L, 1L) (8429L, 3L)