Fibonacci Series Using Recursive Function

54 ビュー (過去 30 日間)
Asif Ahmed
Asif Ahmed 2020 年 8 月 30 日
回答済み: Sandeep Kumar Patel 2022 年 4 月 13 日
I want to write a ecursive function without using loops for the Fibonacci Series. I done it using loops
function f =lfibor(n)
for i=1:n
if i<=2
f(i)=1;
else f(i)=f(i-2)+f(i-1);
end
end
end
I got the bellow code but It does not work for many RANDOM Number such as N=1
function v = fibor(n,v)
if nargin==1
v = fibor(n-1,[1,1]);
elseif n>1
v = fibor(n-1,[v,v(end-1)+v(end)]);
elseif n<1
v = 0;
end
How can I fix these ?

回答 (3 件)

James Tursa
James Tursa 2020 年 8 月 31 日
All of your recursive calls decrement n-1. Eventually you will wind up with the input n=0 and just return v=0, which is not what you want. Get rid of that v=0.

Varsha Lohani
Varsha Lohani 2021 年 10 月 23 日
a = lfibor(5)
a = 1×5
1 1 2 3 5
function f =lfibor(n)
if ~isscalar(n) || n ~= fix(n) || n < 0
error('non-negative integer scale input expected')
end
for i=1:n
if i<=2
f(i)=1;
else
f(i)=f(i-2)+f(i-1);
end
end
end

Sandeep Kumar Patel
Sandeep Kumar Patel 2022 年 4 月 13 日
function v = fibor(n,v)
if nargin==1
v = fibor(n-1,[1,1]);
elseif n>1
v = fibor(n-1,[v,v(end-1)+v(end)]);
elseif n<1
v = 1;
end

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by