aretor
aretor

Reputation: 2569

Convert a MATLAB matrix object to a python NumPy array

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.

Upvotes: 2

Views: 10896

Answers (2)

kurupama
kurupama

Reputation: 1

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

Upvotes: 0

Dev-iL
Dev-iL

Reputation: 24169

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.

Upvotes: 3

Related Questions