File Exchange Pick of the Week

January 2nd, 2008

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

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.

13 Responses to “MATLAB Basics: ‘Switch case’ vs. ‘If elseif’”

  1. Robert McCormick replied on :

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

  2. Doug replied on :

    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

  3. Phil replied on :

    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.

  4. Doug replied on :

    Phil,

    Excellent example. Thank you!

    Doug

  5. Jon replied on :

    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

  6. Phillip Diedrick replied on :

    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

  7. Doug replied on :

    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

  8. Rick Stauf replied on :

    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

  9. Rick Stauf replied on :

    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.

  10. Yuri replied on :

    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

  11. Doug replied on :

    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

  12. Carly replied on :

    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.

  13. Doug replied on :

    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

Leave a Reply

Wrap code fragments inside <pre> tags, like this:

<pre class="code">
a = magic(3);
sum(a)
</pre>

If you have a "<" character in your code, either follow it with a space or replace it with "&lt;" (including the semicolon).


Bob, Brett & Jiro share their favorite user-contributed submissions from the File Exchange.

  • Zach: Hi Doug and Les, I didn’t have a lot of time to mess with this, but I did find a work-around. I plotted...
  • hamed: k
  • Les: @Zach This isn’t exactly what you are looking for but at least it puts all three parameters on the same...
  • Zach: Thanks for your suggestions Doug. I’ll give that a shot and see what happens. I’ve seen many of...
  • Doug: @Zach, I would say to use plotYYY, because that is close to what you want, but using depth as Y makes sense....
  • Doug: @Teja, I think this will work: http://www.mathworks .com/access/helpdesk /help/techdoc/ref...
  • Gify: merry christmas :) nice christmas tree! Regards, Janet Gify
  • Teja: Dear Doug Is there anyway to plot a surface from nonuniform data without meshgrid and griddata? Basically i...
  • Zach: I’m working with geophysical data, so I’d like to produce a depth profile. The y-axis would be...
  • Doug: @Ashok First, please do not use variable names that are MATLAB commands (std and mean). Second, p(j) should be...

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