Matlab is a computer program for people doing numerical computation. It began as a "MATrix LABoratory" program, intended to provide interactive access to the libraries Linpack and Eispack. These are carefully tested, high-quality programming packages for solving linear equations and eigenvalue problems. The goal of Matlab was to enable scientists to use matrix-based techniques to solve problems, without having to write programs in traditional languages like C and Fortran. More capabilities have been added as time has passed (especially graphics support for X windows).

Matlab has been called "the lingua franca for the exchange of software and algorithms," rapidly displacing Fortran from that position due to its interactive interface, reliable algorithmic foundation, fully extensible environment, and computational speed. Matlab is available for many different computer systems. A student edition, for Windows and Macintosh, is available from local bookstores at a very economical price.

This document is intended to help you get started with Matlab, running an X windows system and the Unix operating system. It is intended to be used, while sitting at a computer terminal running Matlab. We will not include output, and many of the commands will fail to convey the intended lesson without it.

No familarity with Linear Algebra is required, although some of what we do cannot be fully appreciated, without it.

Matlab is available in the Math Department at WSU on UNIX workstations.

Our first command will make a record of the session, in a file named "session". [The ">>" is Matlab's prompt, you don't need to type it]. Enter:

>> diary session

>> 2+3 >> 3*4, 4^2Powers are performed before division and multiplication, which are done before subtraction and addition.

>> 2+3*4^2The arrow keys allow "command-line editing," which cuts down on the amount of typing required, and allows easy error correction. Press the "up" arrow, and add "/2." What will this produce?

>> 2+3*4^2/2Parentheses may be used to group terms, or to make them more readable.

>> (2 + 3*4^2)/2The equality sign is used to assign values to

>> x = 3 >> y = x^2 >> y/xIf no other name is given, an answer is saved in a variable named "ans."

>> z=2*ans, ansHere

To get a list of your variables, use one of

>> who, whosIn Matlab, like C or Fortran, variables must have a value [which might be numerical, or a string of characters, for example]. Complex numbers are automatically available [by default, both i and j are initially aliased to sqrt(-1)].

>> a=sqrt(2) >> format long, b=sqrt(2) >> a-b >> format shortTo save the value of the variable "

>> save x.value x -asciiTo save all variables in a file named mysession.mat, in reloadable format, use

>> save mysessionTo restore the session, use

>> load mysessionTo find out about this kind of thing, consult the

>> help >> help general >> docFinally, to stop Matlab and logout, use

>> quitWithin Matlab, when using a Unix computer, current saved files (ascii format) from your session can be viewed. For example, to see the file "x.value", type

>> !more x.valueUse of the space bar allows each page of the given file to be viewed in sequence. Use of the "b" key allows the previous page to be viewed.

The names of all of your files from the current (and previous) session(s) will be displayed if you type

>> !lsIf you are in one of the Math Department Labs at WSU, the Unix command "lpr somefile" should send the file with name "somefile" to a printer in that lab. To print this file from within Matlab, type

>> !lpr somefileDo Not Use this command unless you are working in the lab. If you are working remotely (via telnet from some other computer, for example) you can use the Unix mailer to email your file to yourself with a Matlab command of the form

>> !mail someuserid@some.where.else < somefileFor this command to work, you need to substitute your remote email address for "someuserid@some.where.else". You can use this command to send yourself a copy of your "session" file if you have used the "diary" command, but you will need to use the command "diary off" before you email to yourself.

There is also a "web" command which can be used in the lab to access the web

>> web http://www.some.web.addressUse "help web" for further details about the "web" command.

Matlab is designed to make matrix manipulation as simple as possible. Every Matlab variable refers to a matrix [a number is a 1 by 1 matrix]. Start Matlab again, and enter the following command.

>> a = [1,2,3; 4 5 6]Note that:

- the elements of a matrix being entered are enclosed by brackets;
- a matrix is entered in "row-major order" [ie all of the first row, then all of the second row, etc];
- rows are seperated by a semicolon [or a newline], and the elements of the
row may be seperated by either a comma or a space. [
*Caution:*Watch out for extra spaces!]

>> a(1,2), a(2,3)It's very easy to modify matrices:

>> a(2,3) = 10The

