GEOSC 203: Matlab® Tutorial





Getting Started

There are a couple of different ways to start Matlab on the HPs in the Geoscience Computing Laboratory. Matlab is only licensed to run on farallon, so you'll need to get onto farallon by one of these three methods:

You should see a graphics window flash up on the screen and then disappear. If so, you are all set -- otherwise you need to recheck that you have set your display properly.

To see the graphics window, you just need to plot something. Try typing

>> plot(1:0.5:5)

which will plot the numbers 1 to 5 (counting by 0.5) by their index (1 to 9). As you'll see later, the colon (:) is a shorthand for creating a vector of numbers. You will use it a lot in Matlab.

What is Matlab?

Matlab is a program for doing scientific calculations using matrices. The matrix is the only type of data that can be used, though it may be real or complex. You can also use scalars (1 x 1 matrices) or vectors (n x 1 or 1 x n matrices). What makes Matlab very powerful is that you can perform operations on whole vectors or matrices at one time, without having to loop through each element. Matlab is also quite good at plotting all types of data, which makes it useful for plotting data generated elsewhere.

In this tutorial, we'll go over some of the basic commands, how to read in data, how to save data, how to plot data, and how to create simple programs, called m-files

Getting Help in Matlab

If you get stuck or just need more information about Matlab, there are a number of different resources. The easiest one to use is built into Matlab itself. By typing help or help command, you can get a description of a command or group of commands. Try typing

help plotxy

This gives you a list of all of the 2-dimensional plotting functions available. Another helpful command is the lookfor command. By typing lookfor keyword, you will get a list of all commands related to keyword, even if you aren't sure of the exact function name.

There are also a number of books, including the Matlab manual (in Deike 338) and Getting Started in Matlab by Rudra Pratap (on your reading list). There is also a UFL Matlab primer that can be accessed through the GEOSC 203 home page.

Matlab also has online hypertext (WWW) help, accessible through Netscape or Mosaic by typing doc in Matlab or by clicking here.

The Mathworks (developers of Matlab) also have a WWW site, http://www.mathworks.com, where you can find answers to frequently asked questions about Matlab. There is also a newsgroup, comp.soft-sys.matlab, where you can get more information. The class home pages has links to all of these sites.

Dealing With Variables

Here's a short tutorial on working with variables, taken from the book, Getting Started in Matlab. It is highly recommended that you obtain this book as it will make your life (and your Matlab) easier. Variables in Matlab can have any name as long as you don't use the same name as a Matlab function. Try typing the following into Matlab.


>> 2+2				% Add two numbers
				
ans =				% Matlab uses the default variable
				% 'ans' if you don't specify one
     4

>> x = 2+2			% Assign the value of the expression
				% 2+2 to a variable, x
x =

     4

>> y = 2^2 + log(pi)*sin(x);	% Using a semicolon supresses screen output
>> y				% To get the value of a variable, just
				% type its name.  Note that the value of pi
y =				% is built into Matlab

    3.1337

>> theta = acos(-1)		% Take the arccosine of -1.  Note that 	
				% Matlab uses radians for all its 
theta =				% trigonometric functions

    3.1416

Using Matlab Functions

In the last section, you saw some examples of Matlab functions (e.g. sin, log, acos). Now we will look more at how to create and evaluate functions in Matlab (as you will need to do for this week's lab). First, let's look at how to generate a vector defining our domain, x. We will make x go from 0 to 3*pi.


>> x = 0:0.1:3*pi;		% Make x from 0 to pi in units of 0.1
				%   x is a 1 x 95 matrix
				%           OR
>> x = linspace(0,3*pi,100);	% Do the same using linspace to make
				%   exactly 100 elements

>> beta = 0.5;			% Define a constant, beta, to use
				%   in our function

>> y = beta*erf(x/5);		% Create our function

>> plot(x,y);			% Plot it


Hopefully, your plot looks something like this.

Creating and Working With Matrices

In Matlab, there are a number of ways to create matrices. For example, to create a 3 x 3 matrix with integer elements, I can type it in on the command line:

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

or

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


In any case, the result is the same, the following 3 x 3 matrix stored as the variable x:


x =

1     4     7
2     5     8
3     6     9

You will notice that I used square brackets ([ ]) to enclose the matrix, spaces or commas (,) between elements within a row, and either a semicolon (;) or a hard return between rows.

To access this matrix, I specify the rows and columns I am interested in. Remember how we used the colon (:) to fill in numbers when we plotted numbers from 1 to 5 in the first section? We will use that again. The syntax is x(rows,cols) so, for example, if we want the to assign the element in the third row, first column to the variable y, we type:


>> y = x(3,1);

y =

3
To specify an entire row or column, use a colon (:) in place of the row or column number. So, if we want the entire second column, we would type:

>> y = x(:,2);

y =

4
5
6

Now let's try a short exercise to use matrices and matrix operations. Create a vector of the integers from 1 to 5 and name it a.


>> a = 1:5;
You will notice that I followed the statement with a semicolon, so the result didn't display. But if I want to see the value of a, I can just type its name.

>> a 

a =

1     2     3     4     5
and the value is displayed. If I hadn't assigned the integers to the variable a, Matlab would have used the built-in variable ans. I then could have assigned the value of ans to a by typing a = ans;.

Now lets's add one (1) to each element in a.


>> a = a+1

a =

2     3     4     5     6
Since we added a scalar (1) to a vector, it added 1 to each element in the vector. Generally, though, if we want to add two vectors or matrices, they need to be the same size. Let's create another vector, b and add it to a

>> b = [5 4 3 2 1];
>> a+b

ans =

7     7     7     7     7
For vectors, you need to pay attention to whether you are dealing with row or column vectors. Up until now, we have been using row vectors, but in Matlab, you will find column vectors more common. To change a row vector into a column vector, you can take its transpose by typing a period followed by an apostrophe (.'). For example

>> c = a.'

c =

2
3
4
5
6
Normally when you read in data from a text file, you will read the data into columns. Many Matlab functions are set up to operate on data in a matrix by operating on the column vectors separately. As you'll see in the next section, if we try to plot an entire matrix, Matlab will plot each column as a separate line.

You may have noticed in the last example, that I used a period in front of the apostrophe. That period is very important. It means that I want to operate on each element of the matrix or vector separately. In most of the work you will do, you will want to use a period in front of any arithmatic operator (e.g. .* for multiplication, ./ for division, or .^ for power). For example, if I want to square a matrix, a by multiplying it by itself, I want to type


>> a = 1:5;
>> a.*a

ans =

1     4     9    16    25
instead of

>> a*a
??? Error using ==> *
Inner matrix dimensions must agree.
In the second example, Matlab assumed that we wanted to use matrix multiplication to multply a by itself. That won't work since we would need to multiply a 1 x 5 vector by a 5 x n matrix for it to work. However, we really only wanted to multiply each element in a by the corresponding element in a (hence the period). If you have trouble with this, use the whos command to see the sizes of the matrices you are using. I often try to add or multiply row and column vectors together, and end up having to take the transpose of one of them.

Plotting

Now that we can read in and create data, we need a way to plot it. The main function for making 2-dimensional plots is called plot. To create a plot of two vectors x and y, type plot(x,y). plot is an example of a function that can have variable input arguments: if you give it one argument, e.g. plot(x), then it will plot the vector x as a function of its index. If x is a matrix, then plot(x) will produce a plot of the columns of x each in a different color or linestyle.

That brings us to the third possible argument for plot, the linestyle. plot(x,y,s) will plot y as a function of x using linestyle s, where s is a 1 to 3 character string (enclosed by single quotes) made up of the following characters.

       y     yellow        .     point
       m     magenta       o     circle
       c     cyan          x     x-mark
       r     red           +     plus
       g     green         -     solid
       b     blue          *     star
       w     white         :     dotted
       k     black         -.    dashdot
			   --    dashed
For example, to create a plot of x versus y, using magenta circles, type the command plot(x,y,'mo'); To plot more than one line, you can combine plots by typing plot(x1,y1,s1,x2,y2,s2,...);

As an example, plot a random vector (10 x 1) and an integer vector from 1 to 10 using two different line types.


>> y1 = rand(10,1);         % create a random vector (10 x 1) from 0 to 1
>> y2 = linspace(1,0,10);   % create a vector of numbers from 10 to 1
>> x = 1:10;                % create a vector of integers from 1 to 10
>> plot(x,y1,'w+',x,y2,'r-');
>> title('Test of plot function');   % make a title
>> xlabel('X Axis');        % label the axes
>> ylabel('Y Axis');

Another useful plotting command is called errorbar. The following example will generate a plot of the random vector y1 using an error of 0.1 above and below the line.

>> errorbar(x,y1,ones(10,1).*0.1)    
>> title('Test of errorbar');
>> xlabel('X axis'); ylabel('Y axis');

Labelling the Plot

As you have probably noticed, I have been using title, xlabel, and ylabel to create labels for the top and sides of the plot. They each take a string variable, which must be in single quotes. In the next section, you can see how I used an integer within a string to customize the title. One other labelling function that might be useful is the text function. The following command


>> text(1,10,'Here is some text');
will write the text string 'Here is some text' at the (x,y) position (1,10) in data units.

Changing the Axes

One thing you might want to do with your plot is to change the axes. Normally, Matlab automatically chooses appropriate axes for you, but they're easy to change. The axis command will allow you to find out the current axes and change them.

>> axis

ans =

         0   12.0000   -0.2000    1.2000

>> axis([2 10 -0.2 1.0])
Here I've gotten the current axes and changed them by creating a 1 x 4 vector of [xmin xmax ymin ymax]. Sometimes you will want to switch the order of the Y axis (e.g. if you are plotting depth). Typing

>> axis('ij')
will switch the Y axis for you.

Appending Data to Plots

Sometimes it's useful to be able to add something to a plot window without having to draw two lines with the same plot statement (as we did above). So Matlab has a command, hold which will cause the plot to remain (it doesn't redraw it). Typing hold on will hold the current plot, and hold off will release the plot. Also, hold by itself will toggle the hold state. You might also want to use clf to clear the graphics window and release the window.

Loading and Saving Data

The key to loading data into Matlab is to remember that Matlab only uses matrices. That means that if you want to read a data set into Matlab, all of the rows must have the same number of elements, and they must all be numbers.

Most commonly, you'll be dealing with a text (ASCII) file. If you have a set of data on disk in a file called points.dat, then to load it, you would type

>> load points.dat

at the Matlab prompt. This will load your data into the Matlab variable points, which will appear in the workspace. In the next section, we will discuss what to do with the data once you've read it in. Let's assume that the file points.dat contains two columns, where column 1 is height and column 2 is distance.


>> load points.dat
>> height = points(:,1);
>> distance = points(:,2);

To save the same data into an ASCII file called mydata.dat, type

>> save mydata.dat height distance -ascii
You will note that when Matlab saves files in ASCII format, it uses scientific notation whether it needs it or not.

Creating m-files

In Matlab, you can create a file using Matlab commands, called an m-file. The file needs to have a .m extension (hence the name -- m-file). There are two types of m-files -- scripts and functions. For this lab, we are only going to need to write a script, so we'll worry about functions later.

Running a Matlab script is the same as typing the commands in the workspace. Any variables created or changed in the script are changed in the workspace. A script file is executed by typing the name of the script (without the .m extension). Script files do not take or return any arguments, they only operate on the variables in the workspace. If you need to be able to specify an argument, then you need to use a function. Here is an example of a simple script to plot a function.


% makefunction.m
% script to plot a function

x = linspace(0,pi,25);	% Create variable x from 0 to pi with 150 values
y = erfc(x);		% Take the complementary error function of x
scl = 0.25;		
y = y*scl;		% Scale y by scl
plot(x,y);		% Plot x and y
title('My Script');	% Create a title
xlabel('X');		% Label the x and y axes
ylabel('Y');


>> makefunction


>> whos
              Name        Size       Elements     Bytes    Density   Complex

               scl       1 by 1             1         8       Full      No 
                 x       1 by 25           25       200       Full      No 
                 y       1 by 25           25       200       Full      No 

Grand total is 51 elements using 408 bytes

You will notice that all of the variables used in the script are now sitting in the workspace, so that they can be used again. This is exactly the same as if they had been typed in separately. Matlab scripts are useful to use as throwaway m-files -- even if you only use them once, it makes sense not to waste time typing them in on the command line.

Printing

Saving Your Plot

Once you've created a plot, you will want to save or print it. To print the current plot window to the default printer, type


>> print
It will use the printer defined by your LPDEST or PRINTER environment variables (probably vemalp). To see what it's set to, type

>> !echo $LPDEST
dolomite
If you want to print to a different printer (e.g. the new HP Laserjet IV -- dolomite), type

>> print -Pdolomite

Saving Your Session

One other useful command is the diary command. Typing


>> diary filename.txt
will create a file with all the commands you've typed. When you're done, typing

>> diary off
will close the file. This might be useful to create a record of your work to hand in with a lab or to create a Matlab m-file.

At this point, hopefully, you know enough to maneuver around in Matlab (at least enough to complete the lab).


red ball Go to Matlab online documentation (farallon or vema only)
blue ballReturn to GEOSC 203 Home Page
blue ballReturn to Geodynamics Page