我试图将一些变量从python传递到Matlab,但我没有成功。如果我只传递一个变量,它可以正常工作,但由于我需要传递更多不同类型的变量(矩阵、向量、标量(,所以不起作用。
这是我在Python test_return.py:中的代码
import numpy as np
def run_test_return():
a = np.ones((5,3))
b = np.ones((10))
c = 4
return a, b, c
# I don't know if I should return the variables as tuples,list, dictionary... to be easier to read in matlab
这是要读取的matlab脚本:
pyOut = py.importlib.import_module('test_return');
py.importlib.reload(pyOut);
[a,b,c] = py.test_return.run_test_return(); % This is the part that doesn't work, I don't know how to import more than one variable, if I import only one works fine...
a = double(py.array.array('d',py.numpy.nditer(a))); % I don't know if this is the best way to read numpy 2D array
b = double(py.array.array('d',py.numpy.nditer(a)));
c = double(py.array.array('d',py.numpy.nditer(a)));
函数返回一个元组:
>> p = py.file_return.run_test_return;
>> class(p)
py.tuple
元组中的元素具有不同的数据类型:
>> class(p{1})
py.numpy.ndarray
>> class(p{3})
py.int
在MATLAB中,您可以简单地将元组封装在一个单元格中,并使用cellfun对其进行迭代,以将每个元素转换为一个双元组的单元格数组:
>> c=cellfun(@double,cell(p),'UniformOutput',false);