2

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.

Jason Thapa
  • 123
  • 9

3 Answers3

2

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
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
0

When you recursively call collatz you should save num too.

[out,num] = collatz(val/2);
rayryeng
  • 102,964
  • 22
  • 184
  • 193
Wilf Rosenbaum
  • 518
  • 3
  • 10
0

You can also avoid using global declarations by changing your recursive calls in collatz so that they output num as well. You'll also need to change the base case so that num = 0 when val = 1. Therefore, do this instead:

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

You can then use collatz so that num is also output when you call it in the command prompt. When I do this, and calling collatz with 5, I get:

[out,num] = collatz(5)

out = 

    1

num = 

    6
rayryeng
  • 102,964
  • 22
  • 184
  • 193