Find a Guide

Switch Statement in MATLAB

What are they?

In MATLAB, a similar process to if statements are switch statements. In a switch statement, you start out by selecting a variable to check against and then you define cases. Let's take a look at an example of this.

matlab

num = 2;
switch num
    case 1
        disp("num is 1");
    case 2
        disp("num is 2");
    otherwise
        disp("num is not 1 or 2");
end

Now, for switch statements there can be as many cases as needed, and there must always be an otherwise default as well, otherwise an error will occur.

Find a Guide