MatLab3-程序设计1解析 联系客服

发布时间 : 星期三 文章MatLab3-程序设计1解析更新完毕开始阅读5a8cf42a1611cc7931b765ce05087632311274bf

Columns 8 through 10 0.5878 0.3090 0.0000 For循环可按需要嵌套。 n=0:1:10; for i=1:11 for j=1:11 y(i=sin(n(i; n(j=n(j*10; end end y =

Columns 1 through 7

0 -0.5064 0.9300 -0.8027 -0.1425 -0.9765 -0.5118 Columns 8 through 11 0.8586 -0.9957 0.9917 0.9287 n = 1.0e+012 * Columns 1 through 7

0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 Columns 8 through 11 0.7000 0.8000 0.9000 1.0000

可以利用break命令跳出for循环 【例】一个简单的for循环示例。 for i=1:10; %i依次取1,2,…10,.

x(i=i; %对每个i值,重复执行由该指令构成的循环体, end; x %要求显示运行后数组x的值。 x =

1 2 3 4 5 6 7 8 9 10 while循环结构

与For循环以固定次数求一组命令的值相反,While 循环以不定的次数求一组语句的值。While循环的一般形式是:

while expression {commands} end

只要在表达式里的所有元素为真,就执行while和end 语句之间的{commands}。

【例】num=0;EPS=1; while (1+EPS>1 EPS=EPS/2; num=num+1;

end ? num num = 53

? EPS=2*EPS EPS = 2.2204e-016 【例】

x = zeros(1,6; % x是一个的零矩阵 i = 1; while i <= 6, x(i = 1/i; i = i+1; end ?x x =

1.0000 0.5000 0.3333 0.2500 0.2000 0.1667 可以利用 break 命令跳出 while 循环 while 循环可按需要嵌套。 【例】Fibonacci 数组的元素满足 Fibonacci 规则: ak

;且

。现要求该数组中第一个大于

10000 的元素。 a(1=1;a(2=1;i=2; while a(i<=10000 a(i+1=a(i-1+a(i; i=i+1; end; i,a(i, i

= 21 ans = 10946 %当现有的元素仍小于 10000 时,求解下一个元素。 if-else-end 分支结构 很多情况下,命令的序列必须根据关系的检验有条件地执行。在编程语言里,这种逻辑由某 种 If-Else-End 结构来提供。最简单的 If-Else-End 结构是: if expression {commands} end 如果在表达式中的所有元素为真(非零,那么就执行 if 和 end 语言之间的{commands} 【例】?apples=10; ?cost=apples*25 cost = 250 ?if apples>5 cost=(1-20/100*cost; end ?cost cost = 200 假如有两个选择,If-Else-End 结构是: 6

if expression commands evaluated if True else commands evaluated if False end 在这里,如果表达式为真,则执行第一组命令;如果表达式是假,则执行第二组命令。 当有三个或更多的选择时,If-Else-End 结构采用形式 if expression1 commands evaluated if expression1 is True elseif expression2 commands evaluated if expression2 is True elseif expression3 commands evaluated if expression3 is True elseif expression4 commands evaluated if expression4 is True elseif ?? . . . else commands evaluated if no other expression is True end 最后的这种形式,只和所碰到的、与第一个真值表达式相关的命令被执行;接下来的 关系表达式不检验,跳过其余的 If-Else-End 结构。而且,最后的 else 命令可有可无。 【例】 if rand(1>0.5 disp('i love you' else disp('i donot love you' end 【例】一个简单的分支结构。 cost=10;number=12; if number>8 7

sums=number*0.95*cost; end, sums sums = 114.0000 【例】用 for 循环指令来寻求 Fibonacc 数组中第一个大于 10000 的元素。 n=100;a=ones(1,n; for i=3:n a(i=a(i-1+a(i-2; if a(i>=10000 a(i, break; end end i ans = 10946 i = 21 %跳出所在的一级循环。 MATLAB 的输入与输出语句

输入语句 o 输入数值 x=input('please input a

number:' please input a number:22 x = 22 o 输入字符串 x=input('please input a

输出语句 o 输出显示

命令

自由格式 (disp 8

disp(23+454-29*4 361 disp([11 22 33; 44 55 66; 77 88 99] 11 22 33 44 55 66 77 88

格式化输出 (fprintf。 fprintf('The area