《GNU_Octave_Beginner_s_Guide》讀書筆記4:Octave腳本
在指令行中edit,進入Editor視窗。
Editor有自己的菜單,儲存的檔案名字尾為m,是為了能在MatLib上跑。
檔案:script41.m内容如下:
A=rand(3,5);
min(min(A))
在指令視窗中執行:
>> script41
ans = 0.25487
完成,注意調用時不帶字尾。
>> script41.m
error: invalid call to script D:\octaveHome\script41.m
使用source函數也可以執行。即使把檔案名改為script41.k
>> source("script41.k")
ans = 0.0024577
有兩類檔案:
function檔案,以function開頭;
script檔案。
鍵盤輸入指令格式:a = input(prompt string, "s")
>> a = input("Enter a number: ");
Enter a number:
>> s = input("Enter a string: " , "s");
Enter a string: //加了“s”參數,輸入字串時不用帶引号。
因為Octave把字串視為字元的數組,ischar(s)為真。
input接受數組輸入。
>> A = input("Enter matrix elements: ")
Enter matrix elements: [1 2; 3 4]
A =
1 2
3 4
disp函數類似于println,在控制台上顯示。
>> disp("a has the value"), disp(a)
a has the value
dd
以#或%開始的行被忽略,用以為行注釋。 %可以與matlib相容,#不行。
使用...(matlib風格)或\(linux風格)結尾,做行連接配接符。
>> rem(7,3) //傳回餘數remainder
ans = 1
條件: if...elseif...else...endif
endif不可少,是指令行判斷結束的标志
元素級bool操作:&, |, !.
短路操作: &&,||
switch語句:
switch ( x<2 | rem(x,2)== 0 )
case 1
disp("x not a prime");
otherwise //用otherwise,不是default.
disp("x could be a prime");
endswitch //endswitch表示結束
for循環:
例1:
for 初值表達式:終值表達式 //沒有步長,步長為1,如:for y=3:x-1
do something (body)
endfor
例2:
for 初值表達式:步長:終值表達式 //沒有步長,步長為1,如 for y=3:2:x-1
do something (body)
endfor
循環體内有break語句和continue語句。 break; continue;
while語句:
while condition
do something (body)
endwhile
endif,endfor,endwhile可以全換成end,與matlib相容。
do...util語句:
do
something (body)
until condition
自增,自減: ++,--
支援循環嵌套
異常處理:
//類似java的try...catch
try
something (body)
catch
cleanup if an error has occurred (body)
end_try_catch
另一種方式:
//類似java的try...finally
unwind_protect
do something (body)
unwind_protect_cleanup
cleanup whether an error has occurred or not (body)
end_unwind_protect
C語言風格的輸入輸出函數:
printf(), 格式:%d,%f,%e or %E,%c,%s,\n,\t,\b,\r
儲存工作/持久化:
save –option1 –option2 filename variable1 variable2 ...
option的選擇:-text,
讀入資料:
load primes.mat
函數形式:
save("prime.mat", "prime_sequence");
ss= load("primes.dat", "ascii"); //可防止現在的空間變量名被覆寫。