Control Flow in MATLAB
Learn conditionals, switch statements, for and while loops, and array-based logical indexing in MATLAB with Docker-ready GNU Octave examples
Control flow determines the order in which statements execute. MATLAB provides the familiar structured constructs — if/elseif/else, switch/case, for, and while — that you would expect from any procedural language. Because MATLAB is a multi-paradigm language (procedural, object-oriented, and array-based), it gives you both classic branching and looping and a powerful array-oriented alternative.
The array-based heritage matters here. MATLAB was built around matrices, and many problems that would require an explicit loop in C or Java are expressed more naturally — and run faster — using logical indexing and vectorized operations. Idiomatic MATLAB tends to reach for an explicit for loop only when vectorization is awkward.
One important difference from C-style languages: every control block in MATLAB is closed with an explicit end keyword. There are no curly braces and indentation is purely stylistic. There is also no ?: ternary operator — conditional expressions are written with if/else or expressed using logical arrays.
This tutorial covers conditionals, multi-way branching, both loop types with break and continue, and the array-based approach that makes MATLAB distinctive.
Conditionals: if / elseif / else
The if statement evaluates a condition and runs a block when it is true. Note the spelling elseif (one word) and the closing end.
Create a file named control_flow_if.m:
| |
A condition is considered true when it evaluates to a nonzero value. When the condition is an array, the if is true only if every element is nonzero (equivalent to wrapping it in all(...)). This is a common source of surprises for newcomers coming from scalar languages.
Multi-way branching: switch / case
For comparing one value against several possibilities, switch is clearer than a long elseif chain. Unlike C, there is no fall-through, so no break is needed — exactly one matching case runs. A case can also match against several values using a cell array.
Create a file named control_flow_switch.m:
| |
MATLAB’s switch is more flexible than C’s: it works directly on character arrays (strings), and the {'octave', 'scilab'} cell array lets a single case match multiple values.
Loops: for and while
The for loop iterates over the columns of an array — most commonly the range 1:n. The while loop repeats as long as its condition holds. Both support break (exit the loop) and continue (skip to the next iteration).
Create a file named control_flow_loops.m:
| |
The for k = 1:5 form is shorthand: 1:5 builds the row vector [1 2 3 4 5], and the loop variable k takes each column in turn. You can also loop with a step, such as for k = 0:2:10 (0, 2, 4, 6, 8, 10), or even iterate backwards with for k = 5:-1:1.
The MATLAB way: array-based control flow
Here is where MATLAB differs from most languages. Instead of looping over elements to test and modify them, you operate on the entire array at once using logical indexing. A comparison like v > 0 produces a logical array of 1s and 0s, which can then select or assign elements directly.
Create a file named control_flow_vectorized.m:
| |
The expression v(v > 0) reads as “the elements of v where v is greater than zero.” The assignment v(v < 0) = 0 updates all matching elements at once. This style is not just shorter — for large arrays it is significantly faster than an element-by-element loop, because the work runs in optimized, compiled routines. When you find yourself writing a loop in MATLAB, ask whether logical indexing or a built-in vectorized function could do the same job.
Running with Docker
MATLAB is commercial software, so these examples use GNU Octave, a free, MATLAB-compatible alternative. All four scripts run unchanged.
| |
Expected Output
control_flow_if.m:
Grade: C
control_flow_switch.m:
Matrix Laboratory
control_flow_loops.m:
Sum of 1 to 5 = 15
Fruit 1: apple
Fruit 2: banana
Fruit 3: cherry
Odd: 1
Odd: 3
Odd: 5
Odd: 7
control_flow_vectorized.m:
Positive values: [4 7 9]
After clamping negatives to zero: [4 0 7 0 0 9 0]
Signs: [1 0 1 0 0 1 0]
Key Concepts
- Every block ends with
end—if,switch,for, andwhileall close with the explicitendkeyword; there are no curly braces. elseifis one word — writingelse ifstarts a new nestedifthat needs its ownend.switchhas no fall-through — exactly one matchingcaseruns, so nobreakis required, and acasecan match several values via a cell array.ifon an array means “all elements” — a condition that is an array is true only when every element is nonzero, equivalent toall(...).breakandcontinue—breakexits the nearest enclosing loop;continueskips to the next iteration.- No ternary operator — MATLAB has no
?:; useif/elseor express the choice with logical arrays. - Prefer vectorization over loops — logical indexing (
v(v > 0)) and built-in functions usually replace explicit loops and run much faster on large arrays. foriterates over columns —for k = 1:nwalks a range;for k = 5:-1:1counts down, andfor k = 0:2:10steps by 2.
Running Today
All examples can be run using Docker:
docker pull gnuoctave/octave:9.4.0
Comments
Loading comments...
Leave a Comment