Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

python - How to efficiently convert Matlab engine arrays to numpy ndarray?

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 noticed that converting the results from Matlab's matlab.mlarray.double to numpy's numpy.ndarray seems horribly slow.

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)

Which takes the following times:

From other array
0.00150722111994
From list
0.0705359556928
From matlab
7.0873282467

The conversion takes about 100 times as long as a conversion from list.

Is there any way to speed up the conversion?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...