Matlab for Math 2114H

Practical Issues

Matlab is included in the software pagkage for engineering majors.  It is available at the Math Emporium, or can be purchased from software distribution for $40 + tax.

Matlab looks for and saves files in its current working directory.  When you start Matlab the working directory will be set to some default folder on your computer.  (If you enter the command pwd in the Command Window Matlab will tell you what its current working directory is.)  I recommend that you create a folder to use as your working directory for all your Matlab work associated with this course.  Once you have created this folder there are several ways you can make it your current working directory.
  1. Near the upper right corner of the Matlab window there should be a small grey button marked "...".   If you click that it will let you navigate to your desired working directory.
  2. If you are familiar with the Unix/Linux cd command you can use that in the Matlab command window to move to the desired working directory.
  3. You can create a simple script in Matlab's default startup working directory to make the change to your desired working directory.  The script should be a text with the file extension .m and should contain just one line: cd('name of desired directory') .  (Don't leave out the single quotes.)  I suggest that you first navigate to your desired directory by one of two preceeding methods, then type the pwd command to see exactly how Matlab identifies your directory, and use that for the name of desired directory in your script file.  Suppose your name your script file Math2114H.m .  Then in the future after starting Matlab you can simply type Math2114H in the command window (without the .m) and Matlab will change the working directory to the one you specified in the script.
For homework problems that ask you to use Matlab you should turn in a listing of the commands you used to solve the problem.  One way to do this is using the diary command.  The command diary on will create a text file named diary (with no file extension) in your current working directory and will record in it all the commands you enter as well as their results, and will continue to do so until you enter diary off.  You can then edit that file with any text editor to remove any mistakes and add any comments before printing it to turn in.  (You can make it give the diary file a different name, say commands.txt by using diary commands.txt instead of diary on.)

If any homework problems involve graphical output, the File Menu of the graphics window displaying the graphical output will let you save the graphic in any of several common formats (jpg, eps, ...) which you can then print or incorporate into another document to turn in.  If your computer is connected to a printer you can simply print the graphics window directly.

If you need help with the syntax of Matlab's commands, the small blue question mark in the command window toolbar will open a window in which you can search for help on a particular command or look up various help files by topic.  This information is also available from Matlab's website.



We will demonstrate how to use Matlab for the material of this course as we work through it in class, chapter by chapter, with diaries of demonstrations posted on Scholar.  You should be able to learn what you need for your assigned homework by just following the examples of those in-class demonstrations.  Below is a summary of the Matlab features which are involved, organized according to the chpaters in Leon's book, to help you review or pick up things you might have missed.

Chapter 1: Matrix Entry and Row Operations

Matricies are entered using square brackets [ ].  You enter the values left to right across a row, separating the values by either a space or a comma.  At the end of a row enter a semicolon to begin the next row.  For instance:

>> A=[1,2,3;4,5,5;7,8,0]

A(i,j) refers to the i,j entry of the matrix A.  You can edit the entries of A individually by specifying values for A(i,j).  For instance to change the 2,3 entry to 6 use

>> A(2,3)=6

There are commands to produce special matricies, such as all zeros, all ones, or identity matricies of various sizes:

>> zeros(2,3) for a 2x3 matrix of all 0s;
>> ones(3,1) for a 3x1 matrix of all 1s;
>> eye(4) for the 4x4 identity matrix.

Suppose we are interested in Ax=b where b is a single column (nx1).  We can form the augmented matrix for this system by creating a new matrix consisting of A followed by b.

>> Aug=[A,b]

We could now perform row operations on Aug to solve the linear system.  If we were going to find the inverse of A by row operations we would want to work with this augmented matrix:

>> [A,eye(3)]

Performing Row Operations

You can refer to and change an entire row or column of a matrix by using a colon for the index to be "filled out".  For instance

>> A(1,:) will give the first row of A.

We can use this to preform elementary row operations.  For instance:

>> Aug(2,:)=Aug(2,:)-4*Aug(1,:) subtracts 4 times the first row from the second and makes the result new second row;
>> Aug(2,:)=Aug(2,:)/Aug(2,2) divides the second row by A(2,2);
>> Aug([1,3],:)=Aug([3,1],:) interchanges the first and third rows.

In this way Matlab can be made to carry out row reduction calculations step-by-step.  Matlab will produce the result of the entire process for us with the rref command.

>> rref(Aug)

Inverses, transposes, matrix products and powers are all produced by simple commands.  Note that the transpose uses an apostrophe, not a superscript T.

>> inv(A), A', A'*A, A^2

Controlling the Output

When results are not integers Matlab carries a full 15 significant digits of the decimal representation in its calculations, even though only 4 or 5 are typically dispalyed.  For that reason you should not copy and paste values from dispalyed output, because you will be throwing away a lot of accuracy.  For instance, the result of t=1/3 displays as 0.3333, but 1-3*0.3333 is not 0, while 1-3*t is 0.

You can change the dispaly format if you like.  The command  format long  will cause the full 15 significant digits of results to be displayed.   To change back to the default setting use format short

>> format long; x=1/3011 produces 3.321155762205248e-04
>> format short; x produces 3.3212e-04

Many textbook homework problems are designed so that fractional results involve relatively small denominators.  Matlab has format rational which will display results using approximate fractional expressions with denominators of modest size.  This can be useful if you want to compare with answers that you obtained by hand or as dispalyed in the back of the text.  For example,

