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

  • Thread starter Thread starter TylerH
  • Start date Start date
  • Tags Tags
    Plot
AI Thread Summary
To plot the Collatz function values for integers between 1 and 1000 on a scatter plot, a function named "collatz" is defined to calculate the number of steps to reach 1 for a given integer. The correct implementation in MATLAB requires using the "not equal" operator as ~= and incrementing the counter with c = c + 1. The code snippet provided initializes an array x with values from 1 to 1000 and uses arrayfun to apply the collatz function to each element, storing results in y. The scatter plot is created using scatter(x, y). Users transitioning from Octave to MATLAB should note differences in syntax and ensure that the function and plotting code are organized correctly, with the function in a separate file. Additionally, the presence or absence of a semicolon after the scatter command does not affect the output.
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:

Similar threads

Replies
8
Views
2K
Replies
1
Views
2K
Replies
10
Views
3K
Replies
3
Views
2K
Replies
2
Views
3K
Replies
2
Views
2K
Replies
2
Views
2K
Back
Top