找到Matlab安装根目录,比如D:\matlab,然后进入D:\matlab\extern\engines\python目录中,Shift+右键-->“在此处打开命令窗口”,
1.有管理员权限的,用 管理员权限执行:python setup.py install
2.无管理员权限的,将installdir添加到Python的包搜索路径中,再加入到PYTHONPATH环境变量中即可:python setup.py build --build-base builddir install --install-base installdir
import matlab
import matlab.engine
import time
def basic_test(eng):
print "Basic Testing Begin"
print "eng.power(100,2) = %d"%eng.power(100,2)
print "eng.max(100,200) = %d"%eng.max(100,200)
print "eng.rand(5,5) = "
print eng.rand(5,5)
print "eng.randi(matlab.double([1,100]),matlab.double([3,4]))"%\
eng.randi(matlab.double([1,100]),matlab.double([3,4]))
print "Basic Testing Begin"
def plot_test(eng):
print "Plot Testing Begin"
eng.workspace['data'] = \
eng.randi(matlab.double([1,100]),matlab.double([30,2]))
eng.eval("plot(data(:,1),'ro-')")
eng.hold('on',nargout=0)
eng.eval("plot(data(:,2),'bx--')")
print "Plot testing end"
def audio_test(eng,freq,length):
print "Audio Testing Begin"
eval_str = "f = %d;t=%d;"%(freq,length)
eng.eval(eval_str,nargout = 0)
eng.eval('fs = 44100;T=1/fs;t=(0:T:t);',nargout = 0)
eng.eval('y = sin(2 * pi * f * t);',nargout = 0)
eng.eval('sound(y,fs);',nargout = 0)
time.sleep(length)
print "Audio Testing End"
def fourier_test(eng):
pass
def demo(eng):
basic_test(eng)
plot_test(eng)
audio_test(eng,680,1)
if __name__ == "__main__":
print "Initializing Matlab Engine"
eng = matlab.engine.start_matlab()
print "Initializing Complete!"
demo(eng)
print "Exiting Matlab Engine"
print "Press Any Key to Exit"
raw_input();
eng.quit()
print "Bye-Bye"
eng = matlab.engine.start_matlab()
eng.quit()
比起C++ Engine的API,Python Engine的最牛逼之处就是可以直接以原生的形式调用Matlab内建函数,而不是用Eval方法。当然,如果你想用也是一点问题都没有的。同时,变量的存取再也不用和一堆mxArray以及它们的ADT打交道了,直接以字典的形式对engine.workspace进行存取即可。显然比C++的调用方式更为科学。