How to efficiently convert Matlab engine arrays to numpy ndarray?

后端 未结 2 1981
[愿得一人]
[愿得一人] 2020-12-05 16:00

I am currently working on a project where I need do some steps of processing with legacy Matlab code (using the Matlab engine) and the rest in Python (numpy).

I noti

相关标签:
2条回答
  • 2020-12-05 16:12

    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
    
    0 讨论(0)
  • 2020-12-05 16:18

    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')

    0 讨论(0)
提交回复
热议问题