PythonからMatlabに変数を返す

Oct 08 2020

PythonからMatlabにいくつかの変数を渡そうとしていますが、管理できませんでした。変数を1つだけ渡すと正常に機能しますが、異なるタイプ(行列、ベクトル、スカラー)の変数をさらに渡す必要があるため、機能しません。

これはPythontest_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);