A Short Introduction to MATLAB


The purpose of this class is to acquaint new users with MATLAB, which is a software product to do mathematical calculations, read and analyze data, and make graphics. It is a sophisticated product with diverse capabilities, but there are online sources to learn how to use it. This overview is designed to get the student started in its use.

Getting access to MATLAB

ODU has a site license for MATLAB. You can download the package onto your personal computer. This software works with Windows, Mac OS X and linux/UNIX operating systems. Contact me for information about downloading and installing this software.

Starting and Stopping MATLAB

On UNIX computers, just typing matlab at a UNIX prompt will cause a new window to appear which is the MATLAB interface. On a macintosh computer, it will be necessary to start the X window system first and then start MATLAB (some versions of MATLAB will automatically start X11). Double clicking on the MATLAB icon should accomplish both tasks. On a Windows computer, MATLAB starts by double-clicking on the MATLAB icon (either on the desktop or in the "start" menu.

To exit MATLAB, look in the upper left of the window for the "File" menu. At the bottom of this pop-up menu will be an "exit" entry. Choosing this will cause MATLAB to exit and the window will vanish.

Description of the MATLAB window

The MATLAB workspace (window) can have a number of features depending on which version of MATLAB you have installed, the choices make by individual users and by whomever installed the software. Typically, there is a large workspace (command window) in the center of the window. This place is where you will type commands. There are a number of words along the top of the window which have pop-up menus for various actions.

There may be smaller windows on either side of the central command window which have information on variables that have been created, command scripts that exist in the current directory, lists of previously used commands and so forth. These windows can be removed by clicking on the "x" in the upper right corner of the window. There is a way to get these panels back, but I will not discuss that now.

Making calculations and evaluating formulas

MATLAB responds to typed commands. Some commands are available on pull-down menus in various places. The effects of commands are cumulative. That is, results are saved so later commands can work with results created in earlier commands.

Commands are typed into the workspace. These might be assigning values to variables, evaluating mathematical functions, creating graphs and so forth.

Variables are defined by giving them a value.

Pre-defined variables

Some variables with known values are pre-defined. So, if you use the variable pi then you get the expected value of the ratio of the circumference of a circle to its diameter. Similar common variables are e (the base of natural logarithms), i and j (the square root of -1), and others.

Online help and other documents

There are two general ways to get help. If you know the command name and just want a reminder of the options, then type help COMMAND in the command window, where COMMAND is the name of the command you are interested in. This action will produce a few lines to a few pages of details about the given command.

Try help sin to get information about the trigonometric function "sine".

A more comprehensive (web based) help system is available in two ways. Typing doc COMMAND will open the help browser (which is a part of MATLAB) and show you the general help for the command. If you just type doc then the general help window is shown in the browser and you can find the command by various means. Finally, there is a tab called "help" at the top of the MATLAB window which will open the general help browser system.

Script files and the built-in editor

It is cumbersome to enter commands into MATLAB one at a time. In particular if you are doing repetitive work or if you want to preserve the commands for later use. MATLAB allows you to enter all of the MATLAB commands into a file (the file must end in ".m" which identifies it as a MATLAB script file). Then typing the file name (without the ".m") will cause MATLAB to read the file and execute the commands in sequence. When MATLAB gets to the end of the file, it will stop, leaving all of the results that were created and wait for your next command.

The script file can be created with any text editor that makes plain text files (nano, vi, emacs, textedit, etc.). But there is a built-in editor in MATLAB which can be started by clicking on the "Desktop" tab at the top of the MATLAB window and choose "Editor". A new window will open with the editor. The editor commands are somewhat intuitive with arrow keys moving the cursor or using the mouse to move the cursor by clicking on a location. Typing adds text. Delete removes text.

Under the "help" tab on the editor window, there is an entry "Using the MATLAB editor" which will get you started.

Reading simple data files

MATLAB can read a large variety of files, but the details of this capability can be daunting. If your data are in a plain text file and in columns, then there is an easy way to read the data. Note that there cannot be any header line or any text in the file (for this simple method to read data)-- only numbers. There cannot be any missing data items (no blank entries in the columns).

If the file name is "data.dat" and it has columns of numbers (for example, depth, temperature and salinity), then the command

will read the numbers into the variable called data. The character string in the parentheses must be the correct file name. The variable to the left of the = symbol can be anything you want--I use data out of habit. There are no conventions for the file name--any name will work. I use .dat to indicate data files, but any chose (or none at all) will work.

The variable data is a table of numbers with the same shape (number of rows and columns) as the numbers in your file. Continuing the example above, the first column would be the depth, the second and third columns would be the temperature and salinity measured at that depth, respectively.

It is useful to make the variable names more meaningful. So, the following will take the columns of data and put them into new variables. References to specific items in a variable is accomplished with data(r,c) where r is the row number and c is the column number that is desired. For example, data(3,2) would get the value in the third row and second column of the variable.

It is possible to get a range of values using the "colon" notation. So, data(1,1:3) would get the first row and columns 1 through 3.

Finally, to get all values along a dimension of the table, just put a colon in that location. So the first command below extracts all rows of the first column of the variable data.

  clear data
So, there are now three variables with columns of numbers giving the depth, temperature and salinity from the data file. The last command above removes the variable called data since we no longer need it.

Making simple graphs

Simple line plots can be made with the plot command and associated labeling commands. A short example is

  title('Sine Curve')
The first command creates a vector (a list) having the values from 0 to 8 in steps of 0.1. The next line calculates the sine of all values of x and stores the results in the variable y. The plot(x,y) command opens a graphics window, makes choices for the axes and plots the line. The final three commands put a title on the plot and label the x and y axes. Note the use of a single quotes (') to surround text to indicate a character string.

The plot command can create a wide variety of line plots. Some options are given below.

  plot(x,y,x,z)         %    plot two curves
  plot(x,y,'--')        %    plot using a dashed line
  plot(x,y,'r-.')       %    plot using a red dash-dotted line
  plot(x,y,'b',x,z,'g') %    plot two curves using blue and green lines
To get more information about options for this command type help plot. Note that the % symbol indicates a comment. MATLAB ignores any typing after % to the end of the line.

Saving and printing plots

There are two ways to save the plot or make paper copies. The most direct is to use the "File" menu on the graphics window to send the plot to the printer. If you want to save an electronic version, you can print to a file which will save a postscript version of the plot (by default, other choices are available on the save window).

A more versatile option is to use the print command in the command window. This command allows control over the image format and other features of the file that is created. It also will automatically save a figure when it is created so you don't have to remember to do this every time. The command needs two strings as input: device details and file name.

print('-djpeg','sin.jpg')  %  create a jpeg image
print('-dtiff','sin.tif')  %  create a tiff image
print('-dpng','sin.png')   %  create a png (web) image
print('-dpsc2','sin.ps')   %  create a color postscript 2 image
print('-depsc2','sin.eps') %  create a color encapsulated postscript 2 image
The device information is in a string that begins with "-d" and is followed by information on the image type. Use help print to find other options for the file/image format. The endings on the file names are traditional, but have no effect on the format. Other commands or software may care about the ending.

Saving results for later use

The simplest way to save variables and values for later use is with save FILENAME. All of the currently defined variables (names and values) will be saved to a file named "FILENAME.mat", where you can use any string that you choose in place of "FILENAME". The ending ".mat" is required by MATLAB so it will know that the file is a MATLAB formatted file.

If you exit MATLAB and then start it again at a later time, the command load FILENAME will cause MATLAB to read the file and restore all variables and values that you saved.

Sometimes you only want to save certain variables for later use. For example, if you have read a data file and created variables depth, temp and sal, then you can save just these variables with the command save ctd001 depth temp sal which will create a file called "ctd001.mat" which will contain the three variables.

Expanding MATLAB by adding software packages

MATLAB is in common use in the oceanographic community (and a large number of other science groups). There are many packages of routines that accomplish useful tasks (such as calculating density, potential temperatures, oxygen saturation, etc).

A relatively simple general procedure will install these packages:

The next steps

There are many books explaining MATLAB. There are a number of online documents on the MATLAB site about MATLAB (www.mathworks.com/help/index.html ). Documents about basic MATLAB are under the "MATLAB" entry. The other items in the list are special add-on packages from MathWorks, some of which you can get with the ODU license.

There are also a large number of introductory documents and tutorials on the use of MATLAB scattered thoughout the web. A web search on "matlab introduction" or "matlab tutorial" or a similar topic will bring up hundreds of online introductory documents.

send me email