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

조회 수: 5 (최근 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에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by