octave和python_python 调用octave | 学步园

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 19:35   2090   0

python是一个强大的胶水语言,兼具重量级

Otave和matlab高度兼容,又兼具开源和轻量的特点,用来处理矩阵计算最合适,特别是很多

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

第一步:让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.]]

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP