Building the Fibonacci using recursive

145 views (last 30 days)
Help needed in displaying the fibonacci series as a row or column vector, instead of all number.
Thia is my code: I need to display all the numbers: But getting some unwanted numbers.
function y = my_recursive3(n)
% y = zeros(1,n);
y = zeros(1,n);
ca = 1;
if n == 0
y = n ;
disp(y);
elseif n == 1
y = n;
disp(y);
else
y = my_recursive3(n-1)+ my_recursive3(n-2);
%y(ca) = y;
%ca = ca + 1;
end
%disp(y);
Thanks in advance

Answers (3)

Stephen23
Stephen23 on 12 Jun 2019
Edited: Stephen23 on 12 Jun 2019
I doubt that a recursive function is a very efficient approach for this task, but here is one anyway:
function v = myfib(n,v)
if nargin==1
v = myfib(n-1,[0,1]);
elseif n>1
v = myfib(n-1,[v,v(end-1)+v(end)]);
end
end
and tested:
>> myfib(8)
ans =
0 1 1 2 3 5 8 13
>> myfib(10)
ans =
0 1 1 2 3 5 8 13 21 34
  3 Comments
Stephen23
Stephen23 on 24 Aug 2020
@Akhila M : you could do something like Alwin Varghese suggested, but I recommend a more efficient elseif rather than defining a separate if statement:
function v = myfib(n,v)
if nargin==1
v = myfib(n-1,[0,1]);
elseif n>1
v = myfib(n-1,[v,v(end-1)+v(end)]);
elseif n<1
v = 0;
end

Sign in to comment.


Soumya Sinha
Soumya Sinha on 17 Jun 2019
The code for generating the fabonacci series numbers is given as -
function [n] = abcd(x)
if (x == 1 || x==0)
n = x;
return
else
n = abcd(x-1) + abcd(x-2);
end
end
However you can use a simpler approach using dynamic programming technique -
fibonacci = [0 1];
for i = 1:n-2
fibonacci = [fibonacci fibonacci(end)+fibonacci(end-1)];
end
This is a more efficient approach for this since recursion is exponential in complexity.

Dhiraj Darji
Dhiraj Darji on 30 Mar 2022
function f= fibor(n)
if n<=2
f=1;
else
f=fibor(n-1)+fibor(n-2);
end
This is working very well for small numbers but for large numbers it will take a long time

Products


Release

R2014a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!