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.
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:
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
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.
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:
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)
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.
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.
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!
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:
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)
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:
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)
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.