python - 将 Python numpy 数组写入 .mat 文件

标签 python arrays matlab numpy dictionary

我有一系列要保存在 .mat 文件中的 numpy 数组,以便稍后绘制数据。 (我不想使用 Pickle,因为我的实际程序要复杂得多并且有 2 个以上的数组。)我的 MWE 是:

import numpy as np
import mat4py as m4p

x = np.array([1,20,0.4,0.5,9,8.8])
y = np.array([0.3,0.6,1,1,0.01,0.7])

data = {'x': x,
        'y': y}
m4p.savemat('datafile.mat', data)

但我得到一个错误ValueError: Only dicts, two dimensional numeric, and char arrays are currently supported

这是什么意思,我该如何解决?

最佳答案

In [853]: from scipy import io
In [854]: x = np.array([1,20,0.4,0.5,9,8.8])
     ...: y = np.array([0.3,0.6,1,1,0.01,0.7])
     ...: 
In [855]: data={'x':x, 'y':y}
In [856]: io.savemat('test.mat',data)
In [857]: io.loadmat('test.mat')
Out[857]: 
{'__globals__': [],
 '__header__': b'MATLAB 5.0 MAT-file Platform: posix, Created on: Sun Nov 27 09:30:35 2016',
 '__version__': '1.0',
 'x': array([[  1. ,  20. ,   0.4,   0.5,   9. ,   8.8]]),
 'y': array([[ 0.3 ,  0.6 ,  1.  ,  1.  ,  0.01,  0.7 ]])}

为了与 MATLAB 兼容,数组已转换为 2d orderF 数组。

h5py 是另一种选择。较新的 Matlab 版本使用 HDF5 格式,提供与其他语言更好的兼容性。

np.savez 可以在不修改数组的情况下保存数组字典:

In [881]: data={'x':x, 'y':y,'xy':np.array((x,y))}
In [882]: np.savez('test',**data)
In [883]: D=np.load('test.npz')
In [884]: D.keys()
Out[884]: ['y', 'x', 'xy']
In [885]: D['xy']
Out[885]: 
array([[  1.00000000e+00,   2.00000000e+01,   4.00000000e-01,
          5.00000000e-01,   9.00000000e+00,   8.80000000e+00],
       [  3.00000000e-01,   6.00000000e-01,   1.00000000e+00,
          1.00000000e+00,   1.00000000e-02,   7.00000000e-01]])

D 是一个 NPZFile 对象,它是一个延迟加载器。所以它不会将所有数组直接转储到内存中。您可以通过键名访问它们。

关于python - 将 Python numpy 数组写入 .mat 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40828797/

相关文章:

java - 为什么没有 java.lang.Array 类?如果java数组是一个Object,它不应该扩展Object吗?

matlab - 如何将字符串 'pi' 转换为 double ? (MATLAB 2015a)

Matlab:拒绝抽样

python - 从非类函数调用类中的函数

python - 在 Mechanize 打开方法中获取 urllib2.URLError : <urlopen error EOF occurred in violation of protocol (_ssl. c:661)>

Java-数组 : How do i find the number that has a similar digit most times?

c - 验证一个人是否存在的函数[比较 C 中的字符串]

Python - 在守护进程中调用 multiprocessing.pool

python - Spyder IDE 提示无法检测未定义的名称

Matlab数组操作