TExcelTAD
Home › MATLAB / Octave › switch Statements

switch Statements

When you compare one value against a list of possibilities, a switch statement is cleaner than a long if/elseif chain. MATLAB's switch works with numbers and text, and doesn't need break statements: only the matching case runs.

matlab · try it yourself
day = 6;
switch day
    case 1
        name = 'Monday';
    case 2
        name = 'Tuesday';
    case {3, 4, 5}
        name = 'Midweek';
    case {6, 7}
        name = 'Weekend';
    otherwise
        name = 'Invalid day';
end
disp(name)
Weekend

How it works

  • The expression after switch is evaluated once.
  • Each case is compared with it in order; the first match runs and the rest are skipped.
  • A case can list several values in a cell array {...}; it matches if any of them matches.
  • otherwise (optional) runs when no case matches.
  • Unlike C or Java, there is no fall-through and no break.

Switching on text

Text comparison in switch behaves like strcmp: the whole text must match exactly, including case. Normalise the input with lower or upper first if case shouldn't matter:

matlab · try it yourself
commands = {'start', 'STOP', 'Pause', 'jump'};
for k = 1:numel(commands)
    cmd = commands{k};
    switch lower(cmd)
        case 'start'
            msg = 'Starting engine';
        case {'stop', 'halt'}
            msg = 'Stopping';
        case 'pause'
            msg = 'Pausing';
        otherwise
            msg = sprintf('Unknown command "%s"', cmd);
    end
    disp(msg)
end
Starting engine
Stopping
Pausing
Unknown command "jump"

Ranges need if

A case compares for equality; it can't test a range like "between 10 and 20". For ranges use if/elseif. (You may meet the trick switch true with logical conditions as cases; it works, but it hides the intent, so prefer if.)

A switch on a computed category is often a neat alternative:

matlab · try it yourself
bmiValues = [17.2 22.5 27.9 33.1];
for bmi = bmiValues
    band = sum(bmi >= [18.5 25 30]);   % 0, 1, 2 or 3 thresholds passed
    switch band
        case 0
            label = 'underweight';
        case 1
            label = 'normal';
        case 2
            label = 'overweight';
        otherwise
            label = 'obese';
    end
    fprintf('BMI %.1f: %s\n', bmi, label);
end
BMI 17.2: underweight
BMI 22.5: normal
BMI 27.9: overweight
BMI 33.1: obese

bmi >= [18.5 25 30] compares the value with all three thresholds at once, and sum counts how many were passed.

A small calculator

matlab · try it yourself
ops = {'+', '-', '*', '/', '^', '%'};
a = 12;
b = 4;
for k = 1:numel(ops)
    switch ops{k}
        case '+'
            r = a + b;
        case '-'
            r = a - b;
        case '*'
            r = a * b;
        case '/'
            r = a / b;
        case '^'
            r = a ^ b;
        otherwise
            fprintf('%d %s %d: unsupported operator\n', a, ops{k}, b);
            continue
    end
    fprintf('%d %s %d = %g\n', a, ops{k}, b, r);
end
12 + 4 = 16
12 - 4 = 8
12 * 4 = 48
12 / 4 = 3
12 ^ 4 = 20736
12 % 4: unsupported operator

continue skips to the next loop iteration (see the loops lessons). Note that fprintf prints the % operator correctly here because it is passed as a %s argument, not as part of the format string.

switch vs if

Use switch when Use if when
Comparing one value with fixed constants Testing ranges or inequalities
Matching text commands or options Conditions involve several variables
Several values share one action (case {a, b}) You need short-circuit logic

Test yourself

How do you make one case match either 'y' or 'yes'?

  1. case 'y' || 'yes'
  2. case {'y', 'yes'}
  3. case ['y' 'yes']
  4. Write two cases with fall-through

What does MATLAB's switch do after the matching case runs?

  1. Falls through to the next case
  2. Jumps to the end of the switch
  3. Runs otherwise too
  4. Repeats the switch

With s = 'YES', which case matches in switch s?

  1. case 'yes'
  2. case 'YES'
  3. Both
  4. Neither