>> format rational; x  produces 1/3011

Chapter 2: Determinants

det(A)calculates the determinant of the matrix A.

Chapter 3: Linear Indepdence and Rank

There are several ways to have Matlab check for linear independence of a set of vectors.  Suppose the vectors are the columns of a matrix A.  Linear independence means that Ax=0 has only the trival solution x=0.  So you could see of rref(A) has a leading 1 in every column.  If it does then the vectors are linearly independent.  If there is a column without a leading 1 then the vectors are linearly dependent.

If A is a square matrix then linear independence is equivalent to invertibility of A, so you could check whether det(A) is nonzero.  But this only works for square matricies.

Since rank(A) gives the dimension of the column space, if rank(A) = the number of column vectors then the columns are linearly independent.  (Since rank(A) is also the dimension of the row space, linear independence of the rows is equivalent to rank(A) = the number of row vectors.  That is also equivalent to rref(A) having a leading 1 in every row.)

We sometimes want a description of all solutions to Ax=0.  This is the same as asking for a basis of the null space, N(A).  We know how to work this out by hand from the reduced row echelon form of A.  But we can have Matlab do the work for us with the command null(A,'r').  That will produce a matrix whose columns are the desired basis vectors.  (If you just use null(A) without the 'r' you will still get a basis of N(A) but it will be an orthonormal basis (Chapter 5), not what you would get by hand.  So null(A,'r') is preferable for purposes of this chapter.) 

Chapter 5: Orthogonality and Least Squares

dot(u,v) produces the inner product of vectors u and v, the same as u'*v.  For ||v|| use norm(v)

Solving the normal equations for the least squares solution to Ax=b (Theorem 5.3.2) is easy (proivided A'*A is invertible): inv(A'*A)*A'*b.  There is a special command which will produce a least squares solution (the least squares solution if there is only one): A\b.  If there is a true soluttion A\b will produce one.  (But be careful: unless you already know that a true solution does exist you won't know whether the result of A\b is a true solution or a least squares approximate solution!)

Plotting Approximating Curves

Some examples and problems in Chapter 5 involve plotting an approximate function with coefficients obtained using least squares.  Consider the example on page 230.  The commands

>> x=[-1,0,2.1,2.3,2.4,5.3,6,6.5,8]';
>> y=[-1.02,-.52,.55,.7,.7,2.13,2.52,2.82,3.54]';
>> c=[ones(9,1),x]\y

will calculate the values of c(1) and c(2).  Now we want to plot y=c(1)+c(2)x for -1<x<9.  To do this we need to generate lists of x, y values on the curve and then plot the list of (x,y) pairs:

>> xp=linspace(-1,9,200);
>> yp=c(1)+c(2)*xp;
>> plot(xp,yp)

That produces the line.  To add the data points themselves to the graph:

>> hold on
>> plot(x,y,'.')

Gram-Schmidt

The Gram-Schmidt process can be carried out step-by-step with Matlab.  We will demonstrate this in class.  As the text explains, the Gram-Schmodt process produces the QR decomposition of a matrix.  The Matlab command qr(A,0) will do this for us, except that Leon's requirement that the upper trigangulr matrix R have positive diagonals is not standard, and Matlab doesn't honor it.  The file qrpd.m, which you can find on our Scholar page, defines a command which will produce the positive diagoal version of the QR decomposition, in accord with Leon.  You use it this way:

>> [Q,R]=qrpd(A)

For this to work there needs to be a copy of qrpd.m in your current working directory.

Chapter 6: Eigenvalues and Eigenvectors

Finding the characteristic polynomial by working out the determinant by hand can be tedious.  Matlab's poly command will do it for us.  For instance in Example 4 of page 292:

>> A=[2,-3,1;1,-2,1;1,-3,2]; cpc=poly(A)

produces cpc = [1, -2, 1, 0], which are the coefficients of the characteristic polynomial from highest to lowest powers.  You need to be aware however that for Matlab and many other texts the characteristic polynomial is det(t*I-A), not det(A-t*I) as in Leon. The poly command gives the coefficients of det(t*I-A).  So in the example above det(t*I-A) = t3-2t2+t+0.  This differs from the characteristic polynomial on page 292 by a minus sign.  But the discrepancy won't affect the eigenvalues or eignevectors.

Finding the roots of a polynomial is a difficult task in general.  The characteristic polynomials you will encounter in texbook problems will usually be ones you can factor by hand.  Matlab has a command roots(cpc)which will try to find the roots based on the vector of coefficients (or eig(A) directly from the matrix), but it I don't recommend these for homework purposes because with repeated roots it sometimes identifies two disticnt complex eigenvalues with very small imaginary parts.  One aid to finding the eigenvalues is to simply plot the graph of the characteristic polynomial to visually locate the (real) eigenvalues.  The command polyval(cpc,x) will evaluate the polynomial with coefficients cpc at the values in the vector x.  This can be used to produce a graph of the polynomial.  For instance in our example:

>> x=linspace(-1,2,100);
>> y=polyval(cpc,x);
>> plot(x,y)

Looking at the resulting graph you can "see" the eigenvalues near 0 and 1.  Once you know an eigenvalue, the null command will find the eigenvector(s).  Use the 'r' option to get the same results as you would obtain by hand:

>> null(A-1*eye(3),'r')