Debugging

In most cases, a MATLAB error message is clear enough to enable you to improve your program. This is especially the case with syntax errors, a forgotten

`end`

command or operations with matrices that do not have the correct size (e.g., you have forgotten to transpose). When you do not understand the error or if the program does run but gives unexpected results, you will have to debug the program.
The simplest way of debugging is to look at intermediate results. You can have these printed on your screen by omitting the semicolon at the ends of the corresponding lines. For example, this enables you to keep track of what happens to a certain variable in a loop.

Another, somewhat more intricate option, is to use the MATLAB Debugger. This is built into the Editor, and allows you to go through the program step by step, so that you can see where the error occurs. You can also indicate so-called break points. The program then runs from break point to break point and pauses at these break points. Type

`doc debug`

for more info, the link under "GUI Alternatives" may be helpful as well.
Hereto, first the following program is written, where the first two characters of each line represent the line numbering:

1 %Program to create B with random elements, and C according to the text 2 3 %% give size of matrices, initialise matrices C 4 sh=8; %horizontal size 5 sv=10; %vertical size 6 7 B=zeros(sv,sh); 8 C=zeros(sv,sh); 9 10 %% compute random elements of B 11 B=rand(sv,sh) 12 13 %% Show outputs of B in command window 14 B 15 Bbar=mean(B.^2) 16 17 %% Create C 18 for m=1:sv; 19 for n=1:sh 20 if B(n,m)<sqrt(Bbar); 21 C(n,m)=1; 22 else 23 C(n,m)=0; 24 end 25 end 26 end 27 28 %% Show C 29 CHowever, running this file in MATLAB yields outputs for

??? Attempted to access B(1,9); index out of bounds because size(B)=[10,8]. Error in ==> Untitled at 20 if B(n,m)<sqrt(Bbar);Apparently, the element

20 if B(m,n)<sqrt(Bbar); 21 C(m,n)=1; 23 C(m,n)=0;

Now, MATLAB indeed returns a

Checking the intermediate outputs,

Bbar = 0.2960 0.1812 0.4881 0.3324 0.3646...is not a scalar, though an row vector with 8 elements. With

`help mean`

we find:
.. For matrices, MEAN(X) is a row vector containing the mean value of each column...Thus, we have to change line 15 to:

15 Bbar=mean(mean(B.^2)')Note, that this command takes the mean of elements of the previously found vector

`mean(B.^2)`

. Hereto, this row vector is first transposed with `'`

. Now, the m-file is working properly.
Esteur 2010-03-22