
6 Editing and Debugging M-Files
thatareonthesearchpath.Ifallfilestobeusedareinthesamedirectory,
you can instead m ake that directory be the current directory.
Debugging Example — The Collatz Problem
The debugging process and features are best described via an example.
Topreparetousetheexample,createtwoM-files,
collatz.m and
collatzplot.m, that produce data for the Collatz problem.
For any given p os itiv e integer,
n,theCollatz 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 se quence. 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 p ositive integers. The M-files for this e xample are useful for studying
the Collatz problem. The file
collatz.m generates the sequence of integers
for any given
n.Thefilecollatzplot.m calculates the number of integers
in the sequence for all integers from 1 through
m,andplotstheresults. The
plot shows patterns that can be further studied.
Follow ing are the results when
n is 1, 2, or 3.
n Sequence
Number of Integers in the
Sequence
11 1
221 2
3 3105168421 8
M-Files for the Collatz Problem. Fo ll owing are the two M- fi les 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 wh ere you save them
to the search path. One of the files has an embedded error to illustrate the
debugging features.
6-104
Commentaires sur ces manuels