Matlab matrices ↔ Python

Related:


Passing N-D arrays to/from Python from Matlab ≥ R2014b 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: Matlab string class to/from Python str
  • Matlab R2017b: supports Python 2.7, 3.4, 3.5 and 3.6.

Matlab → Python

% 200x320 image is now in variable X
load clown 

% I ravel X to a row vector, and unravel with Numpy
Xp = py.numpy.reshape(X(:)',size(X),'F'); 

% Apply Gaussian filter to image
Yp = py.skimage.filters.gaussian(Xp,3);

% now let's come back to Matlab
% Y is a regular Matlab 2-D matrix
Y = reshape(cell2mat(cell(Yp.ravel('F').tolist())),size(X)); 

 %map comes from when you load clown
 figure
 subplot(1,2,1), imshow(X,map),title('original')
 subplot(1,2,2), imshow(Y,map),title('filtered by Python Scikit-Image')
%======================================================================
% now let's do something similar in Matlab--
% note I didn't make the filter truncation radius the same, so the numerical results differ.
F = fspecial('gaussian',[15,15],3);
M = imfilter(X,F);
imshow(M,map)

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.

Matlab ↔ xarray

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 matrix
    
I = cell2mat(cell(V{1}.indexes{key}.values.tolist)); 
    
end

Notes

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

Leave a Comment