How to use the switch command in MATLAB

What is a switch command?

The switch command executes a group of several statements where it checks n number of cases that follows the switch command, and if they don't match, it executes the command followed by otherwise.

Explanation

The illustration above explains the working of the switch statement. The program enters the switch statement, which forwards it to the cases; if the switch_expression matches the cases_expression, it executes that case statement. If none of the case expressions matches, it will execute the otherwise statement irrespective of the original statement. A case expression will be valid as follows:

  • If the expression takes a number, case_expression == switch_expression.

  • If it takes characters, strcmp(case_expression ,switch_expression) == 1.

  • If it takes objects that support the eq function, case_expression == switch_expression.

  • If it takes a cell array, one element of case expression should match the switch expression, as it is defined for all kinds above.

Syntax

The syntax for switch, case, and otherwise in Matlab is in the code widget below, which matches the illustration attached above.

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

Program

In the code widget below, we have a set of switch, case, and otherwise statements.

n = input('Enter a number: ');
switch n
case -1
disp('negative one')
case 0
disp('zero')
case 1
disp('positive one')
otherwise
disp('other value')
end

Explanation

  • Line 1: The program takes a number as input.

  • Line 3: It passes to the switch statement.

  • Lines 4–9: The switch_expression is being compared to the case_expressions.

  • Lines 10–11: If the switch_expression doesn't match case_expression, we have an otherwise statement to execute.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved