Code:
function threeEx()
%matlab code for Collatz Conjecture 3n+1 Problem
%This script assumes the Collatz Conjecture holds,
%that sequences end in the 421 loop
start=input('Enter vector of starting values (+ real integers) []: ');
if start<=0
start(start<=0)=input('Replace start<=0 with + real integers []:');
%correct terms if input wrong
newvec=sprintf('%d ',start);
fprintf('Starting values: %s ',newvec)
end
peak=[];
%initialize vector of max. values
labcol='rgbcmykw';
%start condition
for i=1:length(start)
%assign starting position
val=[start(i)];
while val(end)~=1
%Assuming all + real integers result in end sequence 421
if rem(val(end),2)==0
val=[val val(end)/2];
else
val=[val 3*val(end)+1];
end
end
%build values for results of operation on starting value
hold on
if i<=length(labcol)
lincol=strcat('-',labcol(i));
elseif rem(i,length(labcol))==0
lincol=strcat('-',labcol(end));
else
lincol=strcat('-',labcol(rem(i,length(labcol))));
end
%Assign plot colors
plot(1:length(val),val,lincol)
%plot values
for x=1:length(val)
text(x+.05,val(x),num2str(val(x)))
end
%label each point
peak=[peak max(val)];
%Find max value of sequence
end
peak=sprintf('%d ',peak);
fprintf('Max value(s): %s\n',peak)
%output max values of sequences associated with starting values
end