Linear Algebra and Programming Skills

Dr Jon Shiach, Department of Computing and Mathematics, Manchester Metropolitan University

Loops

Learning Outcomes

On successful completion of this page readers will be able to:
The fundamental point of computer programming is to get a computer to do tasks that would take a human too long to complete. A lot of this uses repetition, performing the same calculations or commands over and over again. There are two constructs to help us do this: for loops and while loops.

For loops

If we want to repeat the execution of a set of commands a given number of times then we can use a for loop.
for variable = start : step : stop
commands
end
The for declaration requires a loop variable and a range of values. The commands that are contained between the for and end commands are repeated for each value of the variable from the range.
Note that it is good programming practice to indent any commands which are contained within a loop.
Example 1
The commands below uses the for loop to print the integer numbers 0 to 4. Enter them into the code cell below and run the live script to see the result.
for i = 1 : 5
i
end
for i = 1 : 5
i
end
i = 1
i = 2
i = 3
i = 4
i = 5
Here the loop variable is i and the range is defined by 1 : 5 which is a sequence of numbers from 1 to 5. The value of i is outputed since there is no semi-colon (;) at the end of the line.
Example 2
The nth Fibonacci number is calculated using where the first two Fibonacci numbers are and , e.g.,
0, 1, 1, 2, 3, 5, 8, 13, ...
The following program uses a for loop to print the 20 Fibonacci numbers. Enter this into the code cell below and run the live script.
a = 0;
b = 1;
 
for i = 1 : 20
fprintf('%1i, ', a)
c = a + b;
a = b;
b = c;
end
clear
a = 0;
b = 1;
 
for i = 1 : 20
fprintf('%1i\n', a)
c = a + b;
a = b;
b = c;
end
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
Note that the first two Fibonacci numbers are defined before using a for loop repeat the calculations 20 times.
Example 3
The following program uses a for loop to sum five numbers in an array. Enter this into the code cell below and run the live script.
X = [ 1, 7, -4, 3, -5 ];
total = 0;
 
for i = 1 : 5
total = total + X(i)
end
 
fprintf('The sum of the five numbers is %1i.', total)
X = [ 1, 7, -4, 3, -5];
total = 0;
 
for i = 1 : 5
total = total + X(i);
end
 
fprintf('The sum of the five numbers is %1i.', total)
The sum of the five numbers is 2.
Note this could have been achieved using the command total = sum(numbers).

Exercise 1 - For loops

1. Use a for loop to print 'hello world ' 10 times on different lines.
for i = 1 : 10
fprintf('hello world\n')
end
hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world
2. Use a for loop to print the first 20 even numbers.
for i = 1 : 20
n = 2 * i
end
n = 2
n = 4
n = 6
n = 8
n = 10
n = 12
n = 14
n = 16
n = 18
n = 20
n = 22
n = 24
n = 26
n = 28
n = 30
n = 32
n = 34
n = 36
n = 38
n = 40
3. Use a for loop to calculate the sum of the first 100 natural numbers.
clear
total = 0;
 
for i = 1 : 100
total = total + i;
end
 
fprintf('The sum of the first 100 natural numbers is %1i.', total)
The sum of the first 100 natural numbers is 5050.
4. Use a for loop to calculate the value of 52! (the number of ways you can shuffle a deck of cards).
clear
fact = 1;
 
for i = 1 : 52
fact = fact * i;
end
 
fprintf('%1i', fact)
8.065818e+67
5. Use a for loop to calculate the 10th term and the sum of the first 10 terms of the geometric series: 3, 12, 48, 192,
clear
a = 3;
r = 4;
total = 0;
N = 10;
 
for i = 1 : N
a = a * r;
total = total + a;
end
 
fprintf('The 10th term is %1i and the sum of the first 10 terms is %1i.', a, total)
The 10th term is 3145728 and the sum of the first 10 terms is 4194300.
6. Use for loops to calculate the mean and standard deviation σ of the numbers: 1.2, 4.3, 5.7, 1.4, 7.2, 3.5.
Hint: use an array to store the numbers.
clear
X = [ 1.2, 4.3, 5.7, 1.4, 7.2, 3.5 ];
N = length(X);
 
