Text-only Table of Contents (frame/ no frame)
(31) Visual Debugging Previous Top Next

Visual Debugging



Matlab Editor/Debugger

try:
>> collatzplot(6)


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

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



Previous Top Next


Visual_Debugging.src  last modified Oct 17, 2007 Introduction Table of Contents
(frame/no frame)
Printable
(single file)
© Dartmouth College