如何有效地将Matlab引擎数组转换为numpy ndarray? [英] How to efficiently convert Matlab engine arrays to numpy ndarray?
问题描述
我目前正在一个项目中,需要执行一些步骤以处理旧版Matlab代码(使用Matlab引擎),其余部分则使用Python(numpy)进行处理.
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).
我注意到,将结果从Matlab的matlab.mlarray.double
转换为numpy的numpy.ndarray
似乎非常缓慢.
I noticed that converting the results from Matlab's matlab.mlarray.double
to numpy's numpy.ndarray
seems horribly slow.
下面是一些示例代码,用于从另一个ndarray,列表和mlarray创建具有1000个元素的ndarray:
Here is some example code for creating an ndarray with 1000 elements from another ndarray, a list and an mlarray:
import timeit
setup_range = ("import numpy as np\n"
"x = range(1000)")
setup_arange = ("import numpy as np\n"
"x = np.arange(1000)")
setup_matlab = ("import numpy as np\n"
"import matlab.engine\n"
"eng = matlab.engine.start_matlab()\n"
"x = eng.linspace(0., 1000.-1., 1000.)")
print 'From other array'
print timeit.timeit('np.array(x)', setup=setup_arange, number=1000)
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)
需要以下时间:
From other array
0.00150722111994
From list
0.0705359556928
From matlab
7.0873282467
转换所需时间约为列表转换的100倍.
The conversion takes about 100 times as long as a conversion from list.
有什么方法可以加快转换速度吗?
Is there any way to speed up the conversion?
推荐答案
发布问题后的片刻,我找到了解决方法.
Moments after posting the question I found the solution.
对于一维数组,仅访问Matlab数组的_data
属性.
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)
打印
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
这篇关于如何有效地将Matlab引擎数组转换为numpy ndarray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!