Rückgabe von Variablen von Python an Matlab
Oct 08 2020
Ich habe versucht, einige Variablen von Python an Matlab zu übergeben, aber ich habe es nicht geschafft. Wenn ich nur eine Variable übergebe, funktioniert das einwandfrei, aber da ich mehr Variablen mit unterschiedlichen Typen (Matrix, Vektor, Skalar) übergeben muss, funktioniert dies nicht.
Dies ist mein Code in 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
Und dies ist das Matlab-Skript zum Lesen:
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)));
Antworten
Paolo Oct 08 2020 at 14:59
Ihre Funktion gibt ein Tupel zurück:
>> p = py.file_return.run_test_return;
>> class(p)
py.tuple
und die Elemente im Tupel sind von verschiedenen Datentypen:
>> class(p{1})
py.numpy.ndarray
>> class(p{3})
py.int
In MATLAB können Sie das Tupel einfach in eine Zelle einschließen und mit cellfun darüber iterieren, um jedes Element in ein Zellenarray von Doubles zu konvertieren:
>> c=cellfun(@double,cell(p),'UniformOutput',false);