Matlab Primer

Getting Started With Matlab:Matlab (tm) is a powerful programming, analysis and plotting program which uses vectors and matrices as its fundamental operating elements. It is therefore very useful for performing data analysis and filtering operations (since you can consider a channel of data to be a long vector). This page begins with some fundamental organizational concepts and is followed by a copy of the JumpStart tutorial from the University of Indiana. For further information, check out the Mathworks. Organizational ConceptsWhen you open Matlab, you will be placed in a commandline window into which you will type your commands. Matlab will recognize a set of standard commands, along with any functions or scripts that you program yourself (Mfiles). It will only recognize your function and scripts if they are stored in the present working directory (type 'pwd') or if you have added their location to Matlab's path (type 'help path' for more info). You can change to different directories by using the 'chdir' command (I think 'cd' also works). The Matlab command window keeps track of any variables you create; to see which variables exist, type 'who'; to clear variables and recover the memory they're occupying, type 'clear all' or 'clear X Y Z' (the latter clears selected variables). To do anything beyond trivial work with Matlab, you need to create and use Mfiles. These files take two forms: scripts and functions. To create either kind of file, open a text editor (such as Notepad or Wordpad) and save the file you create with a name like 'myfile.m'. To run your file, type 'myfile' (along with any function arguments that are required  see below) at the Matlab prompt or in another Mfile. ScriptsA script is simply a listing of commands that you would otherwise enter into the command window. Scripts save you a great deal of time when you're debugging some code or running multiple analyses. Suppose that you're doing some data analysis on a number of different vectors. You could type into the command window the following for each vector you were trying to analyze:
Alternatively, you could write a script that contains all the lines:
If you called this file 'go.m', you could do your analysis by typing in the command window:
In short, scripts simply transcribe their contents verbatim into the command window and have access to all global variables (x in the above example). FunctionsIn contrast to scripts, functions exist independently of the global variable space. You can define input variables and, unlike most programming languages, multiple output variables. For example, the following function returns two vectors representing t seconds worth of samples from a sine and a cosine waveform of frequency f at intervals of delT:
Within the body of the function, only the input variables and any locallydefined variables are available; you have no access to global variables. In the command window (or in another script or function), you can call this function just like any other Matlab function:
Note that the parameters you supply do not have to have the same names as the variables you define in your function, nor do they have to be variables at all  you can simply use numbers (0.001 in the example above). University of Indiana Tutorial: Getting Started With MATLABDavid HartMATLAB 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, highquality programming packages for solving linear equations and eigenvalue problems. The goal of MATLAB is to enable scientists to use matrixbased techniques to solve problems, using stateoftheart code, without having to write programs in traditional languages like C and Fortran. More capabilities have been added as time has passed  many more commands, and very fine graphics capabilities. MATLAB is available for many different kinds of computers. At Indiana University in Bloomington, we have MATLAB on the Windows NT computers in the Student Computing Labs; the SHIPS, NATIONS, and DaVinci clusters of SGI and SUN workstations; and several of the large timesharing systems. A student edition is available from local bookstores for your personal Windows and Macintosh systems. This document is intended to be used while sitting at a computer terminal running either NT or the X windows system. It is assumed that you will enter the commands shown, and then think about the result; if you have any questions, either ask your instructor or send email to the address given at the end of this document. BASICSMATLAB is available at IUB on Nickel, Copper, Chrome and Cygnus, as well as the UNIX
workstations of the Orchard and Ships clusters. To start the program type matlab
at the UNIX prompt. The system should respond (eventually) with: Commands to get started: intro, demo, help help Commands for more information: help, whatsnew, info, subscribe >> Our first command will make a record of the session, in a file named "session.txt". If you're using NT, check that the current directory is one that you can write to: click on File, and Set Path; the current directory should be c:\work or m:\ [your locker]. Type: >> diary session.txt [The ">>" is MATLAB's prompt, you won't need to type it]. Arithmetic uses some fairly standard notation. More than one command may be entered on a single line, if they are seperated by commas. >> 2+3 >> 3*4, 4^2 Powers are performed before division and multiplication, which are done before subtraction and addition. >> 2+3*4^2 The arrow keys allow "commandline 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/2 Parentheses may be used to group terms, or to make them more readable. >> (2 + 3*4^2)/2 The equality sign is used to assign values to variables. >> x = 3 >> y = x^2 >> y/x If no other name is given, an answer is saved in a variable named "ans." >> ans, z=2*ans, ans Here z was defined in terms of ans. The result was called z, so ans was unchanged. To get a list of your variables, use one of >> who, whos In 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)]. All arithmetic is done to double precision [about 16 decimal digits], even though results are normally displayed in a shorter form. >> a=sqrt(2) >> format long, b=sqrt(2) >> ab >> format short To save the value of the variable "x" to a plain text file named "x.value" use >> save x.value x ascii To save all variables in a file named mysession.mat, in reloadable format, use >> save mysession To restore the session, use >> load mysession To find out about this kind of thing, consult the help system. There's even an HTML version! There's also a "lookfor" command, so that you don't have to guess the topic name precisely. >> help >> help general >> doc Finally, to stop MATLAB and return to the operating system, use >> quit Then, to see the saved files from your session, on UNIX systems type the commands: % more session % more x.value Under Windows NT, open the appropriate file with Notepad. MATRICESA matrix is a rectangular array of numbers: for example, [ 1 2 3 ] [ 4 5 6 ] defines a matrix with 2 rows, 3 columns, 6 elements. We will refer you to the Math Department for an explanation of the arithmetic of matrices, what they have to do with anything [they're one of the basic tools of science; the course is called Linear Algebra]. MATLAB is designed to make matrix manipulation as simple as possible. Every MATLAB variable refers to a matrix [a 1 row by 1 column matrix is a number]. Start MATLAB again, and enter the following command. >> a = [1,2,3; 4 5 6] Note that:
The element in the i'th row and j'th column of a is referred to in the usual way: >> a(1,2), a(2,3) It's very easy to modify matrices: >> a(2,3) = 10 The transpose of a matrix is the result of interchanging rows and columns. MATLAB denotes the [conjugate] transpose by following the matrix with the singlequote [apostrophe]. >> 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 builtin matrix constructions. Here are a few: >> 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 in numerical analysis courses. 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, ControlC is MATLAB's "break" key. To get more information on these, look at the help pages for elementary and special matrices. >> help elmat >> help specmat A central part of MATLAB syntax is the "colon operator," which produces a list. >> 3:3 The default increment is by 1, but that can be changed. >> x = 3 : .3 : 3 This 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. >> 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 "wildcard" operator which produces a default list. The following command produces the matrix a, followed by its first row [with all of its columns], and then its second column [with all of its rows]. What do you think s(6:7, 2:4) does? >> a, a(1,:), a(:,2) >> s = rand(10,5); s(6:7, 2:4) Matrices may also be constructed by programming. Here is an example, creating a "program loop." >> for i=1:10, >> for j=1:10, >> t(i,j) = i/j; >> end >> end There 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 MATRIX ARITHMETICIf necessary, reenter 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+2 Matrix 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 elementbyelement, precede it by a period. >> a^2, a.^2 >> a.*a, b.*b >> 1 ./ a >> 1./a.^2 One of the main uses of matrices is in representing systems of linear equations. If a is a matrix containing the coefficients of a system of linear equations, x is a column vector containing the "unknowns," and b is the column vector of "righthand sides," the constant terms, then the matrix equation a x =b represents the system of equations. MATLAB provides a very efficient mechanism for solving linear equations: >> x = a \ b This can be read "x equals ainverse times b." To verify this assertion, look at >> a*x, a*x  b Change b, and do the problem again. >> b = [1 1 0]' >> x = a\b >> a*x, a*x  b If there is no solution, a "leastsquares" 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 uparrow, 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 / a This can be read "B times Ainverse." Again, if there is no solution, a leastsquares solution is found. MATRIX FUNCTIONSThere 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. Other valuable functions find the inverse, eigenvalues and eigenvectors of a matrix. >> 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) >> v*d*inv(v), inv(v)*h*v "Roundoff error" is a primary concern in numerical computing. MATLAB does numerical computation, which is to say, it works with limited precision; all decimal expansions are truncated at the sixteenth place [roughly speaking]. Even if this is acceptable for any single calculation, its effects may accumulate with unacceptable consequences. The machine's roundoff, the smallest distinguishable difference between two numbers as represented in MATLAB, is denoted "eps". >> help eps >> eps We 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 roundoff error." GRAPHICSMATLAB 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 ) >> figure >> plot( x, x.^2 ) >> figure >> plot( x.^2, x ) Note that x must be assigned values, before the plot command is issued [although you could use plot( (10 : .1 : 10) .^ 2 ) if you really really wanted to]. >> plot( x, x.*sin(x) ) >> plot( x.*cos(x), x.*sin(x) ) >> comet( x.*cos(x), x.*sin(x) ) >> plot3(x.*cos(x),x.*sin(x),x) Functions of two variables may be plotted, as well, but some "setup" is required! >> [x y] = meshgrid(3:.1:3, 3:.1:3); >> z = x.^2  y.^2; >> mesh(x,y,z) >> plot3(x,y,z) >> surf(x,y,z) >> contour(z) >> help slice There'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 graphics To print MATLAB graphics, just enter "print" at the MATLAB prompt; the current figure window will be sent to the printer. On some systems, it is necessary to set the environment variable PRINTER, before starting MATLAB. This is done by typing, at the UNIX prompt: % setenv PRINTER=myprinter [for C shell] or $ PRINTER=myprinter; export PRINTER [for Bourne shell] We don't normally do printing during classes! SCRIPTS AND FUNCTIONSMATLAB 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 "mfile" (since they must have names of the form foo.m). Writing mfiles 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 >> sketch The 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) quit then the command >> mymatrix reads 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 ControlZ 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 [nongraphics] commands you want processed, at the UNIX prompt type: % matlab < mymatrix.m > homework.out This is read, "Run MATLAB, with input from test.in, and output to test.out." The input file does not need to be named "somethingdotm," but it must end with "quit"! 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; end Save 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 "mfiles" which came with MATLAB provide lots of examples! To find their location, use >> path This will also lead you to some really nifty demos. FOR FURTHER INFORMATIONThe MATLAB at Indiana University page should be especially useful. The web browser that appears as a result of the "doc" command contains a link to the MathWorks Home Page, which offers answers to Frequently Asked Questions, and more. Manuals for statistical and mathematical software are kept in the Swain and SPEA Libraries, and at the IU Center for Statistical and Mathematical Computing. Some books which may be useful are

This page was last edited on April 04, 2000. 