| Programming and Data Types | ![]() |
switch executes certain statements based on the value of a variable or expression. Its basic form is
switchexpression (scalar or string)casevalue1statements %Executes ifexpressionisvalue1casevalue2statements %Executes ifexpressionisvalue2. . . otherwisestatements %Executes ifexpressiondoes not% does not match any case end
switch followed by an expression to evaluate.
case groups. These groups consist of the word case followed by a possible value for the expression, all on a single line. Subsequent lines contain the statements to execute for the given value of the expression. These can be any valid MATLAB statement including another switch block. Execution of a case group ends when MATLAB encounters the next case statement or the otherwise statement. Only the first matching case is executed.
otherwise group. This consists of the word otherwise, followed by the statements to execute if the expression's value is not handled by any of the preceding case groups. Execution of the otherwise group ends at the end statement.
end statement.
switch works by comparing the input expression to each case value. For numeric expressions, a case statement is true if (value==expression). For string expressions, a case statement is true if strcmp(value,expression).
The code below shows a simple example of the switch statement. It checks the variable input_num for certain values. If input_num is -1, 0, or 1, the case statements display the value on screen as text. If input_num is none of these values, execution drops to the otherwise statement and the code displays the text 'other value'.
switch input_num case -1 disp('negative one'); case 0 disp('zero'); case 1 disp('positive one'); otherwise disp('other value'); end
switch can handle multiple conditions in a single case statement by enclosing the case expression in a cell array.
switch var case 1 disp('1') case {2,3,4} disp('2 or 3 or 4') case 5 disp('5') otherwise disp('something else') end
| if, else, and elseif | while | ![]() |