Published online by Cambridge University Press: 08 February 2010
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.
To save this book to your Kindle, first ensure no-reply@cambridge.org is added to your Approved Personal Document E-mail List under your Personal Document Settings on the Manage Your Content and Devices page of your Amazon account. Then enter the ‘name’ part of your Kindle email address below. Find out more about saving to your Kindle.
Note you can select to save to either the @free.kindle.com or @kindle.com variations. ‘@free.kindle.com’ emails are free but can only be saved to your device when it is connected to wi-fi. ‘@kindle.com’ emails can be delivered even when you are not connected to wi-fi, but note that service fees apply.
Find out more about the Kindle Personal Document Service.
To save content items to your account, please confirm that you agree to abide by our usage policies. If this is the first time you use this feature, you will be asked to authorise Cambridge Core to connect with your account. Find out more about saving content to Dropbox.
To save content items to your account, please confirm that you agree to abide by our usage policies. If this is the first time you use this feature, you will be asked to authorise Cambridge Core to connect with your account. Find out more about saving content to Google Drive.