If you want to avoid a global variable in a recursive function you can pass in a value that is updated with each successive recursive call.
I don't want to give you the exact solution for your assignment but consider the example for a recursive implementation of the factorial function. It's fairly straightforward to adapt this method to your Fibonacci function.
function [res, call_count] = recursive_factorial(n, call_count)
% increment counter
call_count = call_count + 1;
if n <= 1
% check for base case
res = 1;
else
% call_count gets updated by recursive call
[res_prev, call_count] = recursive_factorial(n-1, call_count);
res = n * res_prev;
end
end
Usage example of computing 10!. Notice that we initialize the call_count
argument to 0 for the initial call.
>> [ten_factorial, call_count] = recursive_factorial(10, 0)
ten_factorial =
3628800
call_count =
10
Update
If we were using a global variable call counter then the factorial function would look something like this.
function res = recursive_factorial(n)
% increment global counter
global call_count
call_count = call_count + 1;
if n <= 1
res = 1;
else
res = n * recursive_factorial(n-1);
end
end
Compare this with the non-global version and that should help you understand what you need to do to modify your Fibonacci function.