MATLAB: Passing numpy.ndarray from Python to Matlab

ndarraynumpypython

Hi,
Using the MATLAB engine for Python, I've succeeded in calling and passing scalar data from Python to my MATLAB function, however when trying to pass numpy.ndarray data from Python to MATLAB, the following error is returned:
File "C:\Python27\lib\site-packages\matlab\engine\matlabengine.py", line 74, in __call__
out=_stdout, err=_stderr)
TypeError: unsupported data type numpy.ndarray
Any suggestions? Thanks, Yochanan

Best Answer

Beginning in MATLAB R2018b, Python functions that accept numpy arrays may also accept MATLAB arrays without explicit conversion. When necessary, a numpy array can be created explicitly from a MATLAB array. For example, if you have a supported version of Python that is installed with the numpy library, you can do the following:
>> x = rand(2,2); % MATLAB array
>> y = py.numpy.array(x); % numpy array
y =
Python ndarray:
0.5943 0.8064
0.6133 0.1372
Use details function to view the properties of the Python object.
Use double function to convert to a MATLAB array.
Also beginning in MATLAB R2018b, it is possible to convert numeric numpy arrays returned from Python into MATLAB arrays. For example:
>> y = py.numpy.random.random([int32(2), int32(2)]) % numpy array
y =
Python ndarray:
0.5943 0.8064
0.6133 0.1372
Use details function to view the properties of the Python object.
Use double function to convert to a MATLAB array.
>> x = 2*double(y) % MATLAB array
x =
1.1885 1.6129
1.2266 0.2744
See the MATLAB documentation on Passing Matrices and Multidimensional Arrays for additional Information.