1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
<TITLE>SWITCH Switch statement
</TITLE>
</HEAD>
<BODY>
<H2>SWITCH Switch statement
</H2>
<P>
Section: <A HREF=sec_flow.html> Flow Control </A>
<H3>Usage</H3>
The <code>switch</code> statement is used to selective execute code
based on the value of either scalar value or a string.
The general syntax for a <code>switch</code> statement is
<PRE>
switch(expression)
case test_expression_1
statements
case test_expression_2
statements
otherwise
statements
end
</PRE>
<P>
The <code>otherwise</code> clause is optional. Note that each test
expression can either be a scalar value, a string to test
against (if the switch expression is a string), or a
<code>cell-array</code> of expressions to test against. Note that
unlike <code>C</code> <code>switch</code> statements, the FreeMat <code>switch</code>
does not have fall-through, meaning that the statements
associated with the first matching case are executed, and
then the <code>switch</code> ends. Also, if the <code>switch</code> expression
matches multiple <code>case</code> expressions, only the first one
is executed.
<H3>Examples</H3>
Here is an example of a <code>switch</code> expression that tests
against a string input:
<P>
<PRE>
switch_test.m
function c = switch_test(a)
switch(a)
case {'lima beans','root beer'}
c = 'food';
case {'red','green','blue'}
c = 'color';
otherwise
c = 'not sure';
end
</PRE>
<P>
Now we exercise the switch statements
<PRE>
--> switch_test('root beer')
ans =
food
--> switch_test('red')
ans =
color
--> switch_test('carpet')
ans =
not sure
</PRE>
<P>
</BODY>
</HTML>
|