Skip to main content

Section 4.1 for loop

Syntax of for loop:

for (variable) = (some vector, usually regularly spaced a:h:b) 
    (some computation)
end

This means that “some computation” will be repeated for each entry of the vector specified in the line with for. Do not forget to end the loop: Matlab needs it to know which part of the code should be repeated in the loop. Indenting the body of the loop is optional but it improves readability.

Find the sum of cubes of the integers from 1 to 10 using a for loop.

Answer
s = 0;
for k = 1:10
    s = s + k^3;
end

Explanation: before entering the loop, we initialize the variable s with 0, meaning that the value of the sum is 0 before we start adding things to it. Each time the command s = s + k^3 is executed, the cube of k is added to s. This repeats for each value in the vector 1:10. When the loop ends, the variable s will contain the sum of cubes.

This example is for illustration only: in practice the array operation sum((1:10).^3) would be a better choice because it is shorter and possibly more efficient than the loop.

One could use a more descriptive variable name instead of s, for example total. But do not use sum because this is the name of a built-in Matlab function. Same goes for max and min: since they are names of built-in functions, they should not be used as variable names. Also, although mathematicians often use \(i\) as index variable, it is too easy to confuse with digit \(1\) and so is best avoided.

A loop is necessary for iterative computations, when every step of computation uses the result of the previous one. Example 4.1.1 is not like this, since the cubes of 1, 2, 3,... can be computed independently of each other: we do not need the cube of 5 in order to compute the cube of 6. In contrast, the computation of arithmetic-geometric mean in Example 1.2.1 is iterative: we compute the arithmetic and geometric means, and then use them as an input for next computation.

Find the arithmetic-geometric mean (AGM) of 11 and 31 using a for loop.

Answer
x = 11;
y = 31;
for k = 1:10
    a = (x+y)/2;
    g = sqrt(x*y);
    x = a;
    y = g;
end
disp(x)

It does not matter whether we display x or y at the end because they become nearly equal after 10 iterations. The output is the number 19.7127, which we can check for correctness using, for example, Wolfram Alpha: agm(11,31).

The logic of the script: compute arithmetic and geometric means of x and y, then use them as our new values of x and y. One may be tempted to shorten the loop as follows

for k = 1:10
    x = (x+y)/2;
    y = sqrt(x*y);
end

But this loop produces a wrong answer: 23.9912. The reason this script is wrong is that it changes x before the computation of geometric mean. The definition of AGM requires both arithmetic and geometric means to be computed from the same pair x, y. Only after both means are computed, we can replace x and y with new values.