An interactive introduction to MATLAB

(Jeff_L) #1

a advanced topic: the switch statement


Theswitchstatement inMATLABis similar to theif,else, andelseif
statements, and provides a method of executing different bits of code dependent
on whichcaseis true. Typically you would use aswitchstatement in prefer-
ence toif,else, andelseifstatements if you have specific cases (values of
a variable) to test. Listing A.1 presents the syntax of theswitchstatement.
Listing A.1: Syntax of aswitchstatement
1 switch switch_expression
2 casecase_expression1
3 statements
4 casecase_expression2
5 statements
6 casecase_expression3
7 statements
8 ...
9 end


Comments:


  • Line 1 contains theswitchcommand followed by the expression to be
    compared to the various cases.

  • Lines 2–7 contain the different cases and their corresponding statements
    to be executed.

  • If the switch expression matches one of the case expressions then the state-
    ments underneath thatcasewill be executed and theswitchstatement
    will end.


Listing A.2 presents a simple example of the usage of aswitchstatement.
MATLABhas a built-in function calledcomputerthat returns a string of
text corresponding to the operating system that you are running. By analysing
this string you can print out some information about the operating system.
Copy and paste the example into a new script file, and run it to see the results
for yourself.

67
Free download pdf