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?
댓글 수: 0
답변 (3개)
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
댓글 수: 0
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
...
댓글 수: 0
James Tursa
2015년 4월 21일
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
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 Center 및 File Exchange에서 Environment and Settings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!