您的位置:首页 > 产品设计 > UI/UE

《GNU_Octave_Beginner_s_Guide》读书笔记4:Octave脚本

2017-09-08 09:42 246 查看
《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"); //可防止现在的空间变量名被覆盖。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: