An instant primer on using MATLAB to plot data                      Humphrey

 

Open MATLAB on your computer (available in student labs).  Things you type are in bold below.  Asides or notes are in red.

 

MATLAB has a highly modifiable interface with numerous possible open views or windows, thus it may look quite different from somebody else’s screen!

MATLAB will open in one or more windows, (they are detachable from the main frame, and thus may appear anywhere on the desktop).

The important windows are ‘Command Window’, ’Help’, and ‘Editor’.  ‘Help’ and ‘Editor’ may not be displayed until you ask for them (by clicking HELP on the menu bar or by clicking FILE-NEW for the Editor).  I generally work with only 3 ‘windows’: the Command window, the Workspace window, and an Editor window.

 

Make sure you locate the main ‘Command Window’ and type into the big empty space (window labeled ‘command window’), and after the ‘>>’ symbol.

 

1. For the newbie, try the below:

 

Try typing

 

x = 2*3

 

MATALB will answer with

x =

        6

>> 

 

The above illustrates using MATLAB as a calculator.  You can use any operators  that you want.  To see a list of the symbols that matlab uses for powers and logs and cosines etc, type ‘help ops’, or ‘help arith’.  

 

A couple of notes might help.

1) any ‘variable’ (eg. a symbol like x or y or m2 or whatever) retains its last value.

In this example x retains its value of 6 from above and can be used again as in:

 

y = x + 3.2

 

matlab should show:

y =

      9.2000

 

2) the ‘=’ sign is slightly different in MATLAB than you may be used to.  It is a right to left assignment statement, In other words ‘=’ in MATLAB makes the left hand side equal the right hand side.  So in MATLAB the ‘=’ sign is NOT symmetric: x=y makes x the same value as y, while y=x makes y the same as x.

 

3) as far as MATLAB is concerned, everything is a matrix.  So x=2 makes x a 1x1 matrix with a single value of 2.  To illustrate this, try entering some data, such as:

 

m = [ 2.3 4 1.2 5 6 7.3 8 5 3.2 1 1.1]

 