>> a' >> b=[1+i 2 + 2*i 3 - 3*i]'New matrices may be formed out of old ones, in many ways. Enter the following commands; before pressing the enter key, try to predict their results!

>> c = [a; 7 8 9] >> [a; a; a] >> [a, a, a] >> [a', b] >> [ [a; a; a], [b; b] ]There are many built-in matrix

>> rand(1,3), rand(2) >> zeros(3) >> ones(3,2) >> eye(3), eye(2,3) >> magic(3) >> hilb(5)This last command creates the 5 by 5 "Hilbert matrix," a favorite example.

Use a **semicolon** to suppress output:

>> s = zeros(20,25);This is valuable, when working with large matrices. If you forget it, and start printing screenfuls of unwanted data, Control-C is Matlab's "break" key.

To get more information on these, look at the help pages for elementary and special matrices.

>> help elmat >> help specmatA central part of Matlab syntax is the "

>> -3:3The default increment is by 1, but that can be changed.

>> x = -3 : .3 : 3This can be read: "x is the name of the list, which begins at -3, and whose entries increase by .3, until 3 is surpassed." You may think of x as a list, a vector, or a matrix, whichever you like.

You may wish use this construction to extract "subvectors," as follows.

>> x(2:12) >> x(9:-2:1)See if you can predict the result of the following.

[Hint: what will x(2) be? x(10)?].

>> x=10:100; >> x(40:5:60)The colon notation can also be combined with the earlier method of constructing matrices.

>> a = [1:6 ; 2:7 ; 4:9]A very common use of the colon notation is to extract rows, or columns, as a sort of "wild-card" operator which produces a default list. The following command produces the matrix

>> a, a(1,:), a(:,2) >> s = rand(20,5); s(6:7, 2:9)Matrices may also be constructed by programming. Here is an example, creating a "program

>> for i=1:10, >> for j=1:10, >> t(i,j) = i/j; >> end >> endThere are actually two loops here, with one nested inside the other; they define t(1,1), t(1,2), t(1,3) ... t(1,10), t(2,1), t(2,2) ... , t(2,10), ... t(10,10) [in that order].

>> t

If necessary, re-enter the matrices

>> a = [1 2 3 ; 4 5 6 ; 7 8 10], b = [1 1 1]'Scalars multiply matrices as expected, and matrices may be added in the usual way; both are done "element by element."

>> 2*a, a/4 >> a + [b,b,b]Scalars added to matrices produce a "strange" result, but one that is sometimes useful; the scalar is added to every element.

>> a+1, b+2Matrix multiplication requires that the sizes match. If they don't, an error message is generated.

>> a*b, b*a >> b'*a >> a*a', a'*a >> b'*b, b*b'To perform an operation on a matrix element-by-element, precede it by a period.

>> a^2, a.^2 >> a.*a, b.*b >> 1 ./ a >> 1./a.^2One of the main uses of matrices is in representing

>> x = a \ bThis can be read "x equals a-inverse times b." To verify this assertion, look at

>> a*x, a*x - bChange b, and do the problem again.

>> b = [1 1 0]' >> x = a\b >> a*x, a*x - bIf there is no solution, a "least-squares" solution is provided [a*x - b is as small as possible]. Enter

>> a(3,3) = 9[which makes the matrix singular] and do those again. [Use the up-arrow, to recall the commands without retyping them].

There is a related problem, to solve x a = b (given a and b), which is done with

>> x = b / aThis can be read "B times A-inverse." Again, if there is no solution, a least-squares solution is found.

There are a number of builtin matrix functions, for example the determinant, rank, nullspace, and condition number.

>> det(a) >> rank(a) >> norm(a) >> null(a)Enter

>> a(3,3) = 10[which makes the matrix nonsingular] and do those again.

A **very useful** function for linear algebra students is `rref`.
This function preforms a reduction of a matrix to reduced echelon form.
Enter

>> rref(a)for an example. Try

>> h=hilb(5) >> cond(a) >> inv(h) >> eig(h)The "eig" function has two forms of output. The last command produced a vector of eigenvalues. The next command produces two matrices, the first containing the eigenvectors as its columns, and the second containing the eigenvalues, along its diagonal.

>> [v,d]=eig(h)The matrix, h, times the first eigenvector, v(:,1), should equal the first eigenvalue, d(1,1), times that same eigenvector.

>> h*v(:,1) >> d(1,1)*v(:,1)"

>> help eps >> epsWe can check the assertion just made about eigenvectors and eigenvalues, as follows.

>> h*v(:,1) - d(1,1)*v(:,1)This is "the zero vector, modulo round-off error."

Matlab has outstanding graphics capabilities [you must be using a terminal which supports graphics, to use them]. Start with

>> x = -10:.1:10; >> plot( x.^2 ) >> plot( x, x.^2 ) >> plot( x.^2, x )Note that x must be assigned values, before the plot command is issued [although you could use

>> plot( x, x.*sin(x) ) >> plot( x.*cos(x), x.*sin(x) ) >> comet( x.*cos(x), x.*sin(x) )Functions of

>> [x y] = meshgrid(-3:.1:3, -3:.1:3); >> z = x.^2 - y.^2; >> mesh(x,y,z) >> surf(x,y,z) >> contour(z) >> help sliceThere's a very interesting example, in the help page for slice; use the mouse to cut and paste it to the matlab prompt.

The following commands bring up lists of useful graphics commands [each has a help page of its own].

>> help plotxy >> help plotxyz >> help graphicsTo

>> print -Plp4to send the current graphics figure to the printer.

Matlab statements can be prepared with any editor, and stored in a file for
later use. The file is referred to as a script, or an "m-file" (since they
must have names of the form `foo.m`). Writing m-files will make you
much more productive.

Using your favorite editor, create the following file, named sketch.m:

[x y] = meshgrid(-3:.1:3, -3:.1:3); z = x.^2 - y.^2; mesh(x,y,z);Then start Matlab from the directory containing this file, and enter

>> sketchThe result is the same as if you had entered the three lines of the file, at the prompt.

You can also enter **data **this way: if a file named mymatrix.m in the
current working directory contains the lines

A = [2 3 4; 5 6 7; 8 9 0] inv(A) quitthen the command

>> mymatrixreads that file, generates A and the inverse of A, and quits matlab [quitting is optional]. You may prefer to do this, if you use the same data repeatedly, or have an editor that you like to use. You can use Control-Z to suspend Matlab, then edit the file, and then use "fg" to bring matlab back to the foreground, to run it.

Matlab may be ran in "**batch **mode," in a very similar way. If a file
named "test.in" contains the [non-graphics] commands you want processed, at
the Unix prompt type:

% matlab < mymatrix.m > homework.outThis is read, "Run matlab, with input from test.in, and output to test.out." The input file does not need to be named "something-dot-m," but it

**Functions **are like scripts, but are compiled the first time
they are used in a given session, for speed. Create a file, named sqroot.m,
containing the following lines.

function sqroot(x) % Compute square root by Newton's method % Initial guess xstart = 1; for i = 1:100 xnew = ( xstart + x/xstart)/2; disp(xnew); if abs(xnew - xstart)/xnew < eps, break, end; xstart = xnew; endSave this file, start Matlab, and enter the commands

>> format long >> sqroot(19)A good exercise would be to create the STAT function described in the help file for function. Note that

>> stat(x)and

>> [m,sd] = stat(x)produce different results.

The "m-files" which came with Matlab provide lots of examples! To find their location, use

>> pathThis will also lead you to some really nifty demos.

Some books which may be useful are

**Matlab Primer**, by Kermit Sigmon [CRC Press, 1994],**Matrices and Matlab, a Tutorial**, by Marvin Markus [Prentice-Hall, 1993],**Solving Problems in Scientific Computing Using Maple and Matlab**, ed. Walter Gander and Jiri Hrebicek [Springer-Verlag, 1993].

This document, as well as other information, is also available from the UCS Stat/Math Center's WWW home page; connect to

http://www.indiana.edu/~statmath

[from the IUB home page, select __University Computing Services__, and then
__Center for Statistical and Mathematical Computing__].

Permission to copy and to make minor changes to reflect local conditions is granted so long as the source is acknowledged, and the author notified.

Prepared by David Hart, Center for Statistical and Mathematical Computing, Indiana University, Bloomington, Copyright 1994, 1995. Last modification: 1/20/95. Minor modifications for WSU Math 220 classes by Alan Genz, Math Department, WSU, with last modification on 8/99.