logo for matrixlab-examples.com
[?] Subscribe To This Site

XML RSS
Add to Google
Add to My Yahoo!
Add to My MSN
Subscribe with Bloglines


Home
Matrixmania Blog
Contact
-> Sitemap <-
Matlab Books
Quick Matlab Guide
Matlab Tutorials
Matlab Examples
Matlab Flow Control
Boolean Algebra
Linear Algebra
Matlab 2D Plots
Matlab 3D Plots
Matlab GUI
Matlab Cookbook I
Matlab Cookbook II
Probability and Stats
Forums and Help
Relevant Links
Fun!
Your own Website?
Terms/Policies
leftimage for matrixlab-examples.com

Switch Statement



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

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.

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


From 'switch statement' to home
From 'switch statement' to 'Matlab Control Flow'


footer for matlab switch statement page