case - Execute block of code if condition is true

Syntax

switch switch_expr
 case case_expr
    statement, ..., statement
  case {case_expr1, case_expr2, case_expr3, ...}
    statement, ..., statement
  otherwise
    statement, ..., statement
end

Description

case is part of the switch statement syntax which allows for conditional execution. A particular case consists of the case statement itself followed by a case expression and one or more statements.

case case_expr compares the value of the expression switch_expr declared in the preceding switch statement with one or more values in case_expr, and executes the block of code that follows if any of the comparisons yield a true result.

You typically use multiple case statements in the evaluation of a single switch statement. The block of code associated with a particular case statement is executed only if its associated case expression (case_expr) is the first to match the switch expression (switch_expr).

To enter more than one case expression in a switch statement, put the expressions in a cell array, as shown above.

Examples

To execute a certain block of code based on what the string, method, is set to,

method = 'Bilinear';

switch lower(method)
   case {'linear','bilinear'}
      disp('Method is linear')
   case 'cubic'
      disp('Method is cubic')
   case 'nearest'
      disp('Method is nearest')
   otherwise
      disp('Unknown method.')
end

Method is linear

See Also

switch, otherwise, end, if, else, elseif, while

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS