Errors and Warnings

Overview:

  • Teaching: 15 mins
  • Exercises: 5 mins

Objectives:

  • Introduce some common erros messages and warnings that MATLAB produces, and how to interpret them
  • Provide some techniques for debugging code

There's no such thing as a perfect first time

Like all programming languages; so long as you only tell MATLAB to do things it knows how to do, and to do them with things that it knows how to work with, MATLAB will not complain (most of the time). However when writing complex scripts or functions, it is only natural that you will make a mistake from time-to-time. In these cases, MATLAB finds itself in a situation it does not know how to handle, and so decides to stop running your code and attempts to tell you what went wrong.

In this lesson we will look at some of the more common errors (and warnings) that MATLAB can produce, and how to combat them. We will also talk about some methods that you can employ to debug your code, although will not delve into MATLAB's full debugging functionality.

Reading Errors

Being able to read and interpret error messages is central to debugging, but is also something of an art. Let's upset MATLAB produce an error by executing some code that we know will fail:

In [1]:
an_array = rand(1,5); %1-by-5 array of random values

disp(an_array(0)) %display the value at index 0 of an_array
error: an_array(0): subscripts must be either integers 1 to (2^31)-1 or logicals

The command line should produce some red text which is similar to the above:
Array indices must be positive integers or logicals or
Array subscripts must be positive integers or logicals.

Clearly, what we did wrong was told MATLAB to read the value at index 0 in the array an_array, but array indices start at 1 and increase, so the value an_array(0) doesn't exist because we have entered an invalid index, 0. MATLAB has managed to identify this problem, and has told us about this, albeit in a somewhat technical or cryptic way.

(Code) Error Analysis

Read each block of code below, and attempt to identify the error that is going to occur. Then run the code in the command line (or as a short script file) to see how MATLAB tells you about the error.

1) More index problems

an_array = rand(1,5);
disp(an_array(6))

2) Trying times

A = rand(3,3);
b = rand(4,1);

x = A*b;

3) Take it away

v1 = rand(1,5);
v2 = rand(1,10);

disp(v1-v2)

4) Sort your system out!

A = rand(6,6);
A(2:4,2:4) = [1 2 3; 4 5 6; 7 8 9];
b = ones(7,1);

x = A(2:4,2:4)\b(1:3);

Solution

Where's my error?

If you are running a script or function, MATLAB's error messages will also tell you the line (in your script or function file) that it was executing when it ran into the error. Use this information to identify the source of the problem quickly.

Traceback

In the exercise above, the errors came about in the command line. When you start using scripts and functions however, errors can occur within those files too. When this happens MATLAB will also provide you with traceback so you know how you got into the file in which the error occured:

In [6]:
function [z] = pringle_function(x,y,a,b)
%%Evaluates the function z = x^2/a^2 + y^2/b^2

z = (x.*x)./(a*a) + (y.*y)/(b*b);

end %function

x = linspace(0,1,100);
y = linspace(0,1,200);

z = pringle_function(x,y,2,1)
error: pringle_function: operator +: nonconformant arguments (op1 is 1x100, op2 is 1x200)
error: called from
    pringle_function at line 4 column 3

As we can see, the error message spans several lines. We still recieve the explaination as to what caused the error (note that x and y are different lengths), but we are also told that the error came about from code inside the function pringle_function, specifically when trying to execute line 4.

The downside is that, because the error occured inside a function, we don't have access to the variables that caused the error. This is a problem because we might want to look at these variables to identify the problem, and correct our code accordingly.

At this point we should again mention MATLAB's extensive debugging functionality, but sadly we don't have time to dive into it in detail here. However one thing that we will mention are breakpoints - these are markers that can be placed on code lines in the editor window. You can insert a breakpoint by clicking on the space next to the line number in the editor window - a small (usually red) circle will appear there. You can click it again to remove the breakpoint.

Breakpoints in MATLAB

When MATLAB encounters a breakpoint when running code, it will stop and all the variables that it is currently working with will be available for you to look at in the workspace pannel. You will need to hit the prompt that appears to allow MATLAB to continue running the code after the breakpoint. Breakpoints allow you to overcome the inconvenience of loosing access to the variables that were around to cause it.

Alternatives?

If you don't like the sound of breakpoints, or you find yourself encountering an error in a for or while loop, an alternative strategy is simply to use disp and fprintf to print out all the variables that you think might be responsible for the error. Of course, once you fix the error this does mean you'll have to go back through your code and remove all the extra print statements!

Warnings

As you saw in the previous exercise, MATLAB has another kind of message that it can print to the screen if it's unhappy with what you're telling it to do. These are warnings - unlike errors, warnings will not stop your code from running when they are encountered. Instead a warning will allow the code to continue, but will alert you to the fact that something unexpected has gone on in your code. It is important to investigate warning messages when they come up, as the result of code that has warnings in it might not be what you were expecting!

The code in part 4 of the exercise illustrates one such warning:

In [7]:
A = [1 2 3; 4 5 6; 7 8 9];
b = rand(5,1);

x = A\b(1:3);

fprintf('The vector x: \n')
disp(x)
warning: matrix singular to machine precision
The vector x: 
  -0.484259
  -0.019922
   0.444415

The matrix A has determinant zero, so solving linear systems with it is always risky as solutions are not guaranteed to be unique. MATLAB spits out a warning to tell you this, but still goes ahead and performs the calculation to find a solution x and then print it to the screen.

Another example is attempting to evalulate the sine cardindal $$ \mathrm{sinc}(x) = \frac{\sin(x)}{x} $$ function at $x=0$ (it has value 1 here, thank the analysts for that). We can attempt this manually, or by using MATLAB's built-in sinc function:

In [8]:
fprintf('Manually computing the value at x=0: \n')
value1 = sin(0)/0;
fprintf('value1 is %.5f \n', value1)

fprintf('Using MATLAB''s sinc function \n')
value2 = sinc(0);
fprintf('value2 is %.5f \n', value2)
Manually computing the value at x=0: 
warning: division by zero
value1 is NaN 
Using MATLAB's sinc function 
value2 is 1.00000 

MATLAB hasn't given an error, and has run the entire block of code. However it has realised that we are attempting to divide by 0, and has warned us of this. Indeed the answer we get is not the value 1, like we would expect from analysis, but rather is a curious value called NaN (Not a Number) - essentially this is a special variable type that MATLAB uses to store "values which aren't defined" like 0/0. Using MATLAB's in built function for sinc bypasses this problem, as it is constructed to account for this possiblity.

Generally, warnings tend to be a bit easier to read and self-explanitory (provided you know what the code is supposed to be doing!). Conversely they are much more diverse in appearence, unlike errors they don't fall neatly into categories like "index warnings" or "dimension mismatches"; so they do need to be read carefully. If you know which function caused MATLAB to give you a warning, you can use the help feature to read more about the warning and how MATLAB deals with it.

Key Points:

  • Errors occur when MATLAB encounters a problem with the code it is trying to execute, and cannot overcome it.
  • Errors stop the code from running.
  • Warnings are issued when MATLAB encounters something unexpected, but can interpret.
  • Warnings do not stop the code from running, but can produce unexpected results.