我正在寻找一种将NumPy数组传递给Matlab的方法。
我已经通过使用scipy.misc.imsave
将数组存储为图像,然后使用imread
加载它来实现了这一点,但是这会导致矩阵包含0到256之间的值而不是“真实”值。
将此矩阵除以256,并乘以原始NumPy数组中的最大值可以得到正确的矩阵,但我觉得这有点繁琐。
是否有更简单的方法?
我正在寻找一种将NumPy数组传递给Matlab的方法。
我已经通过使用scipy.misc.imsave
将数组存储为图像,然后使用imread
加载它来实现了这一点,但是这会导致矩阵包含0到256之间的值而不是“真实”值。
将此矩阵除以256,并乘以原始NumPy数组中的最大值可以得到正确的矩阵,但我觉得这有点繁琐。
是否有更简单的方法?
scipy.io.savemat
。import numpy as np
import scipy.io
x = np.linspace(0, 2 * np.pi, 100)
y = np.cos(x)
scipy.io.savemat('test.mat', dict(x=x, y=y))
类似的,还有scipy.io.loadmat
。
你可以使用load test
在Matlab中加载它。
或者像@JAB建议的那样,你可以将数据保存为ASCII制表符分隔文件(例如numpy.savetxt
)。但是,如果选择这种方法,您将被限制在2个维度。另一方面,ASCII是通用交换格式。几乎任何东西都能处理一个分隔文本文件。
load('test.mat')
的方式在matlab中读取吗? - Charlie Parkerdata.npz
或 data.npy
不起作用吗?如果不行,为什么? - Charlie Parker一个简单的解决方案,无需通过文件或外部库传递数据。
Numpy有一个将ndarray转换为list的方法,而matlab数据类型可以从列表中定义。因此,可以这样转换:
np_a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
mat_a = matlab.double(np_a.tolist())
从Matlab到Python需要更多的关注。没有内置函数可以直接将类型转换为列表。但是我们可以访问未形成结构的原始数据,因此使用reshape
(正确格式化)和transpose
(由于MATLAB和numpy存储数据的不同方式)来处理。强调一下:在您的项目中进行测试非常重要,特别是如果您正在使用超过2个维度的矩阵。它适用于MATLAB 2015a和2个维度。
np_a = np.array(mat_a._data.tolist())
np_a = np_a.reshape(mat_a.size).transpose()
mat_a = matlab.double(np_a.tolist())
可能非常低效/慢。除了处理np数组之外,最好采用Joe Kington的答案。请参见 https://dev59.com/LlcO5IYBdhLWcg3wvUQp#45284125。 - 5Ke这里有一个解决方案,避免在Python中迭代或使用文件IO——但需要依赖于(丑陋的)Matlab内部结构:
import matlab
# This is actually `matlab._internal`, but matlab/__init__.py
# mangles the path making it appear as `_internal`.
# Importing it under a different name would be a bad idea.
from _internal.mlarray_utils import _get_strides, _get_mlsize
def _wrapper__init__(self, arr):
assert arr.dtype == type(self)._numpy_type
self._python_type = type(arr.dtype.type().item())
self._is_complex = np.issubdtype(arr.dtype, np.complexfloating)
self._size = _get_mlsize(arr.shape)
self._strides = _get_strides(self._size)[:-1]
self._start = 0
if self._is_complex:
self._real = arr.real.ravel(order='F')
self._imag = arr.imag.ravel(order='F')
else:
self._data = arr.ravel(order='F')
_wrappers = {}
def _define_wrapper(matlab_type, numpy_type):
t = type(matlab_type.__name__, (matlab_type,), dict(
__init__=_wrapper__init__,
_numpy_type=numpy_type
))
# this tricks matlab into accepting our new type
t.__module__ = matlab_type.__module__
_wrappers[numpy_type] = t
_define_wrapper(matlab.double, np.double)
_define_wrapper(matlab.single, np.single)
_define_wrapper(matlab.uint8, np.uint8)
_define_wrapper(matlab.int8, np.int8)
_define_wrapper(matlab.uint16, np.uint16)
_define_wrapper(matlab.int16, np.int16)
_define_wrapper(matlab.uint32, np.uint32)
_define_wrapper(matlab.int32, np.int32)
_define_wrapper(matlab.uint64, np.uint64)
_define_wrapper(matlab.int64, np.int64)
_define_wrapper(matlab.logical, np.bool_)
def as_matlab(arr):
try:
cls = _wrappers[arr.dtype.type]
except KeyError:
raise TypeError("Unsupported data type")
return cls(arr)
到达这里所需的观察是:
type(x).__name__
和type(x).__module__
来确定是否理解类型。._data
属性中。不幸的是,Matlab在内部没有有效地使用_data
属性,并且正在逐个项目地迭代它,而不是使用Python的memoryview
协议 :(. 因此,使用这种方法的速度增益很小。
array.array
包装(就像你在那里做的那样)和不这样做(就像我在这里做的那样)有什么区别吗? - Eric不确定是否算作“简单”,但我找到了一个解决方案,可以快速地从在Matlab中调用的Python脚本中创建的numpy数组中移动数据:
dump_reader.py(Python源代码):
import numpy
def matlab_test2():
np_a = numpy.random.uniform(low = 0.0, high = 30000.0, size = (1000,1000))
return np_a
dump_read.m(Matlab脚本):
clear classes
mod = py.importlib.import_module('dump_reader');
py.importlib.reload(mod);
if count(py.sys.path,'') == 0
insert(py.sys.path,int32(0),'');
end
tic
A = py.dump_reader.matlab_test2();
toc
shape = cellfun(@int64,cell(A.shape));
ls = py.array.array('d',A.flatten('F').tolist());
p = double(ls);
toc
C = reshape(p,shape);
toc
这取决于matlab的双精度在数组上相对于单元格/矩阵的高效工作。第二个技巧是通过Python的本地array.array以有效的方式将数据传递给matlab的双精度。
P.S. 抱歉挖坟,但我为此苦苦挣扎了很久,这个主题是最接近的结果之一。也许它可以帮助有所缩短难以解决问题的时间。
P.P.S. 已在 Matlab R2016b + python 3.5.4 (64位) 上测试。
不久以前,我遇到了同样的问题,并编写了以下脚本,以便轻松地在交互式会话之间复制和粘贴数组。显然,仅适用于小型数组,但我发现这比每次通过文件保存/加载更为方便:
声明:我编写了这个库。
import matlab.engine
import numpy
eng = matlab.engine.start_matlab()
buf = numpy.array([[1, 2, 3], [4, 5, 6]], dtype='uint16')
# Supported in R2022a and earlier: must initialize a matlab.uint16 from
# the numpy array and pass it to the function
array_as_matlab_uint16 = matlab.uint16(buf)
res = eng.sum(array_as_matlab_uint16, 1, 'native')
print(res)
# Supported as of R2022b: can pass the numpy array
# directly to the function
res = eng.sum(buf, 1, 'native')
print(res)
假设您有一个形状为(365,10)的2D每日数据,保存在np数组np3Darrat
中,该数组将具有形状(5,365,10),表示五年的数据。在Python中保存您的np数组:
import scipy.io as sio #SciPy module to load and save mat-files
m['np3Darray']=np3Darray #shape(5,365,10)
sio.savemat('file.mat',m) #Save np 3D array
然后在MATLAB中将np的3D数组转换为MATLAB的3D矩阵:
load('file.mat','np3Darray')
M3D=permute(np3Darray, [2 3 1]); %Convert numpy array with shape (5,365,10) to MATLAB matrix with shape (365,10,5)