Desktop Tools and Development Environment Previous page   Next Page

Debugging Example--The Collatz Problem

The example debugging session requires you to create two M-files, collatz.m and collatzplot.m, that produce data for the Collatz problem.

For any given positive integer, n, the Collatz function produces a sequence of numbers that always resolves to 1. If n is even, divide it by 2 to get the next integer in the sequence. If n is odd, multiply it by 3 and add 1 to get the next integer in the sequence. Repeat the steps until the next integer is 1. The number of integers in the sequence varies, depending on the starting value, n.

The Collatz problem is to prove that the Collatz function will resolve to 1 for all positive integers. The M-files for this example are useful for studying the Collatz problem. The file collatz.m generates the sequence of integers for any given n. The file collatzplot.m calculates the number of integers in the sequence for all integers from 1 through m, and plots the results. The plot shows patterns that can be further studied.

Following are the results when n is 1, 2, or 3.

n
Sequence
Number of Integers in the Sequence
1
1
1
2
2  1
2
3
3  10  5  16  8  4  2  1
8

M-Files for the Collatz Problem

Following are the two M-files you use for the debugging example. To create these files on your system, open two new M-files. Select and copy the following code from the Help browser and paste it into the M-files. Save and name the files collatz.m and collatzplot.m. Save them to your current directory or add the directory where you save them to the search path. One of the files has an embedded error to illustrate the debugging 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 sequeence 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

Previous page  Finding Errors in M-Files Trial Run for Example Next page

© 1994-2005 The MathWorks, Inc.