Matlab example of passing matrices to/from Python

Related:

Passing N-D arrays to/from Python from Matlab R2014b and newer is possible, but requires ravel/unravel since Matlab doesn’t understand Numpy arrays with ndim>1. Matlab understands lists, dicts, sets, scalars, and other less frequently used classes from Python.

Matlab R2017a brought the Matlab string class to/from Python str, and supports Python 2.7, 3.4 and 3.5.

Calling Python from Matlab Example

the “clown” image is included with Matlab.

filtered clown image
  1. Load an image in Matlab 2. filter the image in Python 3. display result in Matlab.

Access xarray matrices in Matlab

These functions are used to access the auroral model GLOW from Matlab.

function V = xarray2mat(V)
% convert xarray 2-D array to Matlab matrix

V= V{1}.values; 
S = V.shape;
V = cell2mat(cell(V.ravel('F').tolist()));
V = reshape(V,[int64(S{1}), int64(S{2})]);
    
end

function I = xarrayind2vector(V,key)
% convert xarray index to Matlab 1-D matri
    
I = cell2mat(cell(V{1}.indexes{key}.values.tolist)); 
    
end

Note on Python reshape() and ravel() ‘F’ order

The use of the ‘F’ parameter to and from Python in the .reshape() and .ravel() methods–this is crucial or your matrix will be transposed inside Python!