Development Environment    

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 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 any given integer 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 for purposes of illustrating the debugging features.

Code for collatz.m.

Code for collatzplot.m.


  Debugging M-Files Trial Run for Example