1
votes

I want to call some python code from MATLAB, in order to do this I need to convert a matrix object to a NumPy ndarray, through the MATLAB function py.numpy.array. However, passing simply the matrix object to the function does not work. At the moment I solved the problem converting the matrix to a cell of cells object, containing the rows of the matrix. For example

function ndarray = convert(mat)
    % This conversion fails
    ndarray = py.numpy.array(mat)

    % This conversion works
    cstr = cell(1, size(mat, 1));
    for row = 1:size(mat, 1)
        cstr(row) = {mat(row, :)};
    end
    ndarray = py.numpy.array(cstr);

I was wondering if it exists some more efficient solution.

2
Keep in mind you can only send vector from Matlab to Python. 1XN In file.py convert it to a numpy ndarray.Tony Tannous
Which versions of MATLAB and Python are you using? What are the dimensions of the array? Please also provide a minimal reproducible example in your question.Dev-iL
@TonyTannous actually I think that using cell of cells is correctly interpreted in numpy as a MxN ndarray.aretor
@Dev-iL I am using MATLAB 2016a and python3.5. The array can become very large, thus if I need to convert the matrix object to an intermediate structure I want to make a time efficient conversion.aretor
"Large" is meaningless. I meant - how many dimensions does it have? What are typical and maximal sizes (perhaps there's some memory limitation to the MATLAB-Python interface)? In any case I think you could reshape the array to a vector in MATLAB, then reshape it back in numpy.Dev-iL

2 Answers

2
votes

Assuming your array contains double values, the error tells us exactly what we should do:

A = magic(3);
%% Attempt 1:
try 
npA = py.numpy.array(A);
% Result:
%   Error using py.numpy.array
%   Conversion of MATLAB 'double' to Python is only supported for 1-N vectors.
catch
end
%% Attempt 2:
npA = py.numpy.array(A(:).');
% Result: OK!

Then:

>> whos npA
  Name      Size            Bytes  Class               Attributes

  npA       1x1                 8  py.numpy.ndarray   

Afterwards you can use numpy.reshape to get the original shape back, either directly in MATLAB or in Python.

0
votes

Actually, using python 2.7 and Matlab R2018b, it worked with simply doing:

pyvar = py.numpy.array(var);

Matlab tells me that if I want to convert the numpy array to Matlab variable, I can just use double(pyvar)

By the way, it didn't worked with python 3.7, neither using an older version of Matlab . I don't know what this means, but I thought this might be helpful