0
0
MATLABdata~5 mins

Switch-case statements in MATLAB

Choose your learning style9 modes available
Introduction

Switch-case statements help you choose what to do based on different possible values. It makes your code cleaner and easier to read than many if-else checks.

When you want to run different code depending on a variable's value.
When you have many options to check and want to avoid long if-else chains.
When you want to handle specific cases clearly and separately.
When you want a default action if none of the cases match.
Syntax
MATLAB
switch expression
    case value1
        % code to run if expression == value1
    case value2
        % code to run if expression == value2
    otherwise
        % code to run if no case matches
end

The expression is what you check against each case value.

The otherwise part is optional and runs if no cases match.

Examples
This checks the value of day. If it is 1, it prints Monday; if 2, Tuesday; otherwise, it prints Other day.
MATLAB
switch day
    case 1
        disp('Monday')
    case 2
        disp('Tuesday')
    otherwise
        disp('Other day')
end
You can group multiple values in one case using a cell array like {'red', 'blue'}.
MATLAB
switch color
    case {'red', 'blue'}
        disp('Primary color')
    case 'green'
        disp('Secondary color')
end
Sample Program

This program checks the value of choice. Since it is 3, it prints the message for option 3.

MATLAB
choice = 3;
switch choice
    case 1
        disp('You chose option 1')
    case 2
        disp('You chose option 2')
    case 3
        disp('You chose option 3')
    otherwise
        disp('Invalid choice')
end
OutputSuccess
Important Notes

Each case must be unique; MATLAB matches the first one that fits.

Use otherwise to catch unexpected values and avoid errors.

Summary

Switch-case helps select code to run based on a value.

It is cleaner than many if-else statements.

Use otherwise for default actions.