(The ‘[‘ braces in matlab indicate that the enclosed data is a vector or matrix.  If you just space each datum, then matlab makes the vector horizontal or a row, if you put a ‘;’ after each datum, matlab will make it a column.)

 

Matlab will respond with:

m =

  Columns 1 through 7

 

    2.3000    4.0000    1.2000    5.0000    6.0000    7.3000    8.0000

 

  Columns 8 through 11

 

    5.0000    3.2000    1.0000    1.1000

>> 

 

This shows that matlab has made ‘m’ a vector of length 11 ( or actually a matrix of dimension 11x1 )   

 

To acess any part of ‘m’, try typing:

 

m(3)

 

matlab responds with:

ans =

          1.2000

 

ans’ is the matlab shorthand for ‘what you wanted to display’.  And what you asked for was the 3rd value in the list or vector ‘m’.

 

 

To plot the data type:

plot(m)

 

matlab responds with ‘>>’ and a separate window that has your plot in it.

 

Matlab will produce a very simple plot.  To place labels on your plot type:

title(‘Stupid Plot’)

xlabel(‘the index number of the data’)

ylable(‘the value of the data in vector m’)

 

Note these labels appear on your plot (the logic is the same as variables, as far as matlab is concerned your plot is just another variable and you can continue to modify it until you dismiss it, or make a new plot).

 

For more details on ‘plot’, type ‘help plot’ or look at the manual(‘help’) pages under ‘plot’

 

 

Usually you want to plot x and y values.  To do this you can enter both into vectors:

x = [ 2 4 5 5.5 6]

y = [-1 0 1 2 3]

 

(x and y have to be the same length!)

And then

plot(x,y)

 

You can of course use the ‘title’ and ‘label’ commands to improve the figure.  In addition you can add various simple commands to the ‘plot’ command such as:

plot(x,y,’r*:’)

which plots your data in red (the ‘r’) and with a star (‘*’) at each point and connects the data with a dotted line (‘:’).

 

There are a huge number of options to ‘plot’ and other plot commands to plot log or semi log plots.  In addition you can use the ‘edit’ function under ‘tools’ in the figure window to change anything you want about the plot to get it to look exactly as you want.  I use Matalb to produce complex, publication quality plots by changing the fonts, line widths, alignments etc.  Unfortunately, since Matlab is so much more powerful than Excel, it also requires much more learning.

 

2. Note on data entry

You can cut and paste data from most sources into Matlab:

D = [‘paste’]

Works just fine, and D will be a copy of your data. Note you have to put the data in between ‘[ ]’s.  You will have difficulty with large amounts of data using this method, so you may have to use the next method.

 

For those of you with some knowledge of computers, any file containing only numbers in a simple format (that is files with the *.txt extension) can be read directly by matlab with

D = load(‘filename.txt’)

 

This works, and D will have your data.  Note that matlab will complain if ‘filename.txt’ does not have a rectangular array of numbers.  It is also necessary to make sure that the file exists in the Matlab search ‘path’.  The easiest way to do this is to make the folder with your file the ‘current directory’ in the tool bar area at the top of the main window. You can also open the FILE menu and click ‘Set Path’, and follow the windows to add your data folder to the search ‘Path’.

 

Final note, if you put a ‘;’ after any command, matlab will not echo the result.  This is useful operating on big data sets.  If x is a long string of numbers, then x=x*2 will print out the entire string, while x=x*2; will just multiply the entire string by 2 quietly.

 

3. Note on Programming

Although you can do a lot in the Command Window, most modeling is done by saving your typing in a file, called a *.m file.  The idea is that anything you would type into the command window, you can type into a *.m file, and then reuse the typing as often as you need.

 

To create an *.m file, open FILE in the menu, and click ‘new’ and select ‘M-file’.  This will open the m-file editor.

You can then type some commands into the file.  Try:

x = 2^0.5       

note matlab doesn’t do anything at this point.

Now you can either save or run the file.  To be pedantic, lets save this useless program. Chose ‘file-save as’, and save it with a ‘somename.m’.  Note matlab saves in a deeply buried folder called ‘Work’ by default, it is better to save in your data folder, so you can find the m-file again.

 

Once you have saved the file, you can execute or run it.  From the editor, click the ‘run’ icon (a page icon with a down arrow before it). It will look like nothing happened, but if you look in the Command Window, you will see:

x =

            1.4142

>> 

Which means your ‘program’ ran and produced a result.

 

You can now run your program anytime, by either opening it in the editor and clicking ‘run’, or by typing the name (without the .m) in the Command Editor.

 

Somename

Results in:

x =

            1.4142

>> 

Which is exactly what would have happened if you had typed the program into the Command Window.

 

 

4. Functions or Subroutines (this is getting a little advanced for a Primer)

Matlab does not have subroutines quite the same as most programming languages.  (this is because Matlab is an interpreter, not a compiler)

Separate blocks of code that can be run by being called from the main program are called Functions in Matlab.  It turns out that most of the things you type into matlab call inbuilt functions (Plot, xlabel etc. are all functions).  You can make your own functions with the editor, and save them as m-files.  The difference between the main program and functions is that functions expect to be invoked with some variables filled in with values.  These input values are the ‘aurguments’ to the function.

 

If you need to use functions, I will be happy to guide you through the details of setting them up.

 

5. Vectors and Matrices

As I pointed out above, all variables in Matlab are (by default) Matrices.

 

To actually use matrices, you will need to understand the ‘:’ operator.  This operator stands for ‘repeat as needed’. It is easiest to understand by example.

 

Try:

x = [ 1 2 3 4 5 6 7 8]

 

Compare with:

x = 1:8

 

Note the results are the same.  The ‘:’ operator basically fills in the gaps in an (assumed) list.

There are many variations of using the ‘:’, some not so obvious:

 

Try:

x = 1:0.5:8

 

This fills in the gaps between 1 and 8 with steps of size 0.5.

Or now that you have x, try:

x(:)

 

Here ‘:’ stands for the full list, but compare with:

x (3:6)

 

Which picks out only the values of x with indexes of 3,4,5,6.  The ‘:’ operator is hugely useful in allowing you to deal with large vectors or matrices of data or results.

 

 

A final digression on vectorization, which can make your code very fast but also unreadable and extremely difficult to debug.

 

Matlab allows many levels of vectorization.  'Vectorization' is basically just that Matlab can repeat obvious commands over a column of data.

This is very much like a spreadsheet type of action.  If an expression contains a 'wild card' character, usually ':', or a specific list of indices into a vector,

Matlab will automatically try to make repeated calculations or assignments.  Some of these methods can save a lot of program space, however

I would advise avoiding constructions that make reading or debbugging the code more difficult.

 

 

Typical vectorization to avoid a simple 'for' loop

 

nodes = 6;

for n=2:nodes-1

            V(n) = 0.5;

end

 

can be replaced with

 

V(2:nodes-1) = .5;

 

However, things can get complex, either with complex calculations or especially with matrix operations.

To illustrate a complex vector operation, consider an attempt to vectorize the factorial function

 

n = 2:max;

V = ones(max,1);

V(n)=n;                                  % V now has the same value as its index

V(n)=V(n).*V(n-1);               % if matlab did this calculation sequentially in n, then this would produce a factorial

 

You might expect this to produce a list of n factorial (up to n=max) in V.  Instead it produces a list of paired products

The lesson is to avoid vectorization that depends on the specific order of the calculations, unless you make it explicit, or really understand

the order of matlab calculations.

 

Matrix operations tend to be not worth the effort to vectorize.

Consider the folling straightforward piece of typical code to create an identity matrix

 

A = zeros(nodes,nodes);

for n=1:nodes

            A(n,n) = 1;

end

 

As soon as we start 'vectorizing' matrices, we need to recognize 2 important points:

1- Matlab 'vectorizes', but does not 'matricize', meaning that the vector commands only operate on vectors (single rows or columns)

2- However, Matlab stores matrices as vectors, and therefore you can 'vectorize' matrix computations but you need to know how the matrix is stored

and you have to do some of the thinking yourself.  This often leads to absolutely impenetrable code that makes no sense after you have written it

and makes debugging very hard.  Matlab stores a matrix A(n,m) (where n is the index into the row, and m is the column) as a vector of concatenated colums,

eg A(n,m) is stored as a vector [ A(1:n,1)  A(1:n,2)  A(1:n,3)  ...  A(1:n,m) ].

 

As a first atempt to vectorize the identity matrix calculation above, we might try

 

j=1:nodes;

A(j,j) = 1;

 

Which gives an incorrect full '1' matrix. (Why?)

 

The correct replacement is not very readable

 

A = zeros(nodes,nodes)

A(1:nodes+1:nodes*nodes) = 1;            % note the non-obvious 'nodes+1' term

 

This is a little obscure, but gives the correct result.

 

Simple vectorization with matrices can save a lot of coding, but I would advise you to put in copious notes to remind you of your previous

brilliance, that tends to look wrong when debugging later on.