Quantcast

Documentation Center

  • Trial Software
  • Product Updates

switch, case, otherwise

Switch among several cases based on expression

Syntax

switch switch_expression
   case case_expression
      statements
   case case_expression
      statements
    ...
   otherwise
      statements
end

Description

A switch block conditionally executes one set of statements from several choices. Each choice is a case.

An evaluated switch_expression is a scalar or string. An evaluated case_expression is a scalar, a string, or a cell array of scalars or strings. The switch block tests each case until one of the cases is true. A case is true when:

  • For numbers, eq(case_expression,switch_expression).

  • For strings, strcmp(case_expression,switch_expression).

  • For objects that support the eq function, eq(case_expression,switch_expression).

  • For a cell array case_expression, at least one of the elements of the cell array matches switch_expression, as defined above for numbers, strings, and objects.

When a case is true, MATLAB® executes the corresponding statements, and then exits the switch block.

otherwise is optional, and executes only when no case is true.

Examples

Conditionally display different text depending on a value entered at the command line:

mynumber = input('Enter a number:');

switch mynumber
    case -1
        disp('negative one');
    case 0
        disp('zero');
    case 1
        disp('positive one');
    otherwise
        disp('other value');
end
 

Decide which plot to create based on the value of the string plottype:

x = [12, 64, 24];
plottype = 'pie3';

switch plottype
    case 'bar' 
        bar(x)
        title('Bar Graph')
    case {'pie','pie3'}
        pie3(x)
        title('Pie Chart')
        legend('First','Second','Third')
    otherwise
        warning('Unexpected plot type. No plot created.');
end
 

In MATLAB switch blocks, only the first matching case executes:

result = 52;

switch(result)
   case 52
      disp('result is 52')
   case {52, 78}
      disp('result is 52 or 78')
end

This code returns

result is 52

More About

expand all

Tips

  • Unlike the C language switch statement, the MATLAB switch does not fall through. If the first case statement is true, the other case statements do not execute. Do not use a break statement within a switch block.

  • A case_expression cannot include relational operators such as < or > to compare against the switch_expression. To test for inequality, use if-elseif statements.

  • Because MATLAB executes only one case of any switch statement, variables defined within one case are not available for other cases. For example, if your current workspace does not contain a variable x, only cases that define x can use it:

    switch choice
       case 1
          x = -pi:0.01:pi;
       case 2
          % does not know anything about x
    end

See Also

| | |

Was this topic helpful?