Matlab/Octave Scatter Plot: Visualizing Collatz Conjecture for x=1 to 1000

  • Context: MATLAB 
  • Thread starter Thread starter TylerH
  • Start date Start date
  • Tags Tags
    Plot
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
4 replies · 7K views
TylerH
Messages
729
Reaction score
0
How do I plot (x, collatz(x)), where x in an integer between 1 and 1000 inclusive, on a scatter plot?

Code:
function c = collatz(n)
	c = 0;
	while(n != 1)
		if(mod(n,2) == 0)
			n /= 2;
		else
			n = 3 * n + 1;
		end
		c++;
	end
end
 
Physics news on Phys.org
The code you posted above will not work with MatLab. MatLab's "not equal" operator is ~=. There is no division assignment or increment operator for MatLab.

http://www.mathworks.com/help/techdoc/matlab_prog/f0-40063.html

Code:
function [c] = collatz(n)
	c = 0;
	while n ~= 1
		if mod(n,2) == 0
			n = n/2;
		else
			n = 3 * n + 1;
		end
		c = c + 1 ;
	end
end

Code:
x = 1:1000;
y = arrayfun(@collatz, x);
scatter(x, y);
 
Last edited by a moderator:
Oh, I wasn't aware that Octave was so different from Matlab. I'm using the former, of course.

Thanks for your help.
 
How do I get Octave to show the plot? When I run octave collatz.m, it has no output.

collatz.m
Code:
function [c] = collatz(n)
       c = 0;
       while n ~= 1
               if mod(n,2) == 0
                       n = n/2;
               else
                       n = 3 * n + 1;
               end
               c = c + 1 ;
       end
end

x = 1:10;
y = arrayfun(@collatz, x);
scatter(x, y) % Notice the purposfully omitted semicolon!
 
The function and the last three lines should be in separate files. collatz.m is a function file, and it is not the place for separate script code that has a call to the function.

http://www.mathworks.com/help/techdoc/matlab_prog/f7-38085.html

Also, it does not matter if you have a semicolon after "scatter(x,y)"
 
Last edited by a moderator: