MATLAB: Fibonacci number without any loops

fibonacci number

My problem is to use the fprintf command to print out the first N Fibonacci numbers in a two-column table under heading N and F_N. And for the case N >= 50, print out the last 10 Fibonacci numbers F_i for i = N – 9 in a similar two-column table.

Best Answer

Here is a formula (not using loops) for the Fibonacci numbers ranging from n = n1 to n = n2:
L1 = (1+sqrt(5))/2;
L2 = (1-sqrt(5))/2;
A = 1/sqrt(5);
n = (n1:n2)';
F(n) = round(A*(L1.^n-L2.^n));
(The 'round' call is to correct for round-off errors. The formula is valid up to about n = 70 at which point round-off errors become too large to correct with 'round'.)