How to efficiently convert Matlab engine arrays to numpy ndarray?
Moments after posting the question I found the solution.
For one-dimensional arrays, access only the _data
property of the Matlab array.
import timeit
print 'From list'
print timeit.timeit('np.array(x)', setup=setup_range, number=1000)
print 'From matlab'
print timeit.timeit('np.array(x)', setup=setup_matlab, number=1000)
print 'From matlab_data'
print timeit.timeit('np.array(x._data)', setup=setup_matlab, number=1000)
prints
From list
0.0719847538787
From matlab
7.12802865169
From matlab_data
0.118476275533
For multi-dimensional arrays you need to reshape the array afterwards. In the case of two-dimensional arrays this means calling
np.array(x._data).reshape(x.size[::-1]).T
Tim's answer is great for 2D arrays, but a way to adapt it to N dimensional arrays is to use the order
parameter of np.reshape() :
np_x = np.array(x._data).reshape(x.size, order='F')