Biological Systems Analysis

51:040 / 51:141

MATLAB syntax and error messages:

 

There are several examples in the following table. The first one (.m.html) has been formatted and syntax highlighted, but will not run as a MATLAB file. The second one (.m) can be downloaded and run from MATLAB. Images can be clicked for a larger version.

Problem
Solution
Getting Help
 help function %Print out the help on how to use a function
 doc function %Open up MATLAB help for the given function
 lookfor string %Look for a string in the help text of all functions
Working Directory

All the functions you want to run must either be in the current working directory, or in the MATLAB path. You can change your working directory with the browse box at the top of the window.

Naming Functions

The name of the file should be the same as the function. Avoid using names of builtin functions.

Example: example.m.html, example.m

Returning Multiple Variables

It is possible to return more than one variable at a time.

Example: more_than_one_return.m.html, more_than_one_return.m

Preventing Display of Variables

A semicolon (;) at the end of the line tells MATLAB not to print the value of the returned variable. This is especially important when dealing with image data as it will take a long time to display.

Example: use_semicolons.m.hmtl, use_semicolons.m

Matrix Multiplication

When trying to multiply matrices or vectors, you will frequently get the following error:

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

There are 2 common conditions when this occurs with vectors.

  1. You want point by point multiplication. Usually with image processing this is the one that you want. Fixing this usually just means using .* instead of just *
  2. You want matrix multiplication (dot product or inner product), but your vectors are not aligned properly.

Example: multiplication.m.html, multiplication.m

Indexing

In MATLAB, the first index into a vector is 1, not 0. This frequently causes problems with people who are used to how C/C++ does indexes.

    ??? Subscript indices must either be real positive integers or logicals.

Also, MATLAB uses parenthesis (), not brackets [] to index into variables. The error returned is a syntax error, so you need to know what to look for.

    ??? vec1[0]
            |
    Error: Missing operator, comma, or semicolon.

And finally, for a matrix (or image), the first index is the row, and the second index is the column. img(row, col) Often, this seems as though you are indexing as img(y, x). To change indexing to img(x,y) use the transpose operator whenever displaying an image imagesc(img');

Example: indexing.m.html, indexing.m

Vector lengths
In MATLAB, slice notation includes the first and last member of the array, so the vector vec = [0:1:200] has 201 points, including 0 and 200. Also, because the first index has offset 1, vec(1) == 0, and vec(201) == 200

Created by: Lina Arbach