logo for matrixlab-examples.com
leftimage for matrixlab-examples.com

Switch Statement

Another way to branch in programming

The switch statement in Matlab executes groups of instructions or statements based on the value of a variable or expression.
   



It's a type of selection control statement that exists in most modern imperative programming languages.

The keywords case and otherwise delineate the groups. Only the first matching case is executed. There must always be an end to match the switch.

how to use a switch-select case block in codes

The syntax is
:

switch switch_expr
  case case_expr
    statement
    ...

  case {case_expr1,case_expr2,case_expr3,...}
    statement
    ...

  otherwise
    statement
    ...
end


MATLAB switch does not fall through. If the first case statement is true, the other case statements do not execute. So, break statements are not required.


Example:



To execute a certain block of code based on what the string 'color' is set to:

color = 'rose';

switch lower(color)
   case {'red', 'light red', 'rose'}
      disp('color is red')

   case 'blue'
      disp('color is blue')

   case 'white'
      disp('color is white')

   otherwise
      disp('Unknown color.')
end



Matlab answer is:

color is red

 

footer for matlab switch statement page