MATLAB Programming/Error Messages

From Wikibooks, open books for an open world
Jump to navigation Jump to search



As far as I've seen there is little help out there to help people decipher MATLAB's error messages. Most of the syntax errors are not difficult to fix once you know what is causing them so this is intended to be a guide to identifying and fixing errors in MATLAB code.

Warnings are also shown here as these often lead to errors later.

Arithmetic errors[edit | edit source]

Usually these are self-explanatory. As a reminder, here are some common functions that cannot be performed and what MATLAB returns (along with a warning for each one):

a/0 = Inf if a > 0, -Inf if a < 0, and NaN if a = 0.
log(0) = -Inf
MATLAB defines 0^0 to be 1.

NaN will very often result in errors or useless results unless measures are taken to avoid propagating them.

???Error using ==> minus
Matrix dimensions must agree.

So check the dimensions of all the terms in your expression. Often it is an indexing mistake that causes the terms to be of different size. If you are using power function you might add a single dot after the parameter. i.e. y=x.^2 instead of y=x^2

Matrix multiplication requires the number of columns in the first matrix to equal the number of rows in the second. Otherwise, you get the message:

??? Error using ==> mtimes
Inner matrix dimensions must agree.

Note the difference between this error and the previous one. This error often occurs because of indexing issues OR because you meant to use componentwise multiplication but forgot the dot.

Attempting to take the inverse of a singular matrix will result in a warning and a matrix of Infs. It is wise to calculate the determinant before attempting to take the inverse or, better, to use a method that does not require you to take the inverse since its not numerically stable.

Attempting to take a power of a nonsquare matrix results in the error

??? Error using ==> mpower
Matrix must be square.

This is usually because you meant to use componentwise exponentiation and forgot the dot.

Array Indexing errors[edit | edit source]

Array indexing is a key component of MATLAB. One feature is that the names of variables and functions are case sensitive, and that one can alias builtin or user-written functions with variables of the same name. So, if you make an array called abs and you try to call the function abs(1), MATLAB will return the first value in the array abs instead of the value 1. MATLAB will not return an error for this as it is not possible to know for certain that the aliasing of the function wasn't intentional. Hence, never ever name your variables the same as an existing MATLAB function. Unfortunately, there are so many supplied functions in the base product plus installed toolboxes, remembering all of them is impossible so use which proposedname if you have any doubt the name might be in use previously before defining a new array or function. Later versions of MATLAB with the command completion feature will show the short help information after the opening parenthesis or tab-completion options, using which will aid in avoiding such errors before they arise later in execution by not creating the alias.

Some things are rather obvious but take some practice in avoiding:

You cannot try to access part of an array that does not exist yet.

>> A = [1,3];
>> A(3)
??? Index exceeds matrix dimensions.

Unfortunately, MATLAB doesn't tell you which variable you exceeded the dimensions on if there's more than one so you'll have to check that. This often occurs if, for example, you are using a loop to change which part of an array is accessed, but the loop doesn't stop before you reach the end of the array. This also happens if you end up with an empty matrix as a result of some operation and then try to access an element inside it.

You cannot try to access a negative, complex, noninteger, or zero part of an array; if you do you get this message:

>> A(-1)
>> A(i)
>> A(1.5)
>> A(0)
??? Subscript indices must either be real positive integers or logicals.

Note that MATLAB arrays are 1-based, not 0-based and are fixed lower dimension, not variable. MATLAB may be able to tell you which index is not real or logical depending on context.

 >> y=3*A(-1)
Attempted to access A(-1); index must be a positive integer or logical. 

The latter being an expression is parsed differently and so has the actual array available in the error message.

Also note that if 0 were a logical 0 (false) then the statement A(0) would not be an indexing error but a logical subscripting expression. In this case the return would be the empty [] array as there are no subscripts matching false in the defined set of [1 2] as A has been defined above. A more useful expression would be something like

>> A(A==3)

Attempting to use non-standard MATLAB syntax in your indexing will often result in the error:

>> A(2::, 2)
??? A(2::, 2)
        |
Error: Unexpected MATLAB operator.

The above could be an example of someone trying to access all rows of A after the first one and the second column, in which case you should use the "end" syntax, as in:

>> A(2:end, 2)
ans = 3

