如何有效地将 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
"
"x = range(1000)")
setup_arange = ("import numpy as np
"
"x = np.arange(1000)")
setup_matlab = ("import numpy as np
"
"import matlab.engine
"
"eng = matlab.engine.start_matlab()
"
"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屋!