【发布时间】:2019-02-26 05:06:53
【问题描述】:
我有一个这样的 python 脚本:
import numpy as np
def my_function(x):
return np.array([x])
我有一个 MATLAB 脚本来调用它:
clear all;
clc;
if count(py.sys.path,'') == 0
insert(py.sys.path,int32(0),'');
end
myfunction_results = py.python_matlab_test.my_function(8);
display(myfunction_results);
它会显示:
myfunction_results =
Python ndarray with properties:
T: [1×1 py.numpy.ndarray]
base: [1×1 py.NoneType]
ctypes: [1×1 py.numpy.core._internal._ctypes]
data: [1×8 py.buffer]
dtype: [1×1 py.numpy.dtype]
flags: [1×1 py.numpy.flagsobj]
flat: [1×1 py.numpy.flatiter]
imag: [1×1 py.numpy.ndarray]
itemsize: 8
nbytes: 8
ndim: 1
real: [1×1 py.numpy.ndarray]
shape: [1×1 py.tuple]
size: 1
strides: [1×1 py.tuple]
[8.]
但我不知道如何真正从这个对象中获取数据。类型是py.numpy.ndarray,但我显然想在 MATLAB 中将它用作数组或矩阵,或整数或其他东西。如何将其转换为其中一种类型?
我一直在看这些:https://www.mathworks.com/help/matlab/examples/call-python-from-matlab.html https://www.mathworks.com/matlabcentral/answers/216498-passing-numpy-ndarray-from-python-to-matlab https://www.mathworks.com/help/matlab/matlab_external/use-matlab-handle-objects-in-python.html
一些答案建议写入.mat 文件。我不想写入文件。这需要能够实时运行,并且由于显而易见的原因,写入文件会使其非常慢。
这里似乎有答案:"Converting" Numpy arrays to Matlab and vice versa 显示
shape = cellfun(@int64,cell(myfunction_results.shape));
ls = py.array.array('d',myfunction_results.flatten('F').tolist());
p = double(ls);
但我必须说这很麻烦......有没有更简单的方法?
【问题讨论】:
标签: python matlab numpy types numpy-ndarray