File Exchange Pick of the Week

MATLAB Basics: ‘Switch case’ vs. ‘If elseif’ 28

Posted by Doug Hull,

This three minute video takes a look at the “Switch case” flow control statement and contrasts it with the more familiar “If elseif” flow control statement.

Often times, people will use an “If elseif” statement where a “Switch case” statement is going to be cleaner and easier to understand and maintain.

Video Content

Find the files here.
PodCast here

Other videos have been gathered here:
http://blogs.mathworks.com/pick/category/video/

Other MATLAB Basics posts have been gathered here:
http://blogs.mathworks.com/pick/category/matlab-basics/

As a cool little post script: At most places you celebrate the 100th something or other, but since this is a software company I feel I should celebrate the 64th video (2^6) and as I post this I see that it is the 18128th file on the File Exchange capturing the next power of two in the last three digits.

28 CommentsOldest to Newest

Ok thanks Doug for this, but which of if-else and switch-case is computationally more efficient??

Robert,

I tested, and it really depended on the number of iterations. For reasonable numbers of iterations it did not seem to matter. TIC TOC and the profiler can be a big help here.

When asked about these kinds of things, I often say “Just code it”, run the profiler and see where the problems are. There is no need to try and optimize one second off of this kind of statement when there is some calculation that take 300 seconds anyways. Write your code clean and maintainable, then modify the slow bits as they appear.

Doug

Doug,
I often see programmers rely on the ‘if elseif’ chain in order to determine if a variable (n) falls into one of several ranges. MATLAB help is not clear on how this is done using the switch statement, but it is possible by comparing the logical value true against each of the range evaluations…

n=80
switch logical(true)
case n>100, disp(‘high’);
case n>50, disp(‘moderate’);
case n>0, disp(‘low’);
otherwise disp(‘invalid’);
end;

Again, this is a much more elegant solution than the ‘if elseif’ alternative.

Phil.

Phil,

Thanks for that! Exactly what I was looking for. MATLAB help does kind of fail to explain how to use logicals with a switch statement.

Jon

I want to use the switch/case for the following. I want to prompt the user to input one the following strings: triangle, square,pentagon or hexagon. Depending which figure you input the program will then calculate the sum of the interior angles of the figure using (n-2)(180). I tried the following and I’m prompted with an error message. Here is my code.
clear;
clc;
n=input(‘Please input the figure:’)
switch n
case (‘triangle’)
n=3;
sum=(n-3).*(180)
case (‘square’)
n=4;
sum=(n-3).*(180)
case(‘pentagon’)
n=5;
sum=(n-3).*(180)
case (‘hexagon’)
n=6;
sum=(n-3).*(180)
end
Please could you assist me.
Thanks

Phillip,

You need this for your input statement:

n=input(‘Please input the figure:’,’s’)

This interprets whatever is typed as a string. Without that switch, MATLAB is taking what you type and interpreting it and thus looks for a function called “triangle” or whatever and does not find it.

Doug

Doug,

I’m looking for a GoTo function for Matlab. I have an efficient search routine that I like to use in a number of areas that requires GoTos. Is there anything like this in matlab procedures?

Thank you for your help,
Rick

Never Mind, I found a more efficient way to do it. Instead of searching the time area I simply multiply the time by the delta time to acquire the index number in the array. Thanks for your web tutorials. They are very helpful.

I’ve got a question about this string. Before this is a whole m-script with the needed parameterinputs, and there is no problem with them. It’s this particular part, where i need to get the 2000>REwater>3000 to work. But I believe this is not a right command for a Matlab m-file. Do you know an alternative to get REwater be unknown when the Reynoldsnumber is larger than 2000 but less than 3000?
Thanks in advance!

REwater=(roowater*v*D)/etawater
if REwater3000
disp(‘The liquid is turbulent’)
elseif 2000>REwater<3000
disp(‘The liquid of water is unknown, laminair and turbulent’)
end

I think instead of
if (x < y < z)

you want

if (x < y) & (y < z)

The first construct could be done with numbers like this:

>> 0 < 0.5 < 1

ans =

0

(I suspect you expected the statement to be true!)

Which has an implied parenthesis here:

(0 < 0.5) < 1

Since (0 < 0.5) evaluates to true (1) this means
1 < 1

Which evaluates to false (0)

Try my construct:

>> (0 < 0.5) & (0.5 < 1)

ans =

1

And I think you will get what you were expecting.

-Doug

Do the switch/case commands go in the function file or the script file.

Is there a way to automatically do the switch command or do you have to ask the user to input the value that you want to switch.

Carly,

