Skip to main content
v2026.11,986 entries · CC-BY 4.0

MATLAB switch Statement: Syntax, Examples and Rules

How the MATLAB switch statement matches values, with worked examples for multiple conditions, ranges and several variables, and common errors.

Written and maintained by CASRAI Editorial Board

Published

On this page

The MATLAB switch statement runs one block of code out of several by comparing one expression against a list of known values. It is built from a switch line, one or more case blocks, an optional otherwise block, and a closing end. This page is for analysts and researchers who need to write one correctly, choose between switch and if, and fix the usual mistakes (case sensitivity, ranges, several variables).

What the switch statement is used for in research code

A switch statement tests one value for equality against a set of known values and runs the first matching case. In research scripts this typically means selecting an analysis mode, a file format, an instrument command or a coded category (for example a numeric status code). MathWorks describes switch as a test for equality against a set of known values, and states that you cannot test for inequality between the switch and case values. For ranges and compound conditions, use if/elseif; see our guides to the MATLAB if statement and if-else in MATLAB.

Install or access (official source only)

switch is a keyword of the MATLAB language itself, documented in the core MATLAB reference, so no add-on toolbox is needed to use it. MATLAB is obtained from MathWorks (mathworks.com); your institution may provide a licence. For other MATLAB topics on this site, see MATLAB documentation.

Step-by-step: write a switch statement

Syntax

  1. Start with switch followed by the switch expression. It must be a scalar or a character vector.
  2. Add one case line per value to test. Each case expression is a scalar, a character vector, or a cell array of those.
  3. Optionally add otherwise as the last block. It runs only when no case matches.
  4. Close the whole block with end.
switch code
    case 1
        disp('Idle')
    case 2
        disp('Running')
    case 3
        disp('Stopped')
    otherwise
        disp('Unknown code')
end

With code = 2 this prints Running. With code = 7 no case matches, so otherwise prints Unknown code.

Several values in one case (multiple conditions)

To make one block run for any of several values, give case a cell array. The case matches if at least one element of the cell array matches.

cmd = 'halt';
switch cmd
    case {'stop','halt'}
        disp('Stopping')
    case 'start'
        disp('Starting')
    otherwise
        disp('Unrecognised command')
end

This prints Stopping, because 'halt' is one of the two elements in the first case.

Output and how to read it: the matching rules

How a case is judged to match depends on the type of the switch expression. These rules come from the MathWorks reference page for switch.

Switch expression Case expression A case matches when
Number Scalar number case_expression == switch_expression
Character vector or string Character vector strcmp(case_expression, switch_expression) returns 1
Number or character vector Cell array At least one element of the cell array matches

Two consequences follow. First, MATLAB runs only the first matching case and then exits the block: unlike C, there is no fall-through, so you do not write break. Second, otherwise is optional; if it is absent and nothing matches, the block does nothing.

Switch or if/elseif: a decision table

Your situation Use Why (from the MathWorks documentation)
One value compared with a fixed list of known values switch switch tests equality against a set of known values
Ranges such as score at least 90, or less than 0 if/elseif You cannot test for inequality between switch and case values
Several values should trigger the same action switch with a cell-array case A cell-array case matches if one element matches

Working with ranges (intervals)

Because case only tests equality, an interval cannot be written directly. Either use if/elseif, or reduce the value to a small set of known values first and switch on that. Here the score is converted to its tens digit:

score = 87;
switch floor(score/10)
    case {10, 9}
        grade = 'A';
    case 8
        grade = 'B';
    otherwise
        grade = 'below B';
end
disp(grade)

floor(87/10) is 8, so this prints B.

Working with more than one variable

The switch expression must be a scalar or character vector, so you cannot switch on two variables at once. One approach is to combine them into a single character vector and write the combinations as cases:

mode = 'fast'; level = 1;
key = sprintf('%s-%d', mode, level);
switch key
    case 'fast-1'
        disp('Fast, level 1')
    case {'fast-2','slow-2'}
        disp('Level 2')
    otherwise
        disp('Other combination')
end

This prints Fast, level 1. If the combinations are numerous or depend on comparisons, nested if statements are usually clearer.

Troubleshooting

Symptom Cause and fix
A text case never matches although it looks identical Text cases match through strcmp, which is case-sensitive, and whitespace counts. 'Halt' does not match 'halt'. Normalise first, for example switch lower(strtrim(cmd)).
You expect the next case to run too after a match MATLAB exits the block after the first matching case; there is no fall-through. To share an action between values, list them in one cell-array case.
Problems with an array as the switch expression The switch expression must be a scalar or a character vector. Reduce an array to a scalar before switching.
You wrote case x > 5 and it does not behave as expected Cases test equality, not inequality. Use if/elseif for comparisons, or switch on a derived value as shown above.
Nothing happens for an unexpected value Add an otherwise block so unexpected values are reported rather than silently skipped.

Free alternatives

Option Note
GNU Octave A free, MATLAB-compatible environment with its own documented switch statement. Run your script and compare results rather than assuming every edge case behaves identically. Our if-else guide shows how the two manuals treat conditionals.

FAQ

How do I use a switch statement in MATLAB?

Write switch followed by a scalar or character-vector expression, one case block per value, an optional otherwise block, and end. MATLAB runs the first case that matches and then leaves the block.

How do I test multiple conditions in one MATLAB case?

Put the values in a cell array, such as case {'stop','halt'}. The case matches if at least one element matches the switch expression.

Does MATLAB switch fall through like C?

No. After a case matches, MATLAB runs that case and exits the switch block, so no break statement is needed.

Can a MATLAB switch compare ranges or use greater-than?

Not directly. MathWorks states that you cannot test for inequality between switch and case values. Use if/elseif, or switch on a derived value.

Is the MATLAB switch statement case-sensitive for text?

Yes. Text values are compared with strcmp, which is case-sensitive, so convert with lower or upper first if input may vary.

Sources

The code examples and their outputs were written for this page and follow the rules in these two documentation pages.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about MATLAB switch Statement: Syntax, Examples and Rules

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →