Programming and Data Types    

switch

switch executes certain statements based on the value of a variable or expression. Its basic form is

This block consists of:

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 can handle multiple conditions in a single case statement by enclosing the case expression in a cell array.


  if, else, and elseif while