0

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

noobcodes
  • 17
  • 6

2 Answers2

1

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

Mehrez
  • 90
  • 2
  • 10
0

you have overwrited the U in the FOR loop, it didn't show the right Collatz sequence. try following code:

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
    clear U;
    hold on;
end
hold off;

After I run the above example where a=1 and b=20, i got 20 different Collatz sequence plots all together.

enter image description here

yaccDL
  • 1