上海交通大学交大密西根 联合学院·一 ◆ 181 UM-SJTU Joint Institute University of Michigan Shanghal Jiao Tong University Notes for if statement discr b*b -4*a*c; if discr 0 disp('Warning:discriminant is negative,roots are imaginary'); elseif discr ==0 disp('Discriminant is zero,roots are repeated') else disp('Roots are real') end The keyword elseif has no space between else and if No semicolon at the end of lines containing if,else,end Indentation of if block is not necessary,but required The end statement is required
Notes for if statement Notes for if statement • The keyword elseif has no space between else and if • No semicolon at the end of lines containing if, else, end • Indentation of if block is not necessary, but required • The end statement is required
上海交通大学交大密西根 联合学院·一 ◆ 81T UM-SJTU Joint Institute ■ University of Michigan Shanghal Jiao Tong University Interation Control The while...end loop i 0; while(i<10) 。The`for.end"loop i=i+1; end for variable start:end arr zeros(5,4); statements for i=1:5 for j=1:4 end arr(i,j)=(i-1)*5+(j-1) end Compute the average end =[84,75,68,93,89,77,88]:n=7: Array index started from 1 not 0 i=1;total 0; -Flow control end with“end” while(i〈=n) totaltotal x(i); -Use“;”to hold displays i=i+1: end average total n
Interation Interation Control Control • The while…end loop • The ``for...end'' loop for variable = start:end statements end • Compute the average – Array index started from 1 not 0 – Flow control end with “end” – Use “;” to hold displays
上海交通大学交大密西根 联合学院·一 181 UM-SJTU Joint Institute University of Michigan Shanghal Jiao Tong University Flow Control The switch-case: Unlike C/C++, switch (rem(n,4)==0)+(rem(n,2)==0) MATLAB switch does case 0 M=odd_magic(n) not fall through. case 1 If the first case M=single_even_magic(n) statement is true,the case 2 other case statements M double_even_magic(n) do not execute.So,no otherwise break statements are error('This is impossible') end necessary
Flow Control Flow Control • The switch-case: Unlike C/C++, MATLAB switch does not fall through. • If the first case statement is true, the other case statements do not execute. So, no break statements are necessary