# n th Fibonacci number with function

26 views (last 30 days)
Adam Roudi on 25 Jun 2020
Answered: Benjamin on 25 Jun 2020
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

Steven Lord on 25 Jun 2020
function [c] = fibo (a, b, n)
n = input('n:');
Every time your user calls your fibo function, you're going to ask them to pass a value into it for n (as the third input) then immediately turn around and prompt them to type in a replacement value for n.
IMO if part of your design requires your user to enter data manually, you should have (at least) two separate functions: the interface function that can call input and then just calls the processing function and the processing function that operates solely on data passed into it (no prompting of the user allowed.)
But that's a bit of an aside. You already have most of what you want. It's not too difficult to translate your first script into a function.
n = input('n:');
Turn this first statement into the function declaration line. "function theOutputs = fibonacci(theInputs)". I'll let you decide what to write in place of theOutputs and theInputs.
fibo = zeros(1,n);
for n = 1:n
Reusing the variable name technically works, but it can be confusing that the role of n kind of changes. I'd use a different variable name for the loop variable.
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);
Turn this last line into the line that defines whatever variables you need to return. It should assign into whatever variables appear in theOutputs above.

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

Benjamin on 25 Jun 2020
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.