Retornar variáveis ​​de python para Matlab

Oct 08 2020

Estou tentando passar algumas variáveis ​​de python para Matlab, mas não consegui. Se eu passar apenas uma variável funciona bem, mas como preciso passar mais variáveis ​​com tipos diferentes (matriz, vetor, escalar) não funciona.

este é meu código em 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

E este é o script matlab para ler:

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)));

Respostas

Paolo Oct 08 2020 at 14:59

Sua função retorna uma tupla:

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

e os elementos na tupla são de diferentes tipos de dados:

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

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

no MATLAB, você pode simplesmente envolver a tupla em uma célula e iterar sobre ela com o cellfun para converter cada elemento em uma matriz de células duplas:

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