matlabgraphplotcollatz

MATLAB Collatz plot


I am trying to do the Collatz problem on Matlab. I am having trouble plotting my results.

a = input( 'Please enter a value for a:'); 
b = input( 'Please enter a value for b:'); 
for n = (a:b), 
    count = 0;
    while n > 1
        count= count+ 1;
        if mod(n,2) == 0 
            n = n/2;
       else
            n = (3*n+1); 
        end
      plot (n:count); 
    end
end

I am attempting to plot the values of n and count (the length of the sequence of n) between two user inputted numbers inclusive (eg from 1 to 40). My graph comes out as a line y = x instead of the intended solution.

Thanks for the help

noobcodes


Solution

  • 1) You are plotting the wrong series of values. n:count gives u an array of doubles going from n to count , in our case the final value of n is 1 and the final value of count is 8, then n:count = [ 1 2 3 4 5 6 7 8 9 ] , this is x=y function like. I suggest that u store the values of n in a different Array , and the to plot that array. Your code should look like this:

    a = input( 'Please enter a value for a:'); 
    b = input( 'Please enter a value for b:'); 
    for n = (a:b), 
        count = 0;
        while n > 1
            count= count+ 1;
            if mod(n,2) == 0 
                n= n/2;
           else
                n = (3*n+1); 
            end
            U(count) =n;
          plot (U); 
        end
    end
    

    After i run the above example where a=1 and b=40, i got a plot like Collatz plots usually.

    Output:

    enter image description here