switch, case, otherwise

switch expression
    case value_1
        block_1
    case value_2
        block_2
    otherwise
        block_3
end

When this statement runs, expression is evaluated first; when its result equals1 the value_i of some case, that case’s block runs. If none of the value_i match, the otherwise block runs. The statement is equivalent to the following elseif:

x = expression;
if isequal(x,value_1)
    block_1
elseif isequal(x,value_2)
    block_2
else
    block_3
end
  • Like elseif, the otherwise clause is optional; when present, the conditional is exhaustive
  • There may be any number of case clauses, all peer and mutually exclusive
  • Here expression must return a scalar or char vector, in contrast with the elseif form, where the conditional expression may be any array
  • Notably, value_i may be a cell array; in that case block_i runs whenever any cell in value_i equals expression

Footnotes

  1. In my experiments, isequal is the function that best captures the notion of “equality” used here.