93
MATLAB switch
The switch is another type of conditional statement and executes one of the group of several statements.
- If we want to test the equality against a pre-defined set of rules, then the switch statement can be an alternative of the if statement.
Syntax:
Flowchart of Switch statement
Following are the points while using switch in MATLAB:
Similar to if block, the switch block tests each case until one of the case_expression is true. It is evaluated as:
- case & switch must be equal for numbers as- case_expression == switch_expression.
- For character vectors, the result returned by the strcmp function must be equal to 1 as – strcmp(case_expression, switch_expression) == 1.
- For object, case_expression == switch_expression.
- For a cell array, at least one of the elements of the cell array in case_expression must match switch_expression.
- switch statement doesn’t test for inequality, so a case_expression cannot include relational operators such as < or > for comparison against the switch_expression.
Example1:
Output:
enter a number: 4 Thursday
Example2:
Next TopicMATLAB Loops