如何从MATLAB中返回的python数据类型中获取数据?
我有这样一个python脚本:如何从MATLAB中返回的python数据类型中获取数据?,python,matlab,numpy,types,numpy-ndarray,Python,Matlab,Numpy,Types,Numpy Ndarray,我有这样一个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); dis
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中将其用作数组或矩阵,或整数或其他。如何将其转换为这些类型之一
我一直在看这些:
一些答案建议写入.mat
文件。我不想写入文件。这需要能够实时运行,写入文件将使其速度非常慢,原因显而易见
这里似乎有一个答案:哪一个显示
shape = cellfun(@int64,cell(myfunction_results.shape));
ls = py.array.array('d',myfunction_results.flatten('F').tolist());
p = double(ls);
但我必须说,这非常麻烦……有没有更简单的方法?目前没有简单的方法将NumPy ndarray转换为Matlab数组,但以下Matlab函数可以执行转换:
函数A=np2mat(X,tp)
%将NumPy ndarray转换为Matlab数组
如果nargin<2
tp='d';
结束
sz=int32(py.array.array('i',X.shape));
如果strcmp(tp,‘d’)
A=重塑(双(py.array.array(tp,X.flatten('F')),sz);
其他strcmp(tp,‘i’)
A=重塑(int32(py.array.array(tp,X.flatten('F')),sz);
其他的
错误('未知数据类型')
结束
默认数据类型为双精度,请指定参数tp='i'
以转换整数数组