n th Fibonacci number with function
Show older comments
Hi guys
I'm playing around with the fibonacci row.
I've been trying the for loops so far, not too hard.
n = input('n:');
fibo = zeros(1,n);
for n = 1:n
if n==1
fibo(n)=0;
else
if n==2
fibo(n)=1;
else
fibo(n)=fibo(n-1)+fibo(n-2);
end
end
end
disp(fibo);
But I want to have the whole thing in one function and only get the n-th fibonacci number.
any ideas
That's my idea, but it' s actually a very dumb.
(I know its not working)
function [c] = fibo (a, b, n)
n = input('n:');
a = n - 2;
b = n - 1;
c = a + b;
disp (c)
end
Accepted Answer
More Answers (2)
Ameer Hamza
on 25 Jun 2020
As compared to using for-loop, an alternative approach is to use a closed-form expression of the Fibonacci sequence as given here: https://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression. For example
function y = Fib(n)
phi = (1+sqrt(5))/2;
y = round((phi^n-(-phi)^-n)/(2*phi-1));
end
or
function y = Fib(n)
phi = (1+sqrt(5))/2;
y = floor(phi^n/sqrt(5)+1/2);
end
Result
>> Fib(1)
ans =
1
>> Fib(2)
ans =
1
>> Fib(3)
ans =
2
>> Fib(4)
ans =
3
>> Fib(5)
ans =
5
>> Fib(10)
ans =
55
>> Fib(15)
ans =
610
Voss
on 25 Jun 2020
0 votes
Notice that your function is calculating n-1 + n-2 and returning that as the nth term in the Fibonacci sequence. In actuality the nth term of the Fibonacci sequence is the (n-1)th term + the (n-2)th term, not just n-1 + n-2. Your loop is doing this correctly, so you just need to make your function do it that way. This is a good example of recursion.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!