Fibonacci Numbers
In Fibonacci’s best known book, Liber Abaci
, published in 1202, he posed the following problem:
A man put a pair of rabbits in a place surrounded on all sides by a wall.How many pairs of rabbits can be produced from that pair in a year if it is supposed that every month each pair begets a new pair which from the second month on becomes productive?
Today the solution to this problem is known as the Fibonacci sequence, or Fibonacci numbers.
Let
f
n
f_n
fn denote the number of pairs of rabbits after n months. The key fact is that the number of rabbits at the end of a month is the number at the beginning of the month plus the number of births produced by the mature pairs:
f
n
=
f
n
−
1
+
f
n
−
2
f_n = f_{n-1} + f_{n-2}
fn=fn−1+fn−2
The initial conditions are that in the first month there is one pair of rabbits and in the second there is also one pair:
f
1
=
1
,
f
2
=
1
f_1 = 1, f_2 = 1
f1=1,f2=1
The following Matlab function, stored in the M-file fibonacci.m, produces a vector containing the first n Fibonacci numbers.
function f = fibonacci(n)
% FIBONACCI Fibonacci sequence
% f = FIBONACCI(n) generates the first n Fibonacci numbers
f = zeros(n,1);
f(1) = 1;
f(2) = 1;
for k = 3 : n
f(k) = f(k-1) + f(k-2);
end
With these initial conditions, the answer to Fibonacci’s original question about the size of the rabbit population after one year is given by
fibonacci(12)
This produces
1
1
2
3
5
8
13
21
34
55
89
144
The answer is 144 pairs of rabbits.
Let’s look carefully at fibonacci.m. It’s a good example of how to create a Matlab function. The first line is
function f = fibonacci(n)
The word function says fibonacci.m is a function, not a script. The remainder of the first line says this particular function produces one output result, f, and takes one input argument, n. The next two lines are comments that provide the text displayed when you ask for help.
help fibonacci
produces
FIBONACCI Fibonacci sequence
f = FIBONACCI(n) generates the first n Fibonacci numbers
The name of the function is in uppercase because historically Matlab was case insensitive and ran on terminals with only a single font. It is important to repeat the input and output arguments in these comments because the first line is not displayed when you ask for help on the function.
Here is another Fibonacci function, fibnum.m. Its output is simply the nth Fibonacci number.
function f = fibnum(n)
% FIBNUM Fibonacci number.
% FIBNUM(n) generates the nth Fibonacci number.
if n <= 2
f = 1;
else
f = fibnum(n-1) + fibnum(n-2);
end
The statement
fibnum(12)
produces
ans =
144
The fibnum function is recursive, The relationship
f
n
=
f
n
−
1
+
f
n
−
2
f_n = f_{n-1} + f_{n-2}
fn=fn−1+fn−2 is known as a recursion relation and a function that calls itself is a recursive function. A recursive program is elegant, but expensive. You can measure execution
time with tic and toc. Try
tic, fibnum(24), toc
Do not try
tic, fibnum(50), toc