Editing a function to return a value that shows how many times a recursive function is called
4 views (last 30 days)
Show older comments
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?
0 Comments
Answers (3)
Jiawei Gong
on 10 Mar 2020
Edited: Jiawei Gong
on 10 Mar 2020
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
0 Comments
Jos (10584)
on 21 Apr 2015
You can add a second output argument
function [result, CallN] = myFunction(n, CallN)
if nargin==1,
CallN = 1 ;
else
CallN = CallN + 1 ;
end
...
0 Comments
James Tursa
on 21 Apr 2015
See this link:
http://www.mathworks.com/matlabcentral/answers/195865-fibonacci-program-makes-matlab-go-busy-forever
You could be waiting a VERY, VERY, LONG time for your answer ...
2 Comments
James Tursa
on 22 Apr 2015
Jos has given you one method. Could also use a global variable for the counter if you don't want to change argument lists.
See Also
Categories
Find more on Environment and Settings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!