问题描述
我试图将一些变量从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,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);