Fibonacci Sequence Recursion, Help!

조회 수: 3 (최근 30일)
SB
SB 2012년 11월 8일
So, I have to recursively generate the entire fibonacci sequence, and while I can get individual terms recursively, I'm unable to generate the sequence. I already made an iterative solution to the problem, but I'm curious about a recursive one. Also, fib(0) should give me 0(so fib(5) would give me 0,1,1,2,3,5). Here's what I tried:
%
function[y]=fib_recur(n)
y = zeros(1,n);
fib(n);
y=[0 y]
function y = fib(n)
if n<3
y(1:n) = 1;
else
y(n) = fib(n-2) + fib(n-1);
end
y = y(n);
end
end

채택된 답변

Honglei Chen
Honglei Chen 2012년 11월 8일
Several issues:
(1) the result of fib(n) never returned. (2) Your fib() only returns one value, not a series
You can change your third line,
fib(n)
to
for m = 1:n
y(m) = fib(m);
end
so you can build an array.
HTH
  댓글 수: 3
Walter Roberson
Walter Roberson 2012년 11월 8일
편집: Walter Roberson 2012년 11월 8일
function y = fib_recur(n)
if n == 0
y = 0;
else
y = [fib_recur(n-1) fib(n)]
end
SB
SB 2012년 11월 8일
Ahh thank you, that's what I was trying to get!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by