Graphics Programs Reference
In-Depth Information
function y = count(x)
switch x
case 1
y = 'one';
case 2
y = 'two';
otherwise
y = 'many';
end
Here the switch statement evaluates the input x and then execution of the
M-file skips to whichever case statement has the same value. Thus if the
input x equals 1 , then the output y is set to be the string 'one' , while if x is
2 ,then y issetto 'two' .Ineachcase,onceMATLABencountersanother case
statement or since an otherwise statement, it skips to the end statement,
so that at most one case is executed. If no match is found among the case
statements, then MATLAB skips to the (optional) otherwise statement, or
else to the end statement. In the example above, because of the otherwise
statement, the output is 'many' if the input is not 1 or 2 .
Unlike if , the command switch does not allow vector expressions, but it
does allow strings. Type help switch to see an example using strings. This
feature can be useful if you want to design a function M-file that uses a string
input argument to select among several different variants of a program you
write.
Thoughstrings cannot be compared withrelational operators suchas ==
(unless they happen to have the same length), you can compare strings in an
if or elseif statement by using the command strcmp . Type help strcmp
to see how this command works; for an example of its use in conjunction
with if and elseif , enter type hold .
More about Loops
In Chapter 3 we introduced the command for , which begins a loop — a
sequence of commands to be executed multiple times. When you use for ,
you effectively specify the number of times to run the loop in advance (though
this number may depend for instance on the input to a function M-file). Some-
times you may want to keep running the commands in a loop until a certain
condition is met, without deciding in advance on the number of iterations. In
MATLAB, the command that allows you to do so is while .
Search WWH ::




Custom Search