Python笔记——读写mat数据

使用模块scipy.io的函数loadmat和savemat可以实现Python对mat数据的读写。

语法:

scipy.io.loadmat(file_name, mdict=None, appendmat=True, **kwargs)

scipy.io.savemat(file_name, mdict, appendmat=True, format=’5′, long_field_names=False, do_compression=False, oned_as=’row’)


任务

代码实现以下两个任务:

(1)读取某路径下文件mat4py.mat 中的变量mat4py ,其中矩阵mat4py的内容如下 

mat4py =
     1     2     3
     4     5     6
     7     8     9

(2)将变量 x=[1, 2, 3], y=[4, 5, 6]和z=[7, 8, 9]三个变量存到data.mat文件中。

代码

import scipy.io as sio 
matfn = '/home/weiliu/workspace/python/matlab/mat4py.mat'
data = sio.loadmat(matfn)
print('Information for mat4py.mat ')
print(data)
print('\nThe vaulue of mat4py:')
print(data['mat4py'])
mat4py_load = data['mat4py']
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
sio.savemat('saveddata.mat', {'x': x,'y': y,'z': z}) 

输出

(1)在终端会有如下输出:

Information for mat4py.mat 
{‘mat4py’: array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]], dtype=uint8), ‘__version__’: ‘1.0’, ‘__header__’: ‘MATLAB 5.0 MAT-file, Platform: GLNXA64, Created on: Thu Dec  4 16:05:35 2014’, ‘__globals__’: []}


The vaulue of mat4py:
[[1 2 3]
 [4 5 6]
 [7 8 9]]
/usr/lib/python2.7/dist-packages/scipy/io/matlab/mio.py:232: FutureWarning: Using oned_as default value (‘column’) This will change to ‘row’ in future versions
  oned_as=oned_as)

(2)saveddata.mat 文件内容:

x = [1; 2; 3]

y = [4; 5; 6]

z = [7; 8; 9]

注意

(1)矩阵用Python读取得到的array的内容

(2)1-D numpy arrays会因savemat中参数oned_as的赋值有相应变化

(3)在使用MATLAB时注意数据的格式转换


参考

http://blog.csdn.net/rumswell/article/details/8545087

    原文作者:刘伟ECJTU
    原文地址: https://blog.csdn.net/breeze5428/article/details/41725153
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