views:

124

answers:

3

The Fibonacci series is given as follow:

1, 2, 3, 5, 8, 13, 21, ...

How can I write a script file to calculate and print out the n-th Fibonacci term for n>2, where n is input by the user.

This is what I've tried:

   n=input('n: ');

    while(n < 3)
        disp('must enter number >= 3')
        if(n < 3)
            fprintf('\n\n Please re-insert again!!\n')
            n=input('n: ')


        else (n >=3)
            fibf(n)=fib(n-1)+fibf(n-2);
        end
    end

    fprintf('the nth value of n is :  ,fibf(n)')

but i didn't manage to print out the answer. WHY???

A: 

In addition to the fprintf error pointed out by James McNellis, you made the following errors:

  1. The fibf(n) = ... line references an array called fib, not fibf.

  2. If the user enters a number greater than 3, your while loop skips the calculation of fibf.

  3. If the user enters a number less than 3 and is prompted to reenter a number, you still skip the calculation because your else should be an else if.

  4. If you fix the logic errors in your while/if/else stuff, you still need to initialize fibf(1) and fibf(2), otherwise MATLAB won't have values for them.

There might be other mistakes, these are the ones I saw at first glance.

In general, stepping through loops and logic statements is the best way to debug. MATLAB will inform you about silly mistakes like forgetting to initialize fibf or using a variable that doesn't exist, but logic is difficult to trace without going line by line. In the editor, try enabling a breakpoint (press F12 in R2009a) at the first line. Then you can press F10 and step line by line and see exactly what's happening (F12 and F10 on windows, not sure what the equivalents are on other OSes).

mtrw
+1  A: 

I would do it like this:

n = input('n: ');

fib = zeros(1, n);
fib([1 2]) = [1 2];
for i = 3:n
    fib(i) = fib(i-1) + fib(i-2);
end

fprintf('the %dth Fibbonaci number is : %d\n', n, fib(n))

Or alternatively, this should work too:

phi = (1 + sqrt(5))/2;
fibn = round((phi^(n+1) - (1-phi)^(n+1))/sqrt(5));
fprintf('the %dth Fibbonaci number is : %d\n', n, fibn)

Aside: I would usually define the first Fibonacci numbers as 1 and 1 rather than 1 and 2.

Nzbuu
In your first example you should pre-allocate the vector to avoid performance problems: `fib=zeros(n,1); fib([1 2]) = [1 2];`
Will Robertson
True. Thanks, @Will.
Nzbuu
+1  A: 

Actually the Fibonacci series starts with 0, so F0=0, F1=1, F2=1 etc. The method of the recursive function is extremely slow. You'd better use linear algebra methods to calculate it.

l1 = (1+sqrt(5))/2;
l2 = (1-sqrt(5))/2;

S = [l1,l2;1,1];
L = [l1,0;0,l2];
C = [-1/(l2-l1);1/(l2-l1)];
k = 15;
y = S * L^k * C;

fprintf('the %dth Fibbonaci number is : %d\n', k, y(2))

the 15th Fibbonaci number is : 610

A proof can be found here.

gd047

related questions