Convert a NumPy array to Matlab

With a newish version of Matlab it is easy to call Python functions from Matlab and work with the results in Matlab. This is great because you get access to the multitude of great free numerical libraries available in Python. It is also nice when you are migrating your code from Matlab to Python and want to verify that the results are identical.

The built in automatic data conversion works fine with native Python data types, but oddly enough it does not work with NumPy ndarray, which is the most widely used numeric array type for Python numeric calculations. Maybe Mathworks is scared by the better alternative to Matlab?

It is, however, possible to convert a NumPy ndarray to a Matlab array using the following Matlab function:

function A = np2mat(X, tp)
% Convert NumPy ndarray to a Matlab array
if nargin < 2
    tp = 'd';
sz = int32(py.array.array('i', X.shape));
if strcmp(tp, 'd')
    A = reshape(double(py.array.array(tp,X.flatten('F'))), sz);
elseif strcmp(tp, 'i')
    A = reshape(int32(py.array.array(tp,X.flatten('F'))), sz);
    error('Unknown data type')

Default data type is double, specify argument tp='i' to convert an integer array.