Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 45 ยท Programming

if, switch and Loops

Learn MATLAB and Octave control flow: if/elseif, switch with strings and cells, for loops over columns, while, break, continue and why loops can be slow.

So far each command ran once, top to bottom. Real programs need to make decisions and repeat work. MATLAB and Octave give you the usual tools: if to choose, switch to pick among many cases, and for and while to repeat. Their syntax is cleaner than in many languages because blocks end with the word end instead of braces.

There is one twist specific to this language. Because everything is a matrix, a condition can be a whole array, and a for loop walks over the columns of whatever you give it. Learning both rules now saves a lot of confusion later.

MATLAB and Octave code on this page is read-only, since neither is installed on the site. Each runnable example is a Python stand-in that follows the same logic and explains the differences.

Four building blocks

if Run code only when a condition holds.
switch Choose one branch by value.
for Repeat once per column.
while Repeat until a condition fails.
1 / 2

if, elseif and else

A conditional starts with if, may include any number of elseif branches and an optional else, and closes with end. No parentheses are required around the condition, though people often add them:

MATLAB
score = 73;
if score >= 90
    grade = 'A';
elseif score >= 70
    grade = 'B';
else
    grade = 'C';
end
disp(grade)       % B

The comparison operators are ==, ~= (not equal), <, >, <= and >=. Octave also accepts !=, but ~= works in both. Combine conditions with && (and) and || (or). These short-circuit: the right side runs only when needed, which makes isfield(s, 'x') && s.x > 0 safe.

The single & and | operate element by element on arrays. Use them for array masks (see logical indexing) and use the double forms in if and while conditions.

Conditions on arrays

An if on an array is true only when all elements are nonzero, and an empty array counts as false:

MATLAB
x = [3 5 8];
if x > 2          % all three are greater than 2
    disp('all large')
end
if x > 4          % 3 > 4 is false, so the whole test is false
    disp('never shown')
end
if any(x > 4)     % any() asks "is at least one true?"
    disp('some large')
end

Spell the intent out with all and any so readers do not have to remember the rule. Floating-point numbers deserve care too: compare with a tolerance, such as abs(a - b) < 1e-10, rather than a == b.

Python Choosing a grade, and any/all

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line shows why tolerances matter: 0.1 + 0.2 is not exactly 0.3 in binary floating point, so the direct comparison prints False while the tolerance test prints True.

switch

When one variable decides among many outcomes, switch is tidier than a pile of elseifs. Each case is compared with == for numbers and with strcmp for text:

MATLAB
command = 'stop';
switch command
    case 'go'
        disp('moving')
    case {'stop', 'halt'}        % a cell matches any of its entries
        disp('stopping')
    otherwise
        disp('unknown')
end
% stopping

Three things to note. A case that holds a cell array matches if the value equals any item in it. Cases do not fall through as in C, so there is no break. And MATLAB runs the first matching case only. The default branch is otherwise.

for loops

for takes a loop variable and a range, and runs the body once per value. The colon operator makes the range:

MATLAB
total = 0;
for k = 1:5
    total = total + k;
end
total              % 15
for k = 10:-3:1    % 10, 7, 4, 1
    fprintf('%d ', k);
end

Here is the twist: the loop variable takes one column at a time of the matrix you give it. For a row vector each column is a single number, so it looks normal. For a matrix, each iteration receives a full column vector:

MATLAB
M = [1 2 3; 4 5 6];
for col = M
    disp(col')       % prints [1 4], then [2 5], then [3 6]
end

If you need row-by-row or element-by-element access, loop over an index instead: for r = 1:size(M, 1) and then use M(r, :). Loop over a cell array with for k = 1:numel(c) and read c{k}, because a plain for item = c gives you a 1-by-1 cell, not its contents.

Python Looping over columns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

NumPy normally walks rows, so the stand-in transposes M to mimic MATLAB's column walk. Notice that range(10, 0, -3) stops before 0, exactly like 10:-3:1 stops at 1.

while, break and continue

while repeats as long as its condition is true. Use it when you do not know the number of passes in advance, for example when iterating until a value converges:

MATLAB
x = 100;
steps = 0;
while x > 1
    x = x / 2;
    steps = steps + 1;
end
steps              % 7

Two keywords change the flow inside any loop. break leaves the loop entirely. continue skips the rest of this pass and starts the next one. A while true loop with a break inside is the usual way to write "repeat until done".

MATLAB
for k = 1:10
    if mod(k, 2) == 0
        continue          % skip even numbers
    end
    if k > 7
        break             % stop completely
    end
    fprintf('%d ', k);    % prints 1 3 5 7
end

Be careful with while conditions that never become false. In MATLAB press Ctrl+C to stop a runaway loop (the same works in Octave).

Python while, break and continue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first loop halves 100 seven times (100 to 0.78125), the same count as the MATLAB example. The last loop follows a classic number sequence that eventually reaches 1.

Why loops can be slow

MATLAB and Octave are fastest when one command processes a whole array, because the work then happens in optimized compiled code. A loop that does a tiny task per pass spends most of its time on interpreter overhead. Compare:

MATLAB
% loop version
total = 0;
for k = 1:1000000
    total = total + k^2;
end

% vectorized version, usually far faster
total = sum((1:1000000).^2);

Modern MATLAB has a just-in-time compiler that narrows the gap, and Octave's interpreter is slower for loops, so the difference is largest in Octave. That does not mean "never loop". Loops are fine when each pass does real work, when passes depend on earlier ones, or when the loop has few iterations. See Vectorization for how to convert the others.

If you build an array inside a loop, preallocate it first with zeros or cell, for example out = zeros(1, n). Growing an array one element per pass forces repeated reallocation.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does if [1 1 0] do?

    An if condition on an array is true only when every element is nonzero. Use any() if you want 'at least one'.
  2. 2. What does for c = [1 2; 3 4] assign to c on the first pass?

    A for loop walks over the columns of its range, so the first value is the first column [1; 3].
  3. 3. In case {'stop', 'halt'}, when does the case match?

    A cell array in a case lists alternatives. The case matches if the switch value equals any of its entries.
  4. 4. Which operator should you use between two scalar conditions in an if statement?

    The double operators && and || short-circuit and are meant for scalar conditions. Single & and | work element by element on arrays.

Summary

  • if, elseif, else and end choose branches; conditions on arrays are true only if all elements are nonzero.
  • Use && and || in conditions, and compare floating-point numbers with a tolerance.
  • switch compares numbers with == and text with strcmp; a cell in a case lists alternatives, and there is no fall-through.
  • for iterates over the columns of its range; use an index loop for rows or cell contents.
  • while, break and continue handle loops of unknown length; prefer array operations over tiny-work loops and preallocate results.

Next: Scripts and Functions, where you'll package your code for reuse.