Section 7.6 The switch-case
command
The
switch-case
command in MATLAB is a more evolved version of the C switch command. For one, no break statements are needed at the end of each case as only the case that is entered is actually executed (and not all of the ones following it). Furthermore, multiple options can be combined into one case. And finally, the switch expression can be a scalar or a string.A switch statement conditionally executes one set of statements from several choices. Each choice is given by a case statement. Here is the syntax:
switch expression % can be a scalar or string
case value1
commands
...
case {value2a, value2b, value2c} % only one needs to match
commands
...
otherwise % optional
commands
...
end % only first match is executed,
% i.e., there is a built-in break
If there is more than one match, only the first one is executed.
Here is an example:
clear all; close all;
letter = input('Enter a letter (A, J, a):', 's');
switch letter
case 'J'
disp('J')
case {'A','a'}
disp('A')
otherwise
disp('Did not find your letter!')
end
Now, let’s compare the syntax of switch statements in MATLAB and C.
MATLAB syntax:
C-Programming syntax:
switch expression
case value1
commands
...
case {value2a, value2b, value2c}
commands
...
otherwise
commands
...
end
switch (expression) {
case const1:
statements1;
break;
case const2:
statements2;
break;
...
default:
statements;
}