In this chapter, we shall introduce further MATLAB structures in the context of some properties of whole numbers.
A loop to calculate Fibonacci numbers
Type in succession
» f = [11]
» f(3) = f(1) + f(2)
» f
» f(4) = f(2) + f(3);
» f
The last command produces the vector [1 1 2 3]. Thus f (1) refers to the first entry of the vector f, f (2) to the second, etc.
We can do this over and over in a loop:
» f = [11]
for k = 1:15
f(k+2) = f(k+1) + f(k)
end
» f
Note that MATLAB suppresses the » prompt until the loop is completed by end. What the for … end loop does is to take in succession the values 1,2, …, 15 for the variable k and to augment the vector f by a new entry f (k + 2) each time round. Thus k = 1 makes f emerge as [1 1 2]; k = 2 makes it emerge as [1 1 2 3], and so on. The semi-colon after the equation for f (k;+ 2) suppresses output during the 15 times the loop is executed.
Typing
plot(f, '*')
gives a plot of the values, placing an asterisk at each point (i,f(i)). Just plot(f) joins these points up with straight segments, producing a steeply sloping curve. The entries of the vector f are the Fibonacci numbers, 1,1,2,3,5,8,13,21,34, … The rule for forming them is, as above, f(1) = f(2) = 1; f (k + 2) = f(k + 1) + f(k) for k ≥ 1.
The above commands can be put into an M-file. As a variant on the above we could use a ‘while loop’, as follows:
f=[1 1];
k=1;
while f(k) > 1000
f(k+2)=f(k+1)+f(k);
k=k+1;
end
f
plot(f)
This M-file is stored under the name fibno.m and is executed by typing fibno.