Collatz Sequence Plotting Issue
Mostrar comentarios más antiguos
I have written code for the collatz problem, and performed some plotting for the number of steps versus the integer values. But now I am trying to plot the values of i versus my xi values *for i = 1 : 300.
Here is my code:
function [ns, seq] = collatz(n)
% first number insequence is n
seq(1) = n;
% position an index on the next element of sequence
i = 2;
% Repeat until you find a 1
while seq(i-1) ~= 1
% mod after division to find an even/odd number
if mod(seq(i-1), 2) == 0
% Step if even
seq(i) = seq(i-1)/2;
else
% Step taken if odd
seq(i) = 3*seq(i-1) + 1;
end
% index increment
i = i+1;
end
% Find length of the sequence
ns = length(seq);
Running Program:
>> [n, seq] = collatz(300)
n =
17
seq =
300 150 75 226 113 340 170 85 256 128 64 32 16 8 4 2 1
Then I wrote this code for the max values of xi with the largest number of steps for i = 1 : 300.
% For max number of steps for i = 1 : 300
clc; clear
% Sequence for max steps for
for i = 1 : 300
% Perform the function and get the number of elements
[n(i), seq{i}] = collatz(i);
end
% Find max number of steps found
[max_steps, ix] = max(n)
% Display the appropriate indexed sequence
seq{ix}
% Running Function:
max_steps =
128
ix =
231
How would I plot i on the x-axis versus my values of xi on the y - axis?
4 comentarios
Walter Roberson
el 22 de Abr. de 2012
What would be on the y axis again? The sequence length n(i) for position i? Or the maximum sequence length over 1:n(i) for position i?
Reelz
el 23 de Abr. de 2012
Walter Roberson
el 23 de Abr. de 2012
Please clarify. There is no "x" variable in your code. You have an "ix" variable, but that is obtained as the position the maximum length occurs over i=1:n and is thus a one-time thing not something that can be plotted against "i". Unless, that is, you want to modify the code slightly so that "ix" are the index of the "running maximum" -- e.g., if at "i" = 58 the maximum so-far had been at "i = 43" then ix(58) would be 43 ??
Reelz
el 23 de Abr. de 2012
Respuestas (1)
Thomas
el 23 de Abr. de 2012
You could plot the number of steps required to get to 1 as shown in the Wolfram mathworld link
You could do it simply by
plot(n,'MarkerSize',10,'Marker','.','LineStyle','none');
% Create xlabel
xlabel('Number');
% Create ylabel
ylabel('Steps to reach 1');
EDIT If the largest upto a number is needed
for i=1:300
newmax(i)=max(n(1:i))
end
plot(newmax)
Categorías
Más información sobre Spline Postprocessing en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!