Matlab Tutorial 1

Getting Started

In general, Matlab is run by selecting the application from a windows environment, or typing matlab at the command line prompt in a UNIX environment. Once running, Matlab is itself a command line program, wherein you will be given a prompt to type in specific commands.

You should see a splash screen appear 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 plot

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 and Getting Started in Matlab by Rudra Pratap.

The Mathworks (developers of Matlab) also have a WWW site,, where you can find answers to frequently asked questions about Matlab. There is online hypertext (WWW) help here. Information for gaining access to this help is at:

There is also a newsgroup, comp.soft-sys.matlab, where you can get more information.

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

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


>> 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


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


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

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]


>> x = [1,4,7

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 =


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 =


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 =


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 =


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 =


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 =


instead of

>> a*a
??? Error using ==> mtimes
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.


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 10 numbers from 0 to 1
>> x = 1:10; % create a vector of integers from 1 to 10

>> plot(x,y1,'k+',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');

Labeling 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.

Additional Plots

In addition to 2-D plots of lines and symbols, Matlab can create many other neat plots. Below are some examples of plots Matlab can create.

Additional 2-D Plots

Histograms: Matlab can plot bar graphs of binned data to create histogram plots. Try the code below to plot a histogram.

>> x = -2.9:0.2:2.9; % Specify the bins to use
>> y = randn(5000,1); % Generate 5000 random data points
>> hist(y,x); % Draw histogram
>> title('Histogram of Gaussian Data'); % Add title

Polar Coordinates: Matlab can also plot data in polar coordinates. Try the following code for example plot in polar coordinates

>> t = linspace(0,2*pi); % Define t
>> r = sin(2*t).*cos(2*t); % Define r
>> polar(t,r); % Plot data in polar coordinate system
>> title('Polar Plot'); % Add title

3-D Plots

Surface Plots: A surface plot in Matlab takes data in an evenly-spaced x-y grid, with z data at each (x,y) loaction and plots it as a mesh with the regions between the lines of the mesh filled-in. Try using the code below to create a mesh plot similar to the plot at the top of this tutorial.

>> [X,Y,Z] = peaks(30); % Define X,Y and Z
>> surf(X,Y,Z); % Create surface plot
>> xlabel('X-axis'), ylabel('Y-axis'), zlabel('Z-axis'); % Label axes
>> title('Surface Plot'); % Add title

Filled Contour Plots: Matlab can also be used to contour 3-D data (just like contouring elevation data in a DEM). The code below will contour some example 3-D data.

>> [X,Y,Z] = peaks; % Define X, Y and Z
>> contourf(X,Y,Z,12); % Create filled contour plot with 12 contours
>> xlabel('X-axis'), ylabel('Y-axis'); % Label axes
>> title('Filled Contour Plot'); % Add title

Hopefully your plots look similar to those shown above

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.

Common Problem: script not in path
In order to run a Matlab script m-file, you first need to be sure the file is within the path, or list of directories Matlab will search to run a command. For example, if you created a script m-file called foo.m in a directory that was not in the path, when you try to run the script, Matlab would return an error, as shown below.

>> foo
??? Undefined function or variable 'foo'.

In the above example, Matlab cannot find the script foo.m to run it because it is not in the list of directories Matlab searches for scripts and functions. To correct this, you should add the directory the script is in to the path. In windows, this can be done by clicking File-->Set Path... in the Matlab toolbar. To add the folder to search, click Add Folder..., navigate to the folder you want to add, select it, click OK and then click Close to close the Set Path window. You can also add directories to the path from the Matlab Command Window using the path function. In windows, to add a directory to the path from the command line, you type

>> path(path,'C:\path\to\script\location')

Where the first path is the function to add to the path, the second path is stating you want to add to the previous list stored as path and the 'C:\path\to\script\location' is the location of the folder you want to add to the path. In Linux/Unix, you can add paths in a similar way, as shown below

>> path(path,'/home/user/path/to/script')

In addition to changing the path, you may also want to change the working directory. The working directory is the directory where Matlab will store diary files and other saved files by default. Matlab will also look for m-files in the working directory, even though it may not be specified in the path. To change working directories in Windows, you can click on the elipsis button to the right of Current Directory in the Matlab toolbar. You can also change directories from the Command Window in Windows or Linux/Unix using the cd command, as shown below.

>> cd C:\new\working\directory % Windows
>> cd /new/working/directory % Linux/Unix

Now that you understand how to add a directory to the path, 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 25 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

>> makefunction

>> whos
Name Size Bytes Class

scl 1x1 8 double array
x 1x25 200 double array
y 1x25 200 double array

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.


<in revision>

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).

Lab Exercises

The following exercises are designed to help you apply your newly acquired Matlab knowledge and hopefully retain some of the commands introduced above. For each of the exercises you'll be asked to submit a diary of commands you've entered, some code and/or a plot, and a few paragraphs of writing. The exercises are listed below.

Exercise 1 - Fun with matrices

For the first exercise, you should create three 3x3 matrices a, b and c with the following values:
a: top row: 1 5 3, middle row: 5,2,8, bottom row: 4,7,2
b: top row: 3 3 5, middle row: 7 2 4, bottom row: 6 2 3
c: top row: 2 6 8, middle row: 6 3 8, bottom row: 9 9 3
Please use the diary function to create a text file log of the steps you take to create the matrices and provide solutions to the following

1. Add the values in matrix a to matrix b
2. Subtract matrix a from matrix c
3. Multiply the values of matrix b by 4
4. Multiply the values in matrix b with matrix c (I want the product of the values in each location in the matrix. See the example below using 2x2 matrices)

1 2 3 4 3 8
example: multiply 4 3 and 1 2 to get 4 6

For this exercise, please submit a printout of the diary of the problems above.

Exercise 2 - Plotting everyting but the kitchen sinc(?)

For this exercise, you need to create a script m-file that plots the sinc function from 0 to 8π. The sinc function is equal to the sin(π*x)/(π*x). This function is the continuous inverse Fourier transform of the rectangular pulse of width 2π and height 1. You can create a new m-file by clicking on File->New->M-File in the Matlab toolbar. Your m-file should
1. Create a vector x that goes from 0 to 8π by increments of 0.1 and create a variable y that is the sinc function of x.
2. Plot the values of y as a function of x with grid lines in the background of the plot (see help grid for how to use grid lines), label the axes something appropriate and give the plot at title.
3. Contain comments on each line of the code, similar to the examples above, explaining what each line does.

For this exercise, please submit a printout of the script m-file you've written and a printout of the plot the m-file creates.

Exercise 3 - More plotting demos in Matlab

Additional mini-tutorials on numerous things can be found by clicking on Help->Demos in the Matlab toolbar. Under the Demos tab in the Help Navigator section of the Help window, click the plus sign left of MATLAB to expand and then click on the Graphics folder. Play around with both the Line-Plotting and 2-D Plots mini-tutorials. Save your Exercise 2 m-file as a new name such as <uniqname>_lab2_ex3.m and modify it as requested below. Your m-file should
1. Contain the same code plotting the same function with the same variables as in Exercise 2.
2. Include modifications of the plotting portion of the code in three different ways to improve the readability of the plot using what you've just learned. For example, you can change the color/width of the line, modify the axes or their labels etc...

For this exercise, please submit a printout of the script m-file you've written and a printout of the plot the m-file creates.

Exercise 4 - "Decoding" other people's Matlab code

You often don't start from scratch when you start actually working with Matlab to do calculations and/or real science. Most likely, you have some objective for a code you want to create and someone has already created something similar, so you get a copy of their code and modify/expand it to fit your purposes. Obviously, the first step is trying to figure out the existing code and how it works before you can modify it. Copy the m-file called point_locations_for_2DMove.m to your own folder. To view the code in an editor window, simply double-click on the m-file in the current directory section of the main Matlab window. To run the code, go to Debug in the Matlab toolbar and click Run. Please answer the following questions:
1. What is the purpose of the code, what does it do, and does it work properly?
2. What are the commands you recognize in the code?
3. What are the commands you don't recognize?
4. Are the comments sufficient for "decoding" this code as a new user? Why or why not?

For this exercise, please submit a printout of your typed responses to the questions above.