MATLAB Answers

Building the Fibonacci using recursive

519 views (last 30 days)
surendra kumar Aralapura mariyappa
Edited: Piyush Gupta on 10 Sep 2020
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 (2)

Stephen Cobeldick
Stephen Cobeldick on 12 Jun 2019
Edited: Stephen Cobeldick 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

Akhila M
Akhila M on 20 Aug 2020
will this code work for myfib(1)???
Alwin Varghese
Alwin Varghese on 21 Aug 2020
you can add two lines to the above code by Stephen Cobeldick to get solution for myfib(1)
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
if n<1
v=0;
end
Stephen Cobeldick
Stephen Cobeldick 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.

  0 Comments

Sign in to comment.

Products


Release

R2014a

Community Treasure Hunt

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

Start Hunting!