# 二、简单示例

``````# coding=utf-8
import matlab.engine
import time

# 第一步，初始化Matlab的Runtime
t1 = time.time()
eng = matlab.engine.start_matlab()
t2 = time.time()

# 第二步，调用Matlab函数
res1 = eng.sqrt(16.0)
t3 = time.time()

res2 = eng.abs(-8.6)
t4 = time.time()

# 第三步，退出Runtime
eng.quit()
t5 = time.time()

print type(res1), res1
print type(res2), res2
print "Initial time", t2 - t1
print "Running time1", t3 - t2
print "Running time2", t4 - t3
print "Quit time", t5 - t4``````

# 三、更复杂的示例

## 1.调用.m文件

``````# coding=utf-8
import matlab.engine

eng = matlab.engine.start_matlab()
eng.triangle(nargout=0)
eng.quit()``````

## 2.调用自定义函数

Python调用代码如下：

``````# coding=utf-8
import matlab.engine

eng = matlab.engine.start_matlab()
ans = eng.triangle(2.3, 9.1)
print ans
eng.quit()``````

``````# coding=utf-8
import matlab.engine

A = matlab.int8([1, 2, 3, 4, 5])
print type(A), A.size, A``````

## 3.绘图测试

``````#coding=utf-8
import matlab.engine

def plot_test(eng):
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--')")

eng = matlab.engine.start_matlab()
plot_test(eng)
# 需要让程序在这暂停，类似于C++里的system('pause')，不然Figure一闪而过
# 按任意键退出
raw_input()
eng.quit()``````

# 三、项目相关

``````def joinCode(new_names):
codes = []
for item in new_names:
codes.append("res = eng." + item + "()")
return codes

def execMatlab(codes, exs, ex2s, eys, ey2s):
eng = matlab.engine.start_matlab()
for code in codes:
exec code
exs.append(res[0][0])
ex2s.append(res[0][1])
eys.append(res[0][2])
ey2s.append(res[0][3])
eng.quit()``````

``````def exeCMD(cmds):
for i in range(cmds.__len__()):
print "n---------------------------------------------------------------------"
print "Executing:", cmds[i]
os.system(cmds[i])
print "---------------------------------------------------------------------n"
print "**********", ((i + 1) * 1.0 / len(cmds)) * 100, "% finished.**********"
print "**********100 % finished.**********"``````

``````def getOSType():
sysstr = platform.system()
if (sysstr == "Windows"):
separator = "\"
elif (sysstr == "Linux"):
separator = "/"
return separator``````

THE END

)">