Search code examples
pythonmatlabnumpy-ndarraymatlab-engine

passing numpy array to matlab engine


I have a code in python but now I have to call a function developed for another person in Matlab. I would like to do that with matlab engine, but I have an error when passing the variables to the function, I got:

TypeError: unsupported Python data type: numpy.ndarray

This is a simple python code, for more or less what I wanna do:

import numpy  as np
import matlab
import matlab.engine
eng =  matlab.engine.start_matlab()

eng.cd()

Nn = 30
x= 250*np.ones((1,Nn)) 
y= 100*np.ones((1,Nn)) 
zz = matlab.double([[32]])
xx = matlab.double(x.tolist())
yy = matlab.double(y.tolist())
Output = eng.simple_test(xx,yy,zz,nargout=4)
A = np.array(Output[0]).astype(float)
B = np.array(Output[1]).astype(float)
C = np.array(Output[2]).astype(float)
D = np.array(Output[3]).astype(float)

And this is an example of the matlab function:

function [A,B,C,D] = simple_test(x,y,z)

A = 3*x+2*y;
B = x*ones(length(x),length(x));
C = ones(z);
D = x*y';
end

Does someone know how to effectively pass NumPy arrays as variables in matlab engine?


Solution

  • Try:

    xx = matlab.double(x.tolist())
    yy = matlab.double(y.tolist())
    zz = matlab.double([[32]])
    out = eng.simple_test(xx, yy, zz, nargout=4)
    

    https://www.mathworks.com/help/matlab/matlab_external/matlab-arrays-as-python-variables.html