Assignment errors[edit | edit source]

Ah, assignment, that is using the = sign to give a variable, or certain elements of an array, a particular value.

Let's start with a classic mistake:

>> a = 2;
>> if a = 3
??? if a = 3
         |
Error: The expression to the left of the equals sign is not a valid target for an assignment.

This error occurs because you meant to see if "a" equaled 3, but instead you told MATLAB to assign "a" a value of 3. You cannot do that on the same line that the if/while statement is on. The correct syntax is

>> if a == 3
>> end

This creates no errors (and you can put anything inside the conditional you want).

You cannot have a normal array with two different classes of data inside it. For example,

>> A = @(T) (1+T)
A = 
   @(T) (1+T)
>> A(2) = 3
??? Conversion to function_handle from double is not possible.

For such a purpose you should use cell arrays or struct arrays.

Here's the tricky one. Take a look at the following code:

>> A = [1,2,3;4,5,6;7,8,9];
>> A(2,:) = [3,5];
??? Subscripted assignment dimension mismatch.
>> A(2,:) = [1,4,5,6];
??? Subscripted assignment dimension mismatch.
>> A(1:2, 1:2) = [1,2,3,4];
??? Subscripted assignment dimension mismatch.

What is happening here? In all three cases, take a look at the dimensions of the left and the right hand sides. In the first example, the left hand side is a 1x3 array but the right side is a 1x2 array. In the second, the left hand side is 1x3 while the right is 1x4. Finally, in the third, the left hand side is 2x2 while the right is 1x4. In all three cases, the dimensions do not match. They must match if you want to replace a specific portion of an existing variable. It doesn't matter if they have the same number of data points or not (as the third example shows); the dimensions must also be the same, with the exception that if you have a 1xn array on one side and an nx1 on the other MATLAB will automatically transpose and replace for you:

>> A(2,:) = [1;2;3]
A =   1     2     3
      1     2     3
      7     8     9

If you do not want this be aware of it!

Struct array errors[edit | edit source]

Struct arrays are rather complex, and they have a rigid set of rules of what you can and can not do with them. Let us first deal with indexing within struct arrays. Suppose you define the variable "cube" and want to store the volume and the length of one side of two different cubes in a struct array. This can be done as follows:

>> cube(1).side = 1;
>> cube(1).volume = 1;
>> cube(2).side = 2;
>> cube(2).volume = 8;

This seems like a good way of storing data and it is for some purposes. However, suppose you wanted to abstract the volumes from the struct and store them in one array. You cannot do it this way:

>> volumes = cube.volume
??? Illegal right hand side in assignment. Too many elements.

You'll notice that if you tell MATLAB to display cube.volume, it will display both values, but reassign the variable ans each time, because it is treated as two separate variables. In order to avoid the error, you must format 'cube.volume' as an array upon assignment.

>> volumes = {cube.volume}

You can also write in a separate assignment for each cube but this is more adaptable to larger numbers of cubes.

Just like extracting data, you must input the data one at a time, even if it is the same for all instances of the root (cube).

>> cube.volForm = @(S) (S^3)
??? Incorrect number of right hand side elements in dot name assignment.  Missing [] around left hand side is a likely cause.
>> cube(:).volForm = @(S) (S^3)
??? Insufficient outputs from right hand side to satisfy comma separated
list expansion on left hand side.  Missing [] are the most likely cause.

Unfortunately missing [] is not the cause, since adding them causes more errors. The cause is that you cannot assign the same value to all fields of the same name at once, you must do it one at a time, as in the following code:

>> for ii = 1:2
>>   cube(ii).volForm = @(S) (S^3);
>> end
>> cube
ans = 1x2 struct array with fields:
  volume
  side
  volForm

The same volume formula is then found in both cubes. This problem can be alleviated if you do not split the root, which is highly recommended. For example, you can use a struct like this:

>> shapes.cubeVol = @(S) (S^3);
>> shapes.cube(1).vol = 1;
>> shapes.cube(2).vol = 8;

This avoids having to use a loop to put in the formula common to all cubes.

Syntax errors[edit | edit source]

Parenthesis errors[edit | edit source]

Unlike in C++, you are not required to terminate every line with anything but a line break of some sort. However, there are still syntax rules you have to follow. In MATLAB you have to be especially careful with where you put your parenthesis so that MATLAB will do what you want it to.

