Editing a function to return a value that shows how many times a recursive function is called

3 次查看(过去 30 天)
I have two separate functions. They are both used to calculate a Fibonacci number. Here is the first
function [result] = myFibonacci1(n)
if (n == 0)
result = 0;
elseif (n == 1)
result = 1;
else
result = myFibonacci1(n - 2) + myFibonacci1(n - 1);
end
end
And here is the second
function [result] = myFibonacci2(n)
% Create a temporary array 'stored' to store results already
% calculated, the Fibonacci value for n is stored in array
% location n + 1 (to allow us to store the value for n = 0 in a
% location.) So, Fibonacci(0) is stored in stored(1),
% Fibonacci(1) is stored in stored(2), etc.
stored = ones(1, n + 1) * -1;
stored(1) = 0;
stored(2) = 1;
function [hResult] = helper(a)
if (stored(a + 1) ~= -1)
hResult = stored(a + 1);
else
hResult = helper(a - 2) + helper(a - 1);
stored(a + 1) = hResult;
end
end
result = helper(n)
end
My goal is to edit these both of these functions so they also return the number of times a recursive functi0n is called.
Any ideas?

回答(3 个)

Jiawei Gong
Jiawei Gong 2020-3-10
编辑:Jiawei Gong 2020-3-10
function [f,count] = MyFib(n)
count = 1;
if n==1 || n==2
f = 1;
else
[f1,count1] = MyFib(n-1);
[f2,count2] = MyFib(n-2);
f = f1+f2;
count = count+count1+count2; % count itself and two branches
end
end
Results:
>> [f,callN] = MyFib(6)
f =
8
callN =
15

Jos (10584)
Jos (10584) 2015-4-21
You can add a second output argument
function [result, CallN] = myFunction(n, CallN)
if nargin==1,
CallN = 1 ;
else
CallN = CallN + 1 ;
end
...

James Tursa
James Tursa 2015-4-21
See this link:
You could be waiting a VERY, VERY, LONG time for your answer ...
  2 个评论
Noah Swiston
Noah Swiston 2015-4-21
I understand this is a bad method to calculate the fibonacci number. However, it was assigned to me just to add to the function to calculate how many times the recursion takes place, and then add that as an output argument as well. Any clue how to calculate how many time it is called?
James Tursa
James Tursa 2015-4-22
Jos has given you one method. Could also use a global variable for the counter if you don't want to change argument lists.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Environment and Settings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by