Matlab Tutorial

Originally Written by:

Steve McKelvey
Mathematics and Computer Science
Saint Olaf College

for the Envision It! Workshop, April 12, 1997

This tutorial is designed to reacquaint you with the MATLAB ideas initially presented by Tom Huber at the Envision It! workshop held at Arlington High School in late January. My hope is that this material will prove to be good preparation for Tom's follow up workshop on April 12th.

Most of the material in this tutorial is derived from the worksheets presented at the January workshops. These documents can be accessed directly by visiting Tom's homepage at Gustavus Adolphus College. Check under the Envision It! item.

Matrices, Arrays and Vectors

The name MATLAB is a contraction of the phrase "matrix laboratory." While the software has progressed well beyond its original incarnation as a tool dedicated to performing matrix computations, the software is still based on the notation of arrays and matrices.

A matrix is simply a rectangular list of numbers. The "size" of a matrix is given as two numbers, the first is traditionally the number of rows in the matrix while the second is the number of columns in the matrix. Matrices are usually written in tabular form contained between two large parentheses or square brackets.

For example, the matrix below is a 2x3 (this size is read "two by three") matrix without the enclosing parenteses or brackets.

   34   56   31
  -45    6   43

The individual entries in the matrix can be references using subscripts enclosed in parentheses after the name of the matrix. For example, if the matrix above is named A then A(1,2) would refer to the entry in the first row, second column, namely 56.

Arrays, sometimes called vectors, are special cases of matrices, namely arrays have a single row or a single column of numbers. Arrays with a single row of numbers are called row vectors to contrast them with column vectors. Only one subscript is needed to reference a particular entry in an array.

MATLAB and Matrices

To create a matrix and assign it a name within the MATLAB program simply fire up MATLAB and at the prompt enter the matrix's name, an equal sign (=), and an open bracket ([). Next enter the numbers, separated by either commas or blank spaces, which make up the first row of the matrix. If your matrix has only one row, type in the close bracket (]) and hit RETURN. If you have several rows to enter, signify the end of each row with a semicolon before proceeding to enter the values for the next row. (No semicolon is necessary after the last row.) When you have finished entering all the entries of the matrix type a close bracket and hit RETURN. Your matrix should appear on the screen.

As an example, consider the 2x3 matrix given above. To give this matrix the name A we would enter the following at the MATLAB prompt:

A = [ 34 56 31; -45 6 43 ]

MATLAB includes a command which returns the size of an array or matrix. The command is the size command. It returns a row vector whose first entry is the number of rows in the argument and whose second entry is the number of columns.

As an example the command

size(A)
would return the vector [2 3] if A is the matrix defined in the example above.

Tutorial Task A:

  1. Fire up MATLAB on your computer can create two 3x5 matrices and name them tut1 and tut2. The matrix you call tut2 should contain no zeros.
  2. Use the size command to verify the size of the matrices you created above.

Shortcuts for Matrix Creation

Many special matrices appear so frequently that the designers of MATLAB have created shortcuts for creating them.

In some of these examples you may have been overwhelmed with output after you entered the command. One nice MATLAB trick is to suppress the printed output by ending any command with a semicolon. Compare the result of the following two commands

a1 = zeros(100)

a2 = zeros(100);

Tutorial Task B:

  1. Use only the commands ones and diag to create a 5x5 identity matrix.
  2. Create a row vector of all even integers between 5 and 25.

Arithmetic Operations on Matrices

MATLAB's power is in its ability to perform matrix arithmetic very efficiently. MATLAB divides its matrix arithmetic into two varieties. First there are componentwise operations in which the indicated operation is performed on two matrices of exactly the same size and the resulting matrix is also of this common size. The entries in the resulting matrix are calculated by performing the operation on entries occupied the same position within each matrix.

The second type of matrix arithemetic is the more traditional type of matrix multiplication and exponentiation taught in high school and college algebra classes.

Aside from operations on pairs of matrices, MATLAB also allows for operations on a matrix and a scalar, which are non-standard but intuitive.

In the sections below we cover each of these types of arithmetic operations.

Scalar Operations

There are four scalar operations, addition, subtraction, multiplication and division, denoted by the symbols + - * and / respectively. In each case the indicated operation is performed on each entry in the matrix.

As an example, consider the two MATLAB commands shown below:

fdj = [ 1 2 3;5 4 3; 6 5 8 ];
abc = 3*fdj
The matrix abc contains entries created by multiplying each of the corresponding entries of fdj by 3.

Matrix Addition and Subtraction

MATLAB's componentwise matrix addition and subtraction matches the traditional form of the same operations. For two matrices to be added or subtracted they must be of the same size. When two matrices are added the resulting matrix is of the same size as the original matrices. The entries are computed by adding or subtracting the corresponding entries in the two original matrices. This addition or subtraction is indicated to MATLAB by placing a + or - sign between two matrices. For example, the MATLAB commands:

abc = [1 2;3 4]
def = abc - [6 -1; 2 0]
would print out the square matrix with -5 and 3 in the first row and 1 and 4 in the second row. This new matrix would be given the name def.

Componentwise Matrix Multiplication and Division

This notion of matrix multiplication differs from the traditional matrix multiplication taught in advanced algebra classes. In traditional advanced algebra classes the notion of matrix division is defined in terms of multiplication by a matrix inverse. In the componentwise matrix multiplication and division the two matrices must be of the same size. If componentwise multiplication or division is performed on a pair of matrices, the resulting matrix is the same size as the original two matrices. The entries of the new matrix are calculated by performing the indicated operation (either multiplication or division) on the entries from the two original matrices which occupy the identical position in both.

For example, the three MATLAB commands:

abc = [1 2 3; 4 5 6];
def = [1 2 1; -1 3 -2];
abc.*def
create a matrix whose first row has entries 1, 4 and 3. The second row has entries -4, 15 and -12.

Note that MATLAB does NOT use the asterisk to denote this componentwise multiplication. The asterisk, by itself, represents the more traditional form of matrix multiplication. To indicate componentwise multiplication MATLAB uses the dot-star notation, namely a period followed immediately by an asterisk.

The same idea holds for componentwise division. The MATLAB symbol for this is dot-slash (./).

Componentwise Exponentiation

MATLAB uses the dot-carat (.^) to signify componentwise exponentiation. The exponent is a scalar and the .^ operation simply means to raise each entry in the matrix to the indicated power. For example,

abc = [1 2;3 4];
abc.^2
would print out a 2x2 matrix whose entries were 1, 4, 9 and 16.

Tutorial Task C:

  1. Create the matrix fdj as indicated above and determine the result of the following scalar arithmetic operations:
    fdj+3
    fdj-6
    fdj/2
    
    in each case the indicated operation should be performed on each entry of the matrix fdj.
  2. Determine and explain the results of these MATLAB commands:
    abc = 1:10;
    def = 5:14;
    ghi = 3*abc + def
    
  3. Determine and explain the results of these MATLAB commands:
    abc = [1 2 3 4;5 6 7 8];
    def = [4 3 2 1;8 7 6 5];
    abc + def
    
  4. Determine and explain the results of these MATLAB commands:
    tut1 .* tut2
    tut2 .* tut1
    tut1 ./ tut2
    tut2 ./ tut1
    tut1 .^ 2
    

Traditional Matrix Multiplication

The symbol MATLAB uses to indicate traditional matrix multiplication is the asterisk without a dot.

Tutorial Task D:

  1. Determine and explain the results of the following MATLAB commands (compare to the results of the previous task):
    tut1 * tut2
    tut2 * tut1
    tut1 * tut2'
    tut2' * tut1
    tut1 ^ 2
    (tut2' * tut1)^2
    
  2. This exercise demonstrates a quick way to total the entries in a vector. Suppose we have a row vector x with, say, 123 entries in it. The sum of these entries can be easily computed using the MATLAB command:
    x*ones(1,123)'
    
    which multiplies the vector x with the column (after the transpose) vector made up of 123 ones.

    To explore this technique create a row vector with 10 entries, and use the idea above to direct MATLAB to compute the sum of the entries.

  3. Use the idea above, along with the short cut method for creating vectors whose entries have constant stepwidths, to create a single MATLAB command which sums up all the integers from 1 to 100. (HINT: The answer should be 5050.)
  4. What is the sum of all the even integers between 1 and 1001?

Functions Applied to Arrays and Matrices

MATLAB supports a large suite of functions, including the usual trigonometry functions as well as functions designed specifically for matrices, such as the matrix inverse function.

Most of the functions we will use are functions which are often applied to single numbers when used outside the context of MATLAB. An example would be the sine trigonometric function. When applied to a matrix in MATLAB these functions perform in a componentwise fashion. As an example, consider the matrix

nums=[0 5*pi/6 pi/2; pi/6 pi 2*pi]
The command
sin(nums)
would return the 2x3 matrix whose first row is 0, 0.5 and 1 while the second row is 0.5, 0 and 0.

Two Dimensional Plots

To create two dimensional graphs of functions or other data, it is necessary to create two row vectors which contain the x and y coordinates, respectively, of the points to be plotted. MATLAB plot command connects the points indicated by these coordinates with a series of straight lines.

For example, the following three MATLAB commands generate a unit square whose lower left hand corner is the origin.

x = [ 0 1 1 0 0];
y = [ 0 0 1 1 0];
plot(x,y)
While the physical drawing of the square occurs too quickly to watch, MATLAB begins at the origin and draws the square in the direction indicated by the points, in this case counterclockwise.

More traditional mathematical graphs can be created by first defining the range of x values over which you want to graph and then creating a vector which contains a good number of values in this x range. For example, to create a graph of the function
y = sin(x)*cos(x)^2
over the range -2*pi to 2*pi, we could enter the following MATLAB commands:

x = -2*pi:0.1:2*pi;
y = sin(x).*cos(x).^2;
plot(x,y)
Note the componentwise arithmetic here. This is critical to the proper functioning of the plot command.

It is possible to place more than one graph on a single plot. The MATLAB commands below plot both the sine and cosine curve on the same plot.

x=-2*pi:0.1:2*pi;
y=sin(x);
z=cos(x);
plot(x,y,x,z);
You can add additional plots by using the hold command.
hold on
plot(x,exp(x),'--')
hold off
Notice that we changed the line style to dashed. See help plot for other plot options.

Tutorial Task E:

  1. Create a graph of the function y=x/(1+x^2) for values of x between -5 and 5. First divide this interval into ten equal slices for graphing, and then do the same exercise dividing the interval into 100 equal slices. What effect do you see on the resolution of the plot?
  2. What shape does the following set of MATLAB commands generate?
    theta = 0 : 0.05 : 2*pi;
    hold on
    axis('square')
    plot(cos(theta),sin(theta))
    
    When you are finished using the image, type hold off. To see the effect of the axis('square') statement, enter the MATLAB command axis('normal') and redraw the graph.
  3. As a final example, try entering these MATLAB commands. This graph is usually part of a calculus course dealing with polar coordinates.
    theta = 0 : 0.1 : 2*pi;
    r = sin(3*theta);
    plot(r .* cos(theta), r .* sin(theta))
    
    Note the componentwise multiplication used in this problem, indicated by the dot-asterisk (.*) notation.

    As an optional exercise guess what happens if the sin(3*t) term is changed to sin(4*t). Then test your guess by creating the graph.

Three Dimensional Graphs

To create a 3-D graph we need to create three matrices. The first gives the x coordinates, the second gives the y coordinates and the third gives the z coordinates.

These matrices can be created in a series of steps. As an example, let's consider the graph of the function
z = (2 sin(3x))/( (x^2+2)(y^2+1) ).
for values of x and y between -3 and 3.

The steps for achieving this are:

  1. Create a row vector containing the values of x we wish to consider (-3 to 3 in this case) and another row vector containing the values of y we are considering.
  2. Create two matrices which contain x and y coordinates of interest. This is usually accomplished with the meshgrid command.
  3. Create a matrix of the same size as the two created above which contains the z coordinates of the function to be graphed. The formula creating this matrix usually involves componentwise arithmetic operations.

The following MATLAB commands carry out these three steps for the example we are considering.

x = -3:0.2:3;
y = -3:0.2:3;
[X Y] = meshgrid(x,y);
Z = 2*sin(3*X)./( (X.^2 + 2).*(Y.^2 + 1) );
surf(X,Y,Z)
Try these out for yourself and see the results. Note how the formula for Z is related to the mathematics with which we started. See if you can explain why each period in the Z formula must be there.

If you prefer contour maps to surface maps, try the contour command:

contour(X,Y,Z)
and a graph of the contour lines for the function will appear.

Tutorial Task F:

  1. Using the help function of MATLAB, investigate the mesh command.
  2. The function z=cos(2*(x+y)) produces surface plots of calm, peaceful waves. Graph this function for values of x and y between -10 and 10. Use stepsizes on the order of 0.2 or 0.3 when creating your x and yvectors.

Next: Age-Class Population Model