Python에서 Matlab으로 변수 반환

Oct 08 2020

파이썬에서 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)));

답변

Paolo Oct 08 2020 at 14:59

함수는 튜플을 반환합니다.

>> p = py.file_return.run_test_return;
>> class(p)
py.tuple

튜플의 요소는 데이터 유형이 다릅니다.

>> class(p{1})
py.numpy.ndarray

>> class(p{3})
py.int

MATLAB에서는 튜플을 셀로 감싸고 cellfun으로 반복하여 모든 요소를 ​​double로 구성된 셀형 배열로 변환 할 수 있습니다.

>> c=cellfun(@double,cell(p),'UniformOutput',false);