# 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
.

.

.

otherwise
statement group n

end
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
·disp(‘Northeast’)
case 135
disp(‘Southeast’)
case 225
disp(‘Southwest’)
case 315
di sp (,Northwest”)
otherwise
disp(‘Direction Unknown’)
end

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
max(x)
case sum
total = sum(x)
otherwise
disp (‘You have not entered a proper choice.’)
end
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’ )
otherwise
disp (‘Direction Unknown’)
end