Page 52 - Basics of MATLAB and Beyond
P. 52
Switch
The basic form of a switch statement is:
switch test
case result1
statements
case result2
statements
.
.
.
otherwise
statements
end
The respective statements are executed if the value of test is equal
to the respective result s. If none of the cases are true, the otherwise
statements are done. Only the first matching case is carried out. If
you want the same statements to be done for different cases, you can
enclose the several result s in curly brackets:
switch x
case 1
disp(’x is 1’)
case {2,3,4}
disp(’x is 2, 3 or 4’)
case 5
disp(’x is 5’)
otherwise
disp(’x is not 1, 2, 3, 4 or 5’)
end
While
The basic form of a while loop is
while test
statements
end
The statements are executed repeatedly while the value of test is
equal to 1. For example, to find the first integer n for which 1+2+···+n
is is greater than 1000:
n=1;
while sum(1:n)<=1000
n = n+1;
end
c 2000 by CRC Press LLC