Python调用Matlab代码
1.1 步骤
为matlab安装python引擎
- windows系统
cd "matlabroot\extern\engines\python"
python setup.py install
- linux、mac系统
cd "matlabroot/extern/engines/python"
python setup.py install
启动、关闭引擎
import matlab.engine
eng = matlab.engine.start_matlab() #开启引擎
# call some matlab codes
eng.quit() # 关闭引擎
需要说明的是,如果python代码执行完毕后,而代码中没有关闭引擎的话,那么引擎会自动关闭。
示例代码
- python调用matlab非函数代码
# -*- coding: utf-8 -*-
if __name__ == "__main__":
print 'start python'
import matlab.engine
print 'start python call matlab ...'
eng = matlab.engine.start_matlab()
eng.triarea(nargout=0) # 调用triarea.m
print 'spython call matlab end'
print 'python end'
triarea.m代码如下,其中triarea.m必须和上面的python代码在同一个路径下:
b = 5;
h = 3;
a = 0.5*(b.* h)
- python调用matlab用户自定义函数代码
# -*- coding: utf-8 -*-
if __name__ == "__main__":
print 'start python'
import matlab.engine
print 'start python call matlab ...'
eng = matlab.engine.start_matlab()
ret = eng.triarea(1.0,5.0) # 调用triarea.m
print(ret)
print 'spython call matlab end'
print 'python end'
triarea.m代码如下:
function a = triarea(b,h)
a = 0.5*(b.* h);