Debugging in MATLAB
The following notes provide a basic summary of debugging in MATLAB.
1 Debugging Overview
Debugging is the process of removing or fixing problematic sections of code. This may be as
simple as removing errors or it might extend to more complex tasks of improving robustness or
optimisation (e.g. by resolving memory leaks). Within the context of this course, debugging will
focus on fixing MATLAB code errors.
MATLAB defines two types of problems with code: errors and warnings.
1.1 Errors
Errors are a serious problem for code as the presence of an error will terminate code execution.
There are three different types of MATLAB error: syntax, runtime, and logical . You will
encounter all three types of these errors at some point.
1.1.1 Syntax errors
Syntax errors are errors of language, such as missing a comma or quotation mark or misspelling a
variable/function. The Editor will occasionally indicate a syntax error and provide fixes, however
if executed the Command Line will indicate the error and where possible provide a suggested fix.
Typo: A very simple example of a syntax error is shown in the following example:
1 value = 5;
2 newvalue = valu + 3;
The error thrown by the Command Line is:
Unrecognized function or variable ’valu’.
Error in MyCode (line 2)
newvalue = valu + 3;
The first line is MATLAB identifying the problem - if there is an unrecognised function or variable
that should clue us to the fact we have a syntax error. The second line is MATLAB reporting that
the error is located in the code document ‘MyCode.m’ and the line that the error is located at.
If we click on the underlined filename it will open the Editor to the offending file. If we click on
the underlined line number it will take us to the offending line in that file. The last line shown in
red is just a print of the offending line. The error is clearly that we mistyped the variable ‘value’
as ‘valu’. If we had instead directly run this snippet of code into the MATLAB Command Line
(rather than the Editor), MATLAB provides further help by suggesting a fix:
1
>> value = 5;
newvalue = valu + 3;
Unrecognized function or variable ’valu’.
Did you mean:
>> newvalue = value + 3;
Parenthetical: A major syntax error, and one that will not always return an error as far as
MATLAB is concerned, is a parenthetical error. This is an error caused by incorrect bracketing.
For example you call:
>> A(1
Which may return the error:
Expression or statement is incorrect--possibly unbalanced (, {, or [.
Or more likely
This statement is incomplete.
If we instead called:
>> A(1))
We would get the error:
Invalid expression. When calling a function or indexing a variable, use
parentheses. Otherwise, check for mismatched delimiters.
The key phrase here is ‘mismatched delimiter.’ A delimeter is something which marks a break in
a series (for example a period for written work). As such, a mismatched delimeter could be either
a missing delimeter or you’re mixing different delimeter types.
1.1.2 Runtime errors
Runtime, or execution, errors are errors of code execution. These are typically either arithmetic,
indexing, or assignment mistakes.
Arithmetic: An arithmetic mistake may be an unintended inf or NaN (Not a Number) caused
by dividing by 0. A more complex arithmetic error may be a linear algebra error where array sizes
do not permit certain operations to be performed. For example:
1 A = [1 2 3 4 5;
2 6 7 8 9 10];
3 B = [1 2;
4 3 4];
5
6 C=A*B;
2
The error thrown by the Command Line is:
Error using *
Incorrect dimensions for matrix multiplication. Check that the number of columns
in the first matrix matches the number of rows in the second matrix. To perform
elementwise multiplication, use ’.*’.
Error in MyCode (line 6)
C=A*B;
Related documentation
In this example MATLAB is telling us that the error is from our mathematical operation. It then
explains what the problem is and provides a suggested remedy. It then offers an alternative opera-
tion in case that is what we actually wanted. Again, it allows us to go to the offending file or line of
code and reprints what that line is. In this example, an additional link - ‘Related documentation’
- is available to explore; this link will open a separate window from MathsWorks explaining the
problem in greater detail.
Indexing: An indexing error is an addressing error where the user is trying to call the value of a
variable at an index which does not exist. It may not exist because it exists outside the bounds of
the actual array, or it may not be a possible index. Using the Arithmetic error example, if B(3,3)
were called, the Command Line would return:
Index in position 1 exceeds array bounds (must not exceed 2).
This error is telling us we have an indexing problem and that the problem is because our index
exceeds the array size. It then tells us the limits to the array size. It is worth pointing out that
our index actually exceeds both the row and column count, however MATLAB faults at the first
error and will only call out the first error. If we were to fix that first error and run again it would
fault again, this time on the second index. Under certain conditions MATLAB might only give us
a basic indexing error notification:
Index exceeds matrix dimensions.
This is the same error but with less assistance. Another common indexing error occurs when you
attempt to access an index which is not an integer. This doesn’t make sense but may happen if
you are using mathematical operations on variables to determine an index. For example, if we try
B(1.5,3) we get the Command Line return:
Index in position 1 is invalid. Array indices must be positive integers or
logical values.
As a reminder, MATLAB is column-major. This means for a single index input it will fill column
by column. The index usage in MATLAB follows the rule: (r,c,p) where r is row, c is column, and
p is page (used for 3-D). MATLAB accepts up to n-dimensions, but this shouldn’t be necessary
for this course where we typically only go up to 2 dimensions (row and column). One way to
remember this indexing order is the mnemonic Remote-Control Planes (RCP). You can specify a
variable in a matrix by its row and column (i.e. two numbers) or by its element number (i.e. a
single number). For example, suppose we want to specify the variable in row 2 and column 4 of a
3
matrix that has size 2 × 4. We could do this with (2,4) using row/column indexing, or we could
do it with 8 using element indexing. If the matrix was 2 × 6, we would still reference this element
with (2,4) using row/column indexing, but we would use 10 for element indexing (here the element
number is the number of columns in the preceding rows plus the number of columns in the current
row up to and including the desired value: 6 + 4 = 10)).
Assignment: An assignment error is an error where a mathematical, relational or logical operator
has been used when another type was expected. An example of this is:
1 a=2;
2
3 if a=3
4 disp('Hello World')
5 end
With the error:
File: AssignmentError.m Line: 3 Column: 5
Incorrect use of ’=’ operator. Assign a value to a variable using ’=’ and compare
values for equality using ’==’.
Again the error is telling us the file and location and the type of error occurring. It offers a
suggestion for a fix. The error here was that an if condition requires a relational/logical operator,
not a mathematical operator. So line 3 should be corrected to: if a==3. For a reminder on the
different logical operators, refer to Tutorial Week 1.
1.1.3 Logical Errors
Logical errors are difficult to locate and MATLAB will not return an error message. This is because
this error is a mistake of reasoning by the programmer, not a mistake in the language. An example
of this mistake might be multiplying instead of dividing.
1.1.4 Function Errors
An error which is difficult to classify easily due to the variety of errors is a Function Call error.
Invocation: If you try to call a function that doesn’t exist you will get the clear error:
Unrecognized function or variable ’myFunction’.
This could be construed as a syntax error, which would be true if the function actually existed
and the error is due to a misspelled name, however in this instance the function is unrecognised
because it does not yet exist.
I/O: Remembering that functions have the form:
[out1,out2,...,outN] = myFunction(in1,in2,...,inN)
There are three possible errors relating to input/output:
1. Not providing enough input arguments to the function:
4
Not enough input arguments.
2. Providing too many input arguments:
Too many input arguments.
3. Requesting too many output arguments.
Too many output arguments.
Requesting too few output arguments is not an issue as MATLAB will output as many outputs as
you have assigned to variables, in the order they are written as outputs in the function definition.
Output variables can be skipped by assigning a ~ instead of a variable, which is useful if, for
example, you wanted the first and third output but not the second:
[V,~,W]=eig(K,M)
Debugging these sorts of errors usually requires looking at the function documentation available
from the help function, or Mathsworks website. For your own functions you can write a preamble
which MATLAB will parse for you and provide in-situ help. A handy tip is that if you type a
function into MATLAB and leave it open for a bit before continuing to type, for example, eig(,
MATLAB will bring up a yellow box indicating your possible inputs for the function:
Figure 1: Function suggested fill
1.2 Warnings
Now that we’ve covered various types of MATLAB errors, let’s now move on to MATLAB warnings.
Warnings are, depending on the context, non-serious problems for code. The presence of a warning
will issue a Command Line response from MATLAB but will continue the execution of code.
Understanding the context of warning messages is important as sometimes a warning is expected
but acceptable - and so can be ignored/suppressed - and at other times it is equivalent to an error
- and therefore must be addressed. An example of this is a rank deficiency warning. This could
be a critical error if you are expecting a fully populated result matrix as an answer to a system
of equations that can not change. However, it could also be a non-critical error if you are able to
reduce the order of your system of equations to reflect the lower rank. Consider the code:
5
1 L = [250 100 125 125 100;
2 125 100 125 100 0;
3 125 100 125 100 0];
4 D = [0.3 0.2 0.2 0.2 0.2;
5 0.2 0.15 0.25 0.15 0;
6 0.2 0.15 0.25 0.15 0];
7 K = L/D;
The warning is produced:
Warning: Rank deficient, rank = 2, tol = 5.551115e-16.
> In RankWarning (line 7)
To interpret the nature of this error you would look at the output of K:
K =
1.0e+03 *
0.6003 0.0878 0
0.0572 0.5188 0
3.9130 0.1426 0
and make a decision based upon the intent of the code and the underlying mathematics. As can
be observed the rank deficiency has led to the solution matrix only being solved to rank 2. This
is implying that a third variable is undefined for the input variables.
1.3 Debugging Tools
As much as MATLAB tries to diagnose problems and assist the user, it is necessary at times to
systematically review code in order to fix problems. Various utilities are in place to assist with
this process. The process of debugging revolves around reviewing control flow (how the code is
working) and variable states. Important note: MATLAB Grader does not have good
debugging capabilities. Therefore, when you are attempting your weekly tutorial
assessments you should do your code development and debugging within your local
version of MATLAB. This way you will benefit from the full debugging capabilities
of MATLAB.
1.3.1 Variable State
Seeing what value a variable takes is an important aspect of debugging as it enables the user to
compare values for the maths and operations performed against what they may have worked out
with pen, paper and a calculator. Alternatively, it might enable the user to observe if a particular
value is changing undesirably. The value of a variable can be observed in the workspace section of
the Editor, or else printed to the Command Line.
6
Figure 2: Workspace variables
Two commands exist to print something to the Command Line:
1. The display command:
>> disp(variable)
0.5497
2. The print command:
>> fprintf(’%f\n’,variable)
0.549724
The display command is a straightforward way to display whatever is requested by the function -
the variable/s you want displayed are passed directly to the display function. The print command
requires specific formatting instructions for the output. Here, you write the string that you want
to print (in the example above, this is ’variable’) and, if printing a variable, particular commands
to reference and print them. For example, %f specifies a fixed, floating-point number. To tell
the printer to move to a new line we specify a new line using \n . The use of inverted commas
denotes the string we want printed, and all inputs following the string and comma are the variables
requested by the string.
To further demonstrate here is a more complex example that uses both string and fixed, floating-
point variable types. The example is given in the following snippet of code:
1 s1 = 'The constant pi has the value';
2 s2 = 'when rounded to two decimal places.';
3
4 fprintf('%s %.2f %s\n',s1,pi,s2)
In the above snippet there are two string-type variables, s1 and s2. We want to print a line
which contains both those strings and also the 2 decimal rounded value of π. π is a constant that
MATLAB permanently stores so can be called at any time, hence why it is not defined anywhere.
The fprintf in this example calls the first string (using %s ) followed by the fixed, floating point
(i.e. decimal) of π (it knows to round to 2 decimal places because we specify that with the .2
before the f). It then follows that by a second string (again using %s ) and finishes the line by
moving the print cursor to a new line (using \n ). The output of the above snippet is:
7
The constant pi has the value 3.14 when rounded to two decimal places.
>>
It should be noted here that a lazy, albeit questionably effective way of displaying a variable is
removing the semi-colon after a line of text. This is easy but is questionably effective as it can
easily clutter the Command Line. This is bad as it can bury warning notices, and as such is
generally not recommended.
1.3.2 Control Flow
Assessing control flow usually requires the user to check how the code is running at various places
throughout the program. This is done using breakpoints. Breakpoints are, as the name suggests,
points within the code where execution is suspended (‘broken’). MATLAB enables the user to
set manual breakpoints or automatic breakpoints. Manual breakpoints are always enforced whilst
automatic breakpoints only occur once a condition is met. Additionally, users are able to pause
code execution at any point, or if necessary (such as in the case of an infinite loop) terminate
execution. Termination, pausing and breakpoints are discussed in more detail below.
Termination: Termination is immediate stopping of code execution. It may be necessary if the
code enters a non-advancing state (e.g. an infinite loop). The user terminates code execution with
the keyboard command ctrl + c .
Pause: Pause is a temporary halt to code execution. Pausing of a script may be done via the
code itself using the function:
pause(n)
where n is the number of seconds to pause for. If left undefined, the code will stay paused until
unpaused by pressing any key. Alternatively, pausing may be done via the tool ribbon at the top
of the editor during execution:
Figure 3: Pause button
Additionally, code may be automatically paused when a condition is met. This is again done using
the tool ribbon, but it is set prior to clicking ‘Run’:
8
Figure 4: Automatic pausing options
As can be seen, the script may be paused if an error, a warning, or an exception value occurs.
Manually pausing operates in much the same way as a breakpoint, the user is able to check vari-
ables and ensure the code is running appropriately. Pausing on an error is useful as it allows the
user to observe the variable states as the error occurs, and where the error occurs as it will stop
at the line throwing the error.
When in a pause state caused by clicking pause, or pause on warning/error, the editor enters the
debug state:
Figure 5: Editor debug state
Within this state the user may observe the workspace and systematically step through code to see
that everything is operating as expected. The user can also swap workspaces between the main
code and various functions in the ‘Function Call Stack’. Additionally, the user is able to simply
resume code operation. Rather than trying to use pause to enter this state at the right time, it is
typically better to use breakpoints.
Breakpoint: Breakpoints are markers in the code where code execution will stop until continued
in the aforementioned debug state, or the code is terminated. Breakpoints can be manually set
either by pressing F12 when the cursor is on the desired line, or by clicking the line indicator ‘-’
on the left-hand side of the script in the editor:
9
Figure 6: Line markers and a breakpoint
This will make a red dot appear. It can be removed by clicking on the red dot.
Skip: A user may wish to skip a section of code. This is most easily achieved by commenting out
that section of code (i.e. by placing a % at the start of the line). A shortcut to comment out a line
of code is ctrl + r whilst the shortcut to uncomment a line of code is ctrl + t .
10