
Debugging Process a nd Features
Code for collatz.m.
function sequence=collatz(n)
% Collatz problem. Generate a sequence of integers resolving to 1
% For any positive integer, n:
% Divide n by 2 if n is even
% Multiply n by 3 and add 1 if n is odd
% Repeat for the result
% Continue until the result is 1%
sequence = n;
next_value = n;
while next_value > 1
if rem(next_value,2)==0
next_value = next_value/2;
else
next_value = 3*next_value+1;
end
sequence = [sequence, next_value];
end
Code for collatzplot.m.
function collatzplot(m)
% Plot length of sequence for Collatz problem
% Prepare figure
clf
set(gcf,'DoubleBuffer','on')
set(gca,'XScale','linear')
%
% Determine and plot sequence and sequence length
for N = 1:m
plot_seq = collatz(N);
seq_length(N) = length(plot_seq);
line(N,plot_seq,'Marker','.','MarkerSize',9,'Color','blue')
drawnow
end
Trial Run for Example. Open the file collatzplot.m. Makesurethe
current directory is the directory in which you saved
collatzplot.
6-105
Commenti su questo manuale