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)
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.]]