![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/249367/image.png)
Helped needed in Fibonacci Sequence code
1 次查看(过去 30 天)
显示 更早的评论
I already made a code that finds the nth term of a Fibonacci sequence (Fn) using a recursive function but I need help updating this code to also output how many times the recursive sequence ran.
As of right now, the code I have to find the nth term is: (where n=2 and n=1 are the base conditions that tells the recursive function to stop)
function[F_n] = Fibonacci(n)
if n == 2
F_n = 1;
elseif n == 1
F_n = 0;
else
F_n = Fibonacci(n-1) + Fibonacci(n-2);
end
end
0 个评论
采纳的回答
Darshan Sen
2019-11-21
Hello Cici. We can solve this by introducing another variable count into the function as shown below.
function[F_n, count] = Fibonacci(n, count)
count = 1;
if n == 2
F_n = 1;
elseif n == 1
F_n = 0;
else
[F_n_1, count_1] = Fibonacci(n-1);
[F_n_2, count_2] = Fibonacci(n-2);
F_n = F_n_1 + F_n_2;
count = count + count_1 + count_2;
end
end
Now your function returns both the
Fibonacci number as well as the number of times the function was called.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/249367/image.png)
You may capture only the count in variable ans using this code snippet for the desired value of n.
[~, ans] = Fibonacci(n);
Hope this helps. :)
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Financial Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!