TExcelTAD
Home › MATLAB / Octave › for Loops

for Loops

A for loop repeats a block of code once for each value in an array. The most common form counts through a range of integers:

matlab · try it yourself
for k = 1:5
    fprintf('Iteration %d, k squared = %d\n', k, k^2);
end
Iteration 1, k squared = 1
Iteration 2, k squared = 4
Iteration 3, k squared = 9
Iteration 4, k squared = 16
Iteration 5, k squared = 25

The loop variable k takes the values 1, 2, 3, 4, 5 in turn, and the block between for and end runs once for each.

Looping over any vector

The range can be any row vector: a colon expression with a step, a counting-down range, or a list of values:

matlab · try it yourself
for t = 0:0.25:1
    fprintf('%.2f ', t);
end
fprintf('\n');
for n = 10:-3:1
    fprintf('%d ', n);
end
fprintf('\n');
for p = [2 3 5 7 11]
    fprintf('%d is prime\n', p);
end
0.00 0.25 0.50 0.75 1.00 
10 7 4 1 
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime

Note: If you loop over a matrix, the loop variable becomes each column in turn, not each element. Loop over A(:)' to visit every element.

Indexing with the loop variable

Usually you loop over indices so you can read and write elements of arrays. numel (or length) gives the number of elements, so the loop works for any size:

matlab · try it yourself
prices = [4.99 12.50 3.25 8.00];
discounted = zeros(size(prices));      % preallocate the result
for k = 1:numel(prices)
    if prices(k) > 5
        discounted(k) = prices(k) * 0.9;
    else
        discounted(k) = prices(k);
    end
end
fprintf('%6.2f -> %6.2f\n', [prices; discounted]);
  4.99 ->   4.99
 12.50 ->  11.25
  3.25 ->   3.25
  8.00 ->   7.20

Accumulating results

A loop often builds up a total, a product or a running maximum. Initialise the accumulator before the loop:

matlab · try it yourself
n = 10;
total = 0;
fact = 1;
for k = 1:n
    total = total + k;
    fact = fact * k;
end
fprintf('Sum of 1..%d = %d\n', n, total);
fprintf('%d! = %d\n', n, fact);

% Approximate pi with the Leibniz series 4*(1 - 1/3 + 1/5 - ...)
approx = 0;
for k = 0:999
    approx = approx + (-1)^k / (2*k + 1);
end
fprintf('pi is about %.6f after 1000 terms\n', 4 * approx);
Sum of 1..10 = 55
10! = 3628800
pi is about 3.140593 after 1000 terms

Nested loops

Loops can be nested, for example to visit every row and column of a matrix. size(A, 1) gives the number of rows and size(A, 2) the number of columns:

matlab · try it yourself
A = zeros(3, 4);
for r = 1:size(A, 1)
    for c = 1:size(A, 2)
        A(r, c) = 10 * r + c;
    end
end
disp(A)

% Print a small multiplication table
for r = 1:4
    for c = 1:4
        fprintf('%4d', r * c);
    end
    fprintf('\n');
end
   11   12   13   14
   21   22   23   24
   31   32   33   34
   1   2   3   4
   2   4   6   8
   3   6   9  12
   4   8  12  16

Tip: Don't use i or j as loop variables if your code also uses complex numbers: inside the loop they no longer mean √-1. Many MATLAB programmers use k, n, ii or descriptive names like row instead.

Looping over a cell array

To loop over a list of names or other mixed data, loop over the indices of a cell array and use curly braces to get each item:

matlab · try it yourself
planets = {'Mercury', 'Venus', 'Earth', 'Mars'};
for k = 1:numel(planets)
    fprintf('%d: %s has %d letters\n', k, planets{k}, length(planets{k}));
end
1: Mercury has 7 letters
2: Venus has 5 letters
3: Earth has 5 letters
4: Mars has 4 letters

Changing the loop variable inside the loop does not affect the next iteration: on the next pass it simply takes the next value from the range.

Test yourself

How many times does for k = 2:2:10 run?

  1. 4
  2. 5
  3. 9
  4. 10

If A is a 3x4 matrix, what is x on each pass of for x = A?

  1. Each element
  2. Each row
  3. Each column
  4. The whole matrix once

Why preallocate with zeros before a loop that fills an array?

  1. It is required syntax
  2. It avoids repeatedly growing (copying) the array, which is slow
  3. It makes the values default to 1
  4. It prevents index errors in all cases