Beginner

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
% if / elseif / else
score = 78;

if score >= 90
    disp('Grade: A')
elseif score >= 80
    disp('Grade: B')
elseif score >= 70
    disp('Grade: C')
else
    disp('Grade: F')
end

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
% switch / case (works with numbers AND strings)
language = 'matlab';

switch language
    case 'matlab'
        disp('Matrix Laboratory')
    case {'octave', 'scilab'}
        disp('Open-source alternative')
    otherwise
        disp('Unknown language')
end

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
% for loop over a numeric range
total = 0;
for k = 1:5
    total = total + k;
end
fprintf('Sum of 1 to 5 = %d\n', total);

% for loop over the elements of a cell array
fruits = {'apple', 'banana', 'cherry'};
for i = 1:numel(fruits)
    fprintf('Fruit %d: %s\n', i, fruits{i});
end

% while loop with continue (skip) and break (stop)
n = 0;
while n < 10
    n = n + 1;
    if mod(n, 2) == 0
        continue;   % skip even numbers
    end
    if n > 7
        break;      % stop once we pass 7
    end
    fprintf('Odd: %d\n', n);
end

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
% Array-based control flow: logical indexing replaces loops
v = [4 -2 7 0 -5 9 -1];

% Select positive values without writing a loop
positives = v(v > 0);
fprintf('Positive values: %s\n', mat2str(positives));

% Replace every negative value with zero in one statement
v(v < 0) = 0;
fprintf('After clamping negatives to zero: %s\n', mat2str(v));

% Vectorized sign computation (no loop needed)
fprintf('Signs: %s\n', mat2str(sign(v)));

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.

1
2
3
4
5
6
7
8
# Pull the GNU Octave image
docker pull gnuoctave/octave:9.4.0

# Run each example
docker run --rm -v $(pwd):/app -w /app gnuoctave/octave:9.4.0 octave --no-gui --no-window-system control_flow_if.m
docker run --rm -v $(pwd):/app -w /app gnuoctave/octave:9.4.0 octave --no-gui --no-window-system control_flow_switch.m
docker run --rm -v $(pwd):/app -w /app gnuoctave/octave:9.4.0 octave --no-gui --no-window-system control_flow_loops.m
docker run --rm -v $(pwd):/app -w /app gnuoctave/octave:9.4.0 octave --no-gui --no-window-system control_flow_vectorized.m

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 endif, switch, for, and while all close with the explicit end keyword; there are no curly braces.
  • elseif is one word — writing else if starts a new nested if that needs its own end.
  • switch has no fall-through — exactly one matching case runs, so no break is required, and a case can match several values via a cell array.
  • if on an array means “all elements” — a condition that is an array is true only when every element is nonzero, equivalent to all(...).
  • break and continuebreak exits the nearest enclosing loop; continue skips to the next iteration.
  • No ternary operator — MATLAB has no ?:; use if/else or 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.
  • for iterates over columnsfor k = 1:n walks a range; for k = 5:-1:1 counts down, and for k = 0:2:10 steps by 2.

Running Today

All examples can be run using Docker:

docker pull gnuoctave/octave:9.4.0
Last updated:

Comments

Loading comments...

Leave a Comment

2000 characters remaining