A very common error is illustrated in the following:

>> A(1
??? A(1
       |
Error: Expression or statement is incorrect--possibly unbalanced (, {, or [.

This error is simple enough, it means you're missing a parenthesis, or you have too many. Another closely related error is the following:

>> A(1))
??? A(1))
        |
Error: Unbalanced or misused parentheses or brackets.

MATLAB tries to tell you where the missing parenthesis should go but it isn't always right. Thus for a complex expression you have to go through it very carefully to find your typo. A useful trick is to try to set a breakpoint a line after the offending line. It won't turn red until the error is corrected, so keep trying to correct it and saving the file until that breakpoint turns red. Of course, after this you have to make sure the parenthesis placement makes sense, otherwise you'll probably get another error related to invalid indecies or invalid function calls.

String errors[edit | edit source]

There are two ways that you can create a string; use the ' string ' syntax, or type two words separated by only whitespace (not including line breaks), as in

>> save file.txt variable

In this line, file.txt and variable are passed to the save function as strings. It is an occasional mistake to forget a parenthesis and accidentally try to pass a string to a function that does not accept strings as input:

>> eye 5
??? Error using ==> eye
Only input must be numeric or a valid numeric class name.

These should not be hard to spot because the string is color-coded purple. Things like this occur if you uncomment a line of text and forget to change it.

Forgetting the closing ' in the other syntax for a string results in an obvious error:

>> A = 'hi
??? A = 'hi
        |
Error: A MATLAB string constant is not terminated properly.

The unterminated string is color-coded red to let you know that it is not terminated, since it's otherwise easy to forget.

A common mistake with strings is to try to compare them using the '==' operator. This does not work if the strings are not the same length, because strings are arrays of characters, and to compare arrays with '==' they must be the same size. To compare two strings you must use the strcmp function:

>> 'AA' == 'AaA'
??? Error using ==> eq
Matrix dimensions must agree.
>> strcmp('AA', 'AaA')
ans = 0
>> strcmp('A', 'a')
ans = 0
>> strcmp('AA', 'AA')
ans = 1

Note that MATLAB strings are case sensitive, 'A' and 'a' are not the same string.

Also beware that the ' character for beginning and ending strings is the same character indicating transposition. So if you close a string and don't begin it, you will most likely end up with an error about an undefined variable (if you're trying to transpose an undefined variable) or just get really weird results because you transposed something you didn't intend to.

Other miscellaneous errors[edit | edit source]

You cannot leave trailing functions, and if you do MATLAB gives you an error that is similar but not exactly the same as that for a missing parenthesis, since it doesn't want to venture a guess:

>> A = 1+3+
??? A = 1+3+
            |
Error: Expression or statement is incomplete or incorrect.

These usually are not hard to spot, and often result from forgetting the "..." necessary to split a line.

The double colon is not the only "unexpected MATLAB operator", there is also "..", "....", and several other typos that generate this error.

If you accidentally type the ` character you get the error:

>> ??? `
       |
Error: The input character is not valid in MATLAB statements or expressions.

This usually occurs because you intended to put a "1" in the equation but missed the key. Another possibility is that you named your m-file with unusual letters for computers. Like in Germany "ä, ü or ö". Be sure to name your m-files only with usual letters and no capital letters.

Function Calling errors[edit | edit source]

It is quite possible to try to call a function that doesn't exist, such as:

>> samplemat = [1 2; 1 4]
>> A = eigen(samplemat);
??? Undefined command/function 'eigen'.

This can happen because you do not know the name of the function that performs the operation intended (for example, if you wanted to compute the eigenvalues of matrix "samplemat", you would want to call eig, not eigen). It is often useful to pull up MATLAB's help (go to help -> product help or type doc into the command prompt) and do a search for the operation you want.

If you're trying to call a function you created and you get this error, there are several possible reasons:

  1. The m-file must be in one of the paths listed under file -> set path, or must be in your current directory
  2. The m-file must have the same name as the name in the function declaration. You must be aware of this especially if you change the name of your functions, you must also change the name of the file or MATLAB will not find the right function!

If MATLAB finds the function, it will attempt to run it. However, there are several potential pitfalls to avoid in calling functions. It is necessary to know the nature of the input and output arguments of a given function in order to call it. For MATLAB's built-in functions, this information is found in the documentation, or by typing

>> help functionname

It is a good idea to set up some comments so that the help function can read them in your own code as well, so you can keep track of how all your functions work and what they do at a quick reference. To do this, note that the help function reads only the block of comments directly under the function declaration, so for example, if you write a function like this:

function outvars = myfunc(invars)
% function outvars = myfunc(invars)
% Outputs outvars
% All of this is outputted when you type >> help myfunc 

% But this wouldn't be

save the function as "myfunc.m", and type

>> help myfunc

it will output:

>> function outvars = myfunc(invars)
Outputs outvars
All of this is outputted when you type >> help myfunc

Most functions (not all however) require at least one input argument, and calling it with too few will result in an error:

>> A = ode45()
??? Error using ==> ode45
Not enough input arguments.  See ODE45.

You cannot call a function with too many input arguments either:

>> A = plus(1,2,3)
??? Error using ==> plus
Too many input arguments.

Input arguments must be in a format expected by the function. This will be very function-specific, so see the documentation or help for details on what they expect. For example, the first argument to ODE45 and other ODE solvers has to be the function handle; if you pass arguments in the wrong order you will be given an error to that effect.

You can choose how many of the output arguments you want out of those available by using the bracket notation. You can choose to save fewer outputs than the function offers, but you cannot assign more variables than the function can output:

>> A = [1,2;3,4]
D = eig(A); %one output argument
[V,D] = eig(A); %two output arguments
[V,D,Mistake] = eig(A);
??? Error using ==> eig
Too many output arguments.

All assigned output arguments must also be of the correct class if you are replacing parts of an array that already exists (see the section on assignment for more on this). If you're creating a new variable with the output, this is not an issue.

Control Flow errors[edit | edit source]

The most common one by far is if you forget the 'END', which is an issue in M-file functions. It will tell you that 'at least one END is missing' and try to tell you where the loop or conditional statement starts.

If you have too many END statements and more than one function in an M-file, MATLAB may give you a cryptic message about not formatting the functions correctly. This is because all functions in the same M-file must either end with an END statement or not. It doesn't matter which, but if you have too many END statements in one of the functions, MATLAB will think your function is ending early and will get confused when the next function in line does not have an END statement at the end of it. So if you get this confusing message, look for extra END statements and it should fix your problem. If the message is displayed when publishing, say to an HTML file, the problem may be an erratic hierarchical indentation. Try selecting all and then hitting cntrl-i for automatic indentation to fix the problem.

Having an extra END in a 'switch' statement gives a message that you used the 'case' keyword illegally, because MATLAB thinks you ended the switch statement early, and 'case' has no meaning outside a 'switch' statement.

Other errors[edit | edit source]

There are numerous types of errors that do not generate errors from the MATLAB compiler, which have to do with calling the wrong function, using the wrong operation, using the wrong variable, introducing an infinite loop, and so on. These will be the hardest to fix, but with the help of the MATLAB debugger, they will be easier to find. See Debugging M Files for details on how to use the debugger.

Detecting or planning an error[edit | edit source]

No matter how accurate the programming is, errors might happen. Using debug techniques are to great help, but planning an error or expecting an error could prove to be just as valuable. This includes making a possibly unneeded if block to decide what to do. I.e. if x < 5 do this and x > 5 do something else. Also inside the big loops add an if block with modulo, like: if not ( mod ( ii , 5 ) ) % do something; end. Now the loop only does a test for every ii counter which can be divided by 5 without any remainder after the division. Some syntax errors or logical errors inside a loop happens after looping for a long time, if an error happens then the error message is displayed, explaining where it happened but not necessarily why it happened. I.e. vector x is one element shorter than element y, and x .* y could not happen. This mistake often happens on the last element in the shortest vector, and is quite difficult to discover unless measures are taken. try % do something; catch me me.getReport; then a breakpoint and even disp(me.getReport) will help in this situation. If the error is not fatal the code may even continue, but instead displaying the error as a message or it could be converted to a warning.

Included Matlab tools / functions: warning, lastwarn, disp, try catch, dbstack, rethrow, throwAsCaller and Matlab help on the above functions to discover pros and cons for each method.