Return variables from python to Matlab

331 views Asked by At

I'm trying to pass some variables from python to Matlab, but I didn't manage. If I pass only one variable it works fine, but since I need to pass more variables with different types (matrix, vector, scalar) doesn't work.

this is my 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

And this is the matlab script to read:

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

There are 1 answers

2
Paolo On

Your function returns a tuple:

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

and the elements in the tuple are of different data types:

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

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

in MATLAB, you can simply wrap the tuple in a cell and iterate over it with cellfun to convert every element to a cell array of doubles:

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