Search code examples
matlabrecursioncollatz

How to keep track of recursive call on my function collatz?


I am trying to keep track of how many times the function call itself. I have tried setting up num as 0 and putting num = num+1 at the end but I keep getting 1. How do I fix this?

function [out num] = collatz(val)
num = 0;
if val == 1
   out = 1;
elseif mod(val, 2) == 0
   out = collatz(val/2);
else 
   out = collatz(3*val+1);
end
num = num+1;
end

Thank you.


Solution

  • A possible approach is to use a global variable to count the number of calls. You need to declare that variable as global

    • in the workspace from which you call collatz the first time; and
    • within the function.

    The function is thus defined as:

    function out = collatz(val)
    global num %// declare as global within the function
    num = num+1; %// increase call counter
    if val == 1
       out = 1;
    elseif mod(val, 2) == 0
       out = collatz(val/2);
    else 
       out = collatz(3*val+1);
    end
    end
    

    And then, from the command line:

    >> clear all
    >> global num %// declare as global in workspace
    >> num = 0; %// initiallize to 0
    >> collatz(5)
    ans =
         1
    >> num %// see value of num
    num =
         6