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

4 views (last 30 days)
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?

Answers (3)

Jiawei Gong
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

Jos (10584)
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
...

James Tursa
James Tursa on 21 Apr 2015
See this link:
You could be waiting a VERY, VERY, LONG time for your answer ...
  2 Comments
Noah Swiston
Noah Swiston on 21 Apr 2015
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 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.

Sign in to comment.

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!