Debugging Example--The Collatz Problem
The example debugging session requires you to create two M-files,
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,
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.
||Number of Integers in the Sequence
||3 10 5 16 8 4 2 1
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
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.
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
function collatzplot(n) % 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 m = 1:n plot_seq = collatz(m); seq_length(m) = length(plot_seq); line(m,plot_seq,'Marker','.','MarkerSize',9,'Color','blue') drawnow end
|Debugging M-Files||Trial Run for Example|