06-640: Molecular Simulations

Introduction to MATLAB

MATLAB is a commercial program that specializes in numerical calculations, particularly those involving linear algebra (the name is short for MATrix LABoratory). MATLAB also has powerful graphics capabilities and other specialized functions. The main feature of MATLAB that we will use in this course is the fact that short codes can be developed and tested in MATLAB with much less fuss than in programming languages like Fortran or C. As with most software packages, by far the best way to learn how to use MATLAB is to simply start using it and look for answers in documentation as questions arise. This document provides a brief introduction to running programs in MATLAB and gives several pointers to extensive documentation and tutorials that have been developed to support MATLAB.

Running MATLAB

To run MATLAB, type matlab at a UNIX prompt on any of the Andrew UNIX machines.

Running MATLAB Programs

A MATLAB program is simply a text file with the suffix .m, for example, myprogram.m . The text in the program is a list of MATLAB commands. You could execute a program by typing the commands into MATLAB line by line. Inevitably if you do this, an error gets typed in after a few lines and you have to start again. This is exactly why using a program is helpful! To run a program, login in to a UNIX machine and move into the directory where your program is stored. Then start MATLAB and type the name of the program without the .m suffix. For example, type myprogram at the MATLAB prompt. This will execute the entire program.

As an example, create a text file called myprogram.m that contains the following

% My first MATLAB program [any line that starts with

% a "%" sign is a comment line that is not

% executed by Matlab.

% Create a scalar variable called var1 with value 0.7

var1 = 0.7

% Create a second variable but don’t print it’s value

% to the screen

var2 = 0.3;

% Note the semi-colon at the end of the previous line

% Add the two variables together and print the result

add = var1 + var2;

add

Run the program. Experiment with changing details of the program such as what values are printed to the screen, the values of the variables and so forth. The easiest way to do this is to open one window where you edit and save the program and a second window where you run MATLAB.

More Information on MATLAB Syntax and Programming

Information about MATLAB can be obtained from many sources. Online help can be obtained by typing helpwin or helpdesk at a MATLAB prompt. This documentation tends to be comprehensive (in the sense that all MATLAB functions are covered) but terse. Two introductions to MATLAB that are available online are

The Matlab Primer

Getting Started With Matlab

Finally, an excellent way to learn about MATLAB is to figure out how existing .m files, like the ones distributed in class, work.