现在的位置: 首页 > 综合 > 正文

python 调用octave

2017年08月04日 ⁄ 综合 ⁄ 共 1390字 ⁄ 字号 评论关闭

python是一个强大的胶水语言,兼具重量级编程语言(如java)和轻巧的脚本(如shell)的优点。实验中处理数据库和文本解析的工作都可以交给它来完成。虽说python也能利用numpy,scipy处理科学计算问题,但是里面同时定义了array和matrix还有稀疏矩阵,每种对象的处理方式都不同,很是头大。

Otave和matlab高度兼容,又兼具开源和轻量的特点,用来处理矩阵计算最合适,特别是很多算法可以向量化(vectorization)更使得计算过程简洁美观实用。

能不能让它们一起工作呢?

第一步:让octave可以当作脚本执行。

在脚本的头部写上:

#!/usr/bin/env /Applications/Octave.app/Contents/Resources/bin/octave -qf

告诉操作系统这个可执行的脚本可以用什么可执行文件来执行,这里我们指定了octave在mac os里的位置。windows的位置也可以被找到,然后填进去。

然后让这个文件是可执行的

chmod a+x octaveScipt.m

第二步:保存octave的运行结果到mat文件

如果python和octave有计算结果的传输。那么就需要借助mat文件了。

save('-v7','computeResult.mat')

注意:需要指明保存mat文件的版本,如果是octave默认版本,python 的scipy.io读取不了。

第三步:python调用octave脚本,载入octave脚本计算结果

只要利用python执行外部的脚本的命令就可以了,等待计算完毕,执行python的后续命令。

os.system("./octaveScript.m")

载入计算结果:

mag=sio.loadmat("computeResult.mat")["mag"]

octaveScript.m

!/usr/bin/env /Applications/Octave.app/Contents/Resources/bin/octave -qf                                                                                     
a=[1,2,3]; 
a; 
for i=1:10
        fprintf('It is octave\n')
end
mag=magic(3)
save('-v7','computeResult.mat','mag')
# end of script 

callOctave.py

import os
import scipy.io as sio 

os.system("./octaveScript.m")                                                                                                                                 
for i in range(0,10):
        print("it's python")

mag=sio.loadmat("computeResult.mat")["mag"]
print(mag)

执行callOctave.py的结果:

It is octave
It is octave
It is octave
It is octave
It is octave
It is octave
It is octave
It is octave
It is octave
It is octave
mag =

   8   1   6
   3   5   7
   4   9   2

it's python
it's python
it's python
it's python
it's python
it's python
it's python
it's python
it's python
it's python
[[ 8.  1.  6.]
 [ 3.  5.  7.]
 [ 4.  9.  2.]]

抱歉!评论已关闭.