Section: Flow Control
switch statement is used to selective execute code
based on the value of either scalar value or a string.
The general syntax for a switch statement is
switch(expression)
case test_expression_1
statements
case test_expression_2
statements
otherwise:
statements
end
The otherwise 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
cell-array of expressions to test against. Note that
unlike C switch statements, the FreeMat switch
does not have fall-through, meaning that the statements
associated with the first matching case are executed, and
then the switch ends. Also, if the switch expression
matches multiple case expressions, only the first one
is executed.
switch expression that tests
against a string input:
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
Now we exercise the switch statements
--> switch_test('root beer')
ans =
<string> - size: [1 4]
food
--> switch_test('red')
ans =
<string> - size: [1 5]
color
--> switch_test('carpet')
ans =
<string> - size: [1 8]
not sure