Switch/case can be used in functions or scripts.

The switch command can work on any variable, not just one put in by the user.

Doug

Is there a way to do a switch statement with strings without comparing case or only comparing the first couple letters? Like how there are the different functions strcmp, strncmp, strncmpi or do you have to perform one of those functions every time?

Thanks,
Nicole

Also, I am doing hundreds of thousands of iterations so is a switch statement faster than all the ifelse statements?

@Nicole,

I don’t know, but one quick test is worth a thousand expert opinions! :)

I would first get the code working and then profile to find the bottle necks. They are rarely where you expect them.

Doug

Doug, thank you for this example, i’m starting to learn matlab and i want to use the switch in my program but i have my switch inside a while that is itself inside a for something like this:

n=2;
for i=1:n,
disp(‘types of things’)
disp(‘1 – thing one’)
disp(‘2 – thing two’)
disp(‘3 – thing 3′)
disp(‘4 – thing 4′)
opcomb=input(strcat (‘what’s the number ‘,num2str(i),’thing:’,32));
while ((opcomb ~=1)|(opcomb~=2)|(opcomb~=3)||(opcomb~=4))
switch opcomb
case 1
combst(i)= 1;
case 2
combst(i)=2;
case 3
combst(i)=3;
case 4
combst(i)=4;
otherwise
disp(‘wrong answer’)
opcomb=input(strcat (‘what’s the number ‘,num2str(i),’thing:’,32));
end
end
end

what its doing is after choosing in the first opcomb and then entering the switch it doesnt “come out”…i’m at a loss as to where my problem is, if it’s in the switch or in the conditions i set in whyle.
thank you in advance

@Ricardo,

Your code simplified looks like this:


While 1
   do something
end

The boolean in the while statement is ALWAYS true, that is why you never leave the loop.

Doug

I have a vector and i want each element of the vector to be raised to a power depending on weather the element is greater or less than a fixed number. I tired using if statement but it is not working. Please can you help the fo
llowing is how i wrote the code:

d = 1:0.1:2
for h = 1:length(d)
if d(h)(1,:)&it 1.500
alpha = 2
else
alpha = 4
end
k(h)(1,:) = d(h)(1,:)^2
end

Thank you, your help will be much appreciated.

Kwashie,

The way you’ve written your code, the value alpha only depends on whether or not the last element of d is less than 1.5. Anyway, using “logical indexing” (you can search the documentation for this term for more information if you’re interested) you can operate on a subset of the elements all at once.

d = 1:0.1:2;
% Create a "logical mask"
smallEnough = d < 1.5;
% Raise all elements of d to the 3rd power
k = d.^3;
% Square those elements that are "small enough" using the mask
k(smallEnough) = d(smallEnough).^2;

If you want alpha to be a vector the same size as d you can do what I did above (predefine it to be a vector of the same size as d with a “default” value then fill in certain elements to override that default) or you can do something slightly different:

alpha = zeros(size(d));
alpha(smallEnough) = 2;
alpha(~smallEnough) = 4;

Note that I negated the smallEnough mask to set elements of alpha corresponding to those elements of d that were NOT smallEnough to 4. You can also AND (&) or OR (|) those logical masks together to form more complicated masks for use with logical indexing.

Hey everyone!
It was so interesting to read this article, I found out a lot of interesting things!

Hi there!
Just wanted to thank you for such an amazing post you shared! It was so useful and helpful for me!

can we go for two conditions in switch case, i mean to say, val1, and val2, with an and operation. ot can we easily don usinf if, ifelse, if elseif else. but it is very expensive… can this we done using switch-case statements..

thanks for the very nice video…

Rushikesh Borse

I have a vector like kwashie’s but a bit more complex

<d = 1:0.1:2
for h = 1:length(d)
if d(h)(1,:)&it 1.500
alpha = d (h) + 2
else
alpha = d (h) + 1
end
k(h)(1,:) = d(h)(1,:)^2
end

This gives an error, how can I use a logical mask for this
Thank you, your help will be much appreciated.

Hello, Doug, Kwashie and Stephen.
Please how do you use logical indexing on an array for the case where the condition is a function and not a constant. As in:

d = 1:0.1:2
for h = 1:length(d)
if d(h)(1,:)&it 1.500
alpha = sin (d)
else
alpha = cos (d)
end
k(h)(1,:) = d(h)(1,:)^2
end

I have a problem like that in my project for an array of 1000 elements and thus can not do it for each element and this code will only work for the last element in the array as in Kwashie’s case.

Thank you very much.

These postings are the author's and don't necessarily represent the opinions of MathWorks.