Created
July 21, 2016 05:37
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The last line of mat2np should enforce matlab to use integers, so size is not converted to floats:
npary = npary.reshape(int32(sh)).transpose();