How to Use the switch Statement in MATLAB

By Jim Sizemore, John Paul Mueller

In MATLAB, you can create any multiple alternative selection code needed using the if…elseif statement. However, you have another good way to make selections. A switch statement lets you choose one of a number of options using code that is both easier to read and less time-consuming to type. The result is essentially the same, but the method of obtaining the result is different.

The following steps demonstrate how to use a switch statement.

  1. Click the arrow under the New entry on the Home tab of the MATLAB menu and select Function from the list that appears.

    You see the Editor window.

  2. Delete output_args.

    The example doesn’t provide an output argument, but it does require an input argument.

  3. Change the function name from Untitled to SimpleSwitch.

    The primary function name must match the name of the file.

  4. Change input_args to Value.

    The function receives a value from the caller to use in the decision-making process.

  5. Type the following code into the function between the comment and the end keyword.

    switch Value
     case 1
      disp(‘You typed 1.’);
     case 2
      disp(‘You typed 2.’);
     case 3
      disp(‘You typed 3.’);
     otherwise
      disp(‘You typed something greater than 3.’);
    end

    This code specifically compares Value to the values provided. When Value matches a specific value, the application outputs an appropriate message.

    At times, the input value doesn’t match the values you expect. In such cases, the otherwise clause comes into play. It provides the means for doing something even if the input wasn’t what you expected. If nothing else, you can use this clause to tell the user to input an appropriate value.

  6. Click Save.

    You see the Select File for Save As dialog box. Notice that the File Name field has the correct filename entered for you.

  7. Click Save.

    The function file is saved to disk.

  8. Type SimpleSwitch(1) and press Enter in the Command window.

    You see the following output:

    You typed 1.
  9. Type SimpleSwitch(2) and press Enter in the Command window.

    You see the following output:

    You typed 2.
  10. Type SimpleSwitch(3) and press Enter in the Command window.

    You see the following output:

    You typed 3.
  11. Type SimpleSwitch(4) and press Enter in the Command window.

    You see the following output:

You typed something greater than 3.