% Calculate mean
xbar = 0;
for i = 1 : N
xbar = xbar + X(i);
end
xbar = xbar / N;
 
% Calculate standard deviation
sigma = 0;
for i = 1 : N
sigma = sigma + (X(i) - xbar) ^ 2;
end
sigma = sqrt(sigma/(N - 1));
 
% Print mean and standard deviation (2 to decimal places)
fprintf('The mean is %1.2f and the standard deviation is %1.2f.', xbar, sigma)
The mean is 3.88 and the standard deviation is 2.37.
7. The series expansion of is
Use a for loop to compute using the first 5 terms. To how many decimal places does your value agree to the one calculated using sin(pi/4)?
Hint: the command factorial(x) computes the value of .
clear
 
x = pi / 4;
sinx = 0;
for n = 0 : 5
sinx = sinx + (-1) ^ n / factorial(2 * n + 1) * x ^ (2 * n + 1);
end
 
fprintf([ 'The sum of the first 5 terms is sin(pi/4) = %1.12f\n', ...
'The exact value of sin(pi/4) = %1.12f.'], sinx, sin(x))
The sum of the first 5 terms is sin(pi/4) = 0.707106781180 The exact value of sin(pi/4) = 0.707106781187.

While loops

If we want to repeat the execution of a set of commands when we don't know how many repetitions is required then we can use a while loop.
while logical condition
commands
end
The commands between the while and end commands will be executed whilst the logical condition is true.
Example 4
The commands below use a while loop to print the integer numbers between 1 and 5 (i.e., similar to example 1). Enter them into the code cell below and run the live script.
i = 1;
 
while i < 6
i
i = i + 1;
end
i = 1;
 
while i < 6
i
i = i + 1;
end
i = 1
i = 2
i = 3
i = 4
i = 5
Note that we needed a variable i which is incremented by 1 at each iteration to keep track of the number of iterations we have done. If we didn't increment i then the logical condition i < 6 would always be true and the while loop would repeat the commands within the while loop forever. This is a common programming error known as an infinite loop which can be exited by clicking on the stop button.
Example 5
The program below uses a while loop to print the first 20 Fibonacci numbers. Enter it into the code cell below and run the live script.
a = 0;
b = 1;
n = 0;
 
while n < 20
fprintf('%1i, ', a)
c = a + b;
b = c;
b = n + 1
end
clear
a = 0;
b = 1;
n = 0;
 
while n < 20
fprintf('%1i, ', a)
c = a + b;
a = b;
b = c;
n = n + 1;
end
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181,

Exercise 2 - While loops

8. Use a while loop to print 'hello again' ten times on separate lines.
clear
n = 1;
 
while n < 11
fprintf('hello again\n')
n = n + 1;
end
hello again hello again hello again hello again hello again hello again hello again hello again hello again hello again
9. Use a while loop to print the first 20 odd numbers.
clear
i = 1;
 
while i < 41
fprintf('%1i\n', i)
i = i + 2;
end
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39
10. Use a while loop to calculate the sum of the first 100 natural numbers.
clear
total = 0;
n = 1;
 
while n < 101
total = total + n;
n = n + 1;
end
 
fprintf('The sum of the first 100 natural numbers is %1i.', total)
The sum of the first 100 natural numbers is 5050.
11. The Collatz conjecture states that the series generated by the following iterative scheme will eventually reach 1.
Use a while loop to print the numbers in this series for a starting value of 100. The first few numbers in this sequence are 100, 50, 25, 76, 38. How many iterations were required to reach 1?
Hint: The command mod(x, y) returns the remainder of .
clear
x0 = 100;
x = x0;
n = 0;
 
while x > 1
fprintf('%1i\n', x)
if mod(x, 2) == 0
x = x / 2;
else
x = 3 * x + 1;
end
n = n + 1;
end
100 50 25 76 38 19 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2
fprintf('\n\n%1i steps were required to reach 1', n)
25 steps were required to reach 1

Loop control

Sometimes it is necessary to interrupt the normal flow of a loop to either exit the loop before all iterations have completed or to move to the next iteration immediately without performing any further commands in the same iteration. To do this MATLAB uses the break and continue commands.

break

The break command is used to exit a loop.
Example 7
The ratio of successive Fibonacci numbers converge to the golden ratio
The program below uses a while loop to calculate approximations of φ ceasing iterations when the difference between two successive iterations is less than . Enter it into the code cell below and run the live script.
phi = (1 + sqrt(5)) / 2; % exact value of phi
a = 0;
b = 1;
 
while true
c = a + b;
phi_estimate = c / b;
 
if abs(phi_estimate - b / a) < 1e-6
break
end
 
a = b;
b = c;
end
 
fprintf([ 'The exact value of the golden ratio is %1.8f.\n' ...
'An approximation of the golden ratio using Fibonacci numbers ' ...
'is %1.8f.'], phi, phi_estimate)
clear
phi = (1 + sqrt(5)) / 2;
a = 0;
b = 1;
 
while true
c = a + b;
phi_estimate = c / b;
if abs(phi_estimate - b / a) < 1e-6
break
end
a = b;
b = c;
end
 
fprintf([ 'The exact value of the golden ratio is %1.8f.\n' ...
'An approximation of the golden ratio using Fibonacci numbers ' ...
'is %1.8f.'], phi, phi_estimate)
The exact value of the golden ratio is 1.61803399. An approximation of the golden ratio using Fibonacci numbers is 1.61803381.
Here the logical condition used in the while loop is always true so the commands will repeat indefinitely unless the break command is executed.

continue

The continue command moves to the next cycle of a loop.
Example 8
The program below uses a for loop to calculate the sum of five numbers. Negative numbers are removed from the calculation. Enter it into the code cell below and run it.
X = [ 1, 7, -4, 3, -5 ];
total = 0;
 
for i = 1 : length(X)
if X(i) < 0
continue
end
total = total + X(i);
end
 
fprintf('The sum of the five numbers (excluding negatives) is %1i.', total)
clear
X = [ 1, 7, -4, 3, -5 ];
total = 0;
 
for i = 1 : length(X)
if X(i) < 0
continue
end
total = total + X(i);
end
 
fprintf('The sum of the five numbers (excluding negatives) is %1i.', total)
The sum of the five numbers (excluding negatives) is 11.

Exercise 3 - loop control

12. Use for loops to loop through the numbers between 2 and 100 and print those numbers that are prime numbers.
Hint: loop through all numbers between 2 and 100 and use another loop to check all numbers between 2 and that number to see if it has a factor that is not itself (the mod(x, y) command will come in useful here).
clear
 
for i = 2 : 100
prime = true;
for j = 2 : i - 1
if mod(i, j) == 0
prime = false;
break
end
end
if prime
fprintf('%1i\n', i)
end
end
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Nested loops

A loop can be contained or nested within another loop.
Example 9
The program below uses nested for loops to generate a multiplication square. Enter it into the code cell below and run the live script to see the result.
M = zeros(10, 10);
 
for i = 1 : 10
for j = 1 : 10
M(i, j) = i * j;
end
end
 
M
clear
M = zeros(10, 10);
 
for i = 1 : 10
for j = 1 : 10
M(i, j) = i * j;
end
end
 
M
M = 10×10
1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100
The first loop use used to loop through the rows of M and another loop to loop through the columns of M and calculate the produce of the row number and column number.

Exercise 4 - Nested loops

13. The matrix multiplication of an matrix A and a matrix B is defined by
Use three nested for loops (one for each i, j and k) to multiply the two matrices
and .
clear
A = [ 1, 2, 3 ; 4, 5, 6 ; 7, 8, 9 ];
B = [ 10, 11, 12 ; 13, 14, 15 ; 16, 17, 18 ];
 
rows = size(A, 1);
cols = size(B, 2);
p = size(A, 2);
 
AB = zeros(rows, cols);
 
for i = 1 : rows
for j = 1 : cols
for k = 1 : p
AB(i, j) = AB(i, j) + A(i, k)*B(k, j);
end
end
end
 
AB
AB = 3×3
84 90 96 201 216 231 318 342 366