Loren on the Art of MATLAB

Turn ideas into MATLAB

Note

Loren on the Art of MATLAB has been archived and will not be updated.

Switching Things Up

If you have ever used a switch statement in MATLAB and also used it in C, you might have noticed that the two constructs have different semantics.

Contents

switch in C

In C, you often terminate case statements in switch constructs with a break statement to prevent execution of the code in the case that follows. Omitting the break statement causes the code in the following case to execute. The behavior of switch statements in C is sometimes described as fall through.

switch in MATLAB

There are several major differences between switch statements in MATLAB and C.

  • MATLAB does not have fall through behavior in its switch statements and therefore no break statement is typically required for individual case statementss.
  • MATLAB case statements have another feature that C and many other languages do not have. The expression following case need not be scalar-valued, but can combine several expressions by placing the acceptable expressions in a cell array.
  • If you want to specify behavior for switch expressions that don't match any of the case expressions, use the otherwise branch. In C, use default instead.
  • Expressions for case statements can include strings and numeric expressions, not just integer values. Though you have to be careful using non-integral numbers because of round-off, this flexibility can make the intent of your code more obvious instead of seeing a list of numbers.
  • More on switch in MATLAB

    When we originally were designing switch for MATLAB, we examined much of our own C source code, and we found a huge majority of the case statements terminated in break, hence the no fall-through behavior of MATLAB. This makes the switch statement in MATLAB equivalent to an if-elseif construct. To achieve fall-through behavior in MATLAB, you can specify all the relevant expressions in one case and then conditionally compute values within that section of code.

    Do You Use switch Statements?

    I am curious to hear about your experiences using switch statements in MATLAB. Post your thoughts here.




    Published with MATLAB® 7.8


    • print

    Comments

    To leave a comment, please click here to sign in to your MathWorks Account or create a new one.