Skip to content

Instantly share code, notes, and snippets.

@samtx
Created July 21, 2016 05:37
Show Gist options
  • Save samtx/108e88bbfcdc3b4fbe9073b470e6668e to your computer and use it in GitHub Desktop.
Save samtx/108e88bbfcdc3b4fbe9073b470e6668e to your computer and use it in GitHub Desktop.
Matlab functions for converting back and forth between Numpy ndarray objects and Matlab matrices
function npary = mat2np(mat)
% convert matlab matrix to python (Numpy) ndarray
sh = fliplr(size(mat));
mat2 = reshape(mat,1,numel(mat)); % [1, n] vector
npary = py.numpy.array(mat2);
npary = npary.reshape(sh).transpose(); % python ndarray
end
function mat = np2mat(npary)
% convert python (Numpy) ndarray to matlab
sh = double(py.array.array('d',npary.shape));
npary2 = double(py.array.array('d',py.numpy.nditer(npary)));
mat = reshape(npary2,fliplr(sh))'; % matlab 2d array
end
@ErwinHoogerwerf
Copy link

The last line of mat2np should enforce matlab to use integers, so size is not converted to floats:
npary = npary.reshape(int32(sh)).transpose();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment