Getting Started |
switch and case
The switch
statement executes groups of statements based on the value of a variable or expression. The keywords case
and otherwise
delineate the groups. Only the first matching case is executed. There must always be an end
to match the switch
.
The logic of the magic squares algorithm can also be described by
switch (rem(n,4)==0) + (rem(n,2)==0) case 0 M = odd_magic(n) case 1 M = single_even_magic(n) case 2 M = double_even_magic(n) otherwise error('This is impossible') end
Note
Unlike the C language switch statement, MATLAB switch does not fall through. If the first case statement is true, the other case statements do not execute. So, break statements are not required.
|
Flow Control | for |