MATLAB - The switch Statement

Advertisements


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

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.

The otherwise block is optional and executes only when no case is true.

Syntax

The syntax of switch statement in MATLAB is:

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

Example

Create a script file and type the following code in it:

grade = 'B';
   switch(grade)
   case 'A' 
      fprintf('Excellent!\n' );
   case 'B' 
       fprintf('Well done\n' );
   case 'C' 
      fprintf('Well done\n' );
   case 'D'
      fprintf('You passed\n' );
   
   case 'F' 
     fprintf('Better try again\n' );
     
   otherwise
     fprintf('Invalid grade\n' );
   end

When you run the file, it displays:

Well done
Your grade is  B


Advertisements
Advertisements