The switch Structure Matlab Help

The switch Structure
The switch structure provides an alternative to using the if, elseif, and else commands. Anything programmed using switch can also be programmed using it structures. However, for some applications the switch structure is
more readable than code using the~if structure. The syntax is .
switch input expression (scalar-or string)
case value 1
statement group 1
case values
statement group 2



statement group n

The input expression is compared to each case value. If they are the same, then the statements following that case statement are executed and processing continues with any statements after the end statement, If the input expression is a string, then it is equal to the case value if strcmp returns a value of I (true).
Only the first matching case is executed. If no match occurs, the statements

following the otherwise statement are executed. However, the otherwise statement is optional. If it is absent, execution continues with the statements following the end statement into match exists. Each case value statement must be on a single line.
For example, suppose the variable angIe has an integer value that represents an angle measured in degrees from North. The following switch block displays the point on the compass that corresponds to that angle .
.switch angle
case 45
case 135
case 225
case 315
di sp (,Northwest”)
disp(‘Direction Unknown’)

The use of a string variable for the input expression can result in very readable programs. For example, in the following code the numeric vector x has values, and the user enters the value of the string variable response; its intended values are min, max, or sum. The code then either finds the minimum or maximum value
of x or sums the elements of x, as directed by the user.
t = [0:100]; x = exp(-t Y.*sin(t);
response = input (‘Type min, max , or s-um.’,”s”)
response = lower(‘response’);
switch response
case min
case sum
total = sum(x)
disp (‘You have not entered a proper choice.’)
The switch statement can handle multiple conditions in a single case statement by enclosing the case value in a cell array. For example. the following switch block displays the corresponding point on the compass, given the integer angle measured from North.
switch angle
case {O,360}
disp (‘North’)

case {-ISO, ISO}
disp (r South’ )
case {-270,90}
disp (,East’ )
case {-90,270}
disp (‘West’ )
disp (‘Direction Unknown’)

Test Your Understanding
T4.6-1 Write a program using the switch structure to input one angle, whose
value may be 45, -45, 135, or -135°, and display the quadrant 1,
or 4) containing the angle.

One of the chapter problems for Section 4.4 (Problem 18) asks you to write a program to determine whether or not a given year is a leap year.

Posted on July 27, 2015 in Programming with MATLAB

Share the Story

Back to Top
Share This