Python调用Matlab的混合编程

一. 配置方法:

找到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


二. 使用方法:

#Start and quit
import matlab.engine
eng = matlab.engine.start_matlab()
eng.quit()

#Call Matlab Functions:
#Just call with form eng.xxx()
#the function xxx should in the namespace of matlab.


#Asynchronously Call
import matlab.engine
eng = matlab.engine.start_matlab()
future = eng.sqrt(4.0,async=True)
ret = future.result()
print(ret)


#WorkSpace Usage:
import matlab.engine
eng = matlab.engine.start_matlab()
eng.workspace['y'] = x
a = eng.eval('sqrt(y)')
print(a)


#Skills for unsupported features in python
#eng.eval()
import matlab.engine
eng = matlab.engine.start_matlab()
eng.eval("T = readtable('patients.dat');",nargout=0)

#Plot With Matlab:
import matlab.engine
eng = matlab.engine.start_matlab()
data = eng.peaks(100)
eng.mesh(data)


三. 测试用例(Python2):

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++的调用方式更为科学。



你可能感兴趣的:(Python,matlab,混合编程)