Using MATLAB 4 - Arizona State Universityrpacheco/RES/PUB/matlab.pdf · Using MATLAB 4.2 Tutorial, ... more control paged output in command ... You can restore this workspace the

  • Upload
    lamkiet

  • View
    224

  • Download
    0

Embed Size (px)

Citation preview

  • Using MATLAB 4.2

    Tutorial, Training Material, and Reference DocumentJune 19, 2000

    Author: Rafael PachecoEditor: Linda Arnesonc2000, Department of Mathematics, Arizona State University

    1

  • Contents

    1 Introduction 4

    2 Basic Concepts 4

    2.1 Starting and quitting MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

    2.2 Arithmetic and MATLAB functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

    2.3 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

    2.4 Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

    2.5 Shell escape and the UNIX command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

    2.6 On-line help and demo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

    3 Matrix Operations 9

    3.1 Transpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

    3.2 Inverse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

    3.3 Multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

    3.4 Matrix division . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

    3.5 Matrix powers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

    3.6 Element by element operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

    4 Matrix Manipulation 10

    4.1 Increment operator (:) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

    4.2 Generating matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

    4.3 Subscripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

    4.4 Reshaping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

    5 Disk Files 12

    5.1 Save and load . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

    5.2 File manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

    5.3 The diary command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

    6 Importing ASCII data 13

    7 Graphics 13

    7.1 X-Y plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

    7.2 Graphic window control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

    7.3 Movies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

    7.4 Graphic input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

    7.5 Creating hardcopy of MATLAB figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

    7.6 Line and mark styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

    7.7 Polar plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

    2

  • 7.8 3-D line plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

    7.9 3-D mesh surface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

    7.10 Viewpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

    7.11 Contour plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

    7.12 Color maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

    7.13 Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

    7.14 Bar charts, stairstep plots, and histograms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

    8 Sound 18

    9 Control Flow 19

    9.1 For loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

    9.2 While loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

    9.3 If statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

    10 M-files 20

    10.1 Script file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

    10.2 Function file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

    11 The MATLAB debugger 22

    12 Order of calls 23

    13 Running MATLAB in the background 23

    14 Other MATLAB functions and toolboxes 24

    3

  • 1 Introduction

    MATLAB1 (MATrix LABoratory) is a matrix-based program for scientific and engineering calculations. You can useit interactively, write script or function files for it, or run it in the background in a batch mode. An outgrowth of theLINPACK and EISPACK projects, MATLAB has been evolving for a number of years to the current system, which cansolve complex numerical problems.

    The purpose of this document is to help you learn MATLAB. As you read, you are encouraged to work at the computerand freely experiment with the examples. Throughout the document you will find tables of MATLAB functions. Thefunctions listed in these tables are by no means complete; they only list the most commonly used functions. For moredetailed descriptions of functions, consult the on-line help facility or copies of MATLAB Users Guide and MATLABReference Guide, which are available for review from a cluster lab consultant.

    2 Basic Concepts

    2.1 Starting and quitting MATLAB

    You need to be in the X Window System or Open Windows environment to run MATLAB. (You can run MATLABfrom terminal consoles but you will not be able to see the graphics.) If you are not familiar with the X Window Systemor OpenWindows, see the OIT document U1030 Introduction to Sun UltraSPARC Cluster for introductory information.To get the most benefit from MATLAB, use a computer with a color monitor. Certain parts of this document regardingcolor display may not be applicable if you use a computer with a monochrome monitor.

    To start MATLAB, type matlab at the UNIX prompt.

    The MATLAB prompt

    will be displayed.

    In a multiple window environment, you may want to start MATLAB in one window and your editor in another. InOpenWindows shelltool or X Windows xterm, the up () and down () arrows help you call commands that you havetype previously. If you type part of a command before pressing the () arrow, you get the last command that startedwith the specified string. In OpenWindows commandtool, these arrow keys do not work, but MATLAB has a commandline editing facility. To learn more about the command line editing facility, type

    You can use the function more to control the paged output of the command window. For example,

    displays twenty-four lines of the output at a time. As with UNIXs more command, pressing the space bar advances tothe next page, pressing q exits the current item, and pressing other keys advances to the next line. Unfortunately, youcannot scroll back.

    To exit MATLAB, type exit or quit at the MATLAB prompt.

    2.2 Arithmetic and MATLAB functions

    The basic arithmetic operators in MATLAB are:

    For example,1MATLAB is licensed by the Math Works Inc., South Natick, MA 01760

    4

  • Arithmetic Functions+ addition negation and subtraction multiplication/ right division\ left divisionhat exponentiation

    Some mathematical functions in MATLAB are:

    Elementary Math Functionsabs absolute value of complex magnitudeangle phase anglesqrt square rootreal real partimag imaginary partconj complex conjugateround round to nearest integerfix round toward zerofloor round toward ceil round toward sign signum functionrem reminder or modulusexp exponential base elog natural logarithmlog 10 log base 10sin, acos, tanh samples of trigonometric functions

    Special Functionsbessel Bessel functiongamma complete and incomplete gamma functionrat rational approximationerf error functioninverf inverse error functionellipk complete elliptic integral of the first kindellipj Jacobian elliptic functions

    2.3 Variables

    In MATLAB, variables are created automatically by assignment statements. For example,

    creates a scalar variable A. The semicolon (;) ends the statement and suppresses the display of the output. Without thesemicolon, the output is displayed.

    Note that MATLAB is case sensitive, A 6= a.

    MATLAB supplies some predefined constants:

    Imaginary numbers are entered as they are normally written, for example, 4i, 3 + 2j.

    5

  • Special Valuesans answer when expression is not assignedeps floating point precisionpi i, j

    1

    Inf NaN Not-a-Numberclock wall clockdate datetic, toc stopwatch timer functionsflops floating point operation countnargin number of function input argumentsnargout number of function output arguments

    To create a matrix variable, use brackets [ and ].

    creates a 3 3 matrix A.

    If a variable is assigned more than once, the last value assigned is retained. For the above examples, the latest A is the3 3 matrix.

    You can display the value of a variable by typing the variable without a semi-colon.

    You can also create the matrix A in a different way.

    You can use a variable on the right hand side of an assignment statement, for example,

    2.4 Workspace

    The collection of variables in a MATLAB session is called the workspace. To list the variables in the workspace, typewho. To list the variables with their sizes, type whos. To delete a variable from the workspace, type clear variable.Typing clear by itself clears all the variables from the workspace.

    6

  • 2.5 Shell escape and the UNIX command

    A shell escape is a facility to run operating system commands from inside a program. MATLABs shell escape is theexclamation mark (!). For example,

    compiles prog.f and then returns to MATLAB.

    The command unix(unix command) executes a UNIX operating system command. The statement returns theresulting status as an integer (0 if the command succeeds, non-zero otherwise) and the standard output in a stringvariable for the UNIX command.

    Special Characters= assignment statement[] used to form vectors and matrices() arithmetic expression precedence. decimal point... continue statement to the next line, separate subscripts and function arguments% comments: subscripting, vector generation! execute operating system command; end a statement, suppress output display

    2.6 On-line help and demo

    You can get on-line help on a MATLAB function by using the command help topic. For example, to get instructions onhow to use the help facility, type

    To get instruction on how to use MATLABs eigenvalue function, type

    help by itself gives you general information and lists available commands and functions. A more user friendly helpfacility which uses Mosaid is now available. To invoke it type

    You can find all functions in all directories accessible to MATLAB that might have been something to do with a givenkeyword using the function lookfor. For example,

    finds all functions that relate to eigenvalues or eigenvectors.

    Note:

    For a function to be related to a keyword, it must contain that keyword in its first comment line (called the H1

    7

  • line). There is more about this in Section 10.

    Lookfor takes a long time to execute because it reads all accessible files.

    Typing

    displays general information about MATLAB and MathWorks, Inc. It also provides e-mail addresses for technicalquestions, bug reports, mailing list, and so forth.

    You can preview some of the features of MATLAB by entering

    General Purpose Commandshelp help facilitydemo run demonstrationswho list variables in memorywhat list m-files on disksize row and column dimensionslength vector lengthclear clear workspacecomputer type of computerC local abortquit terminate programexit same as quitclc clear command screenhome home cursorformat set output display formatdisp display matrix or textfprintf print formatted numberecho enable command echoingmore control paged output in command windowunix Executive UNIX command; return result

    8

  • 3 Matrix Operations

    3.1 Transpose

    3.2 Inverse

    3.3 Multiplication

    3.4 Matrix division

    Note that these operations do not use the computationally intensive matrix inverse calculations.

    3.5 Matrix powers

    Integer powers of a matrix are calculated by multiplying the matrix by itself.

    If the power is not an integer, calculations of eigenvalues and eigenvectors are involved. A scalar can be raised to eithera scalar or matrix power, but a matrix can only be raised to a scalar power.

    3.6 Element by element operations

    Matrix operations can be performed on an element by element basis. These are done by preceding each operation symbolwith a period (.).

    9

  • Matrix Functionsexpm matrix exponentiallogm matrix logarithmsqrtm matrix square rootfunm arbitrary matrix functionspoly characteristic polynomialdet determinanttrace tracekron Kronecker tensor productcond condition number in 2-normnorm 1-norm, 2-norm, F-norm, -normrank rankrcond condition estimatecross cross product of three-element vectorsdot dot product of three-element vectors

    4 Matrix Manipulation

    4.1 Increment operator (:)

    Use the operator : to create a vector with incremental values. If you do not specify the increment, it assumes an incrementof 1.

    Use logspace to generate a logarithmically spaced vector.

    generates a vector x with logarithmically spaced elements from 101 to 103. diag (A) returns the diagonal of matrix A

    10

  • 4.2 Generating matrices

    Special Matricescompan companiondiag diagonaleye identitygallery esoterichadamard Hadamardhankel Hankelhilb Hilbertlinspace linearly spaced vectorslogspace logarithmically spaced vectorsmagic magic squaremeshdom domain for mesh plotsones constantrand uniformly distributed random elementsrandn normally distributed random elementstoeplitz Toeplitzvander Vandermondezeros zero

    4.3 Subscripting

    You can use the statement A(r, c) to choose specific elements of matrix A.

    Specify a range of elements by using the colon (:) operator.

    11

  • 4.4 Reshaping

    You can change a matrix into another using reshape.

    5 Disk Files

    5.1 Save and load

    You can save the workspace for later use by typing save. Typing save by itself saves all the variables in a file namedmatlab.mat. You can restore this workspace the next time you invoke MATLAB by executing load. The commandsave filename or load filename stores or loads the current variables in or from the file filename.mat. Typing savefilename X saves only variable X, and typing save filename X Y Z saves X, Y, and Z. Typing load temp retrieves allthe variables from the file names temp.mat. You can use the -ascii option to save a variable in the ASCII format. Forexample,

    creates an ASCII file called temp.dat that contains

    5.2 File manipulation

    File manipulation commands in MATLAB are:

    Table 1:MATLAB Function UNIXdir directory of files on disk lstype list file catdelete delete file rmcd change directory cd

    Pathnames and wildcards may be used in the same way as in UNIX or DOS.

    5.3 The diary command

    Sometimes you need to save a MATAB session for inclusion into FORTRAN programs, reports, or other documents usinga word processor. The diary filename command saves your MATLAB session in a file named filename. Type diary offto suspend it, and diary on to turn it back on. Typing diary by itself toggles the diary states.

    12

  • Disk Filesdiary diary of the sessionload load variables from filesave save variables on filewhat show m-files on diskfprintf write to a filepack compact memory via save

    6 Importing ASCII data

    Suppose that you have an ASCII file called temp.mat that contains 1000 records:

    You can read the data in and a 10004 matrix temp will be created to accommodate the data (the name of the variablewill be the same as the name of the file).

    7 Graphics

    7.1 X-Y plots

    The following types of X-Y plots are available:

    X-Y Plotsplot linear X-Y plotloglog loglog X-Y plotsemilogx semi-log X-Y plotsemilogy semi-log X-Y plot

    You can put text on the graph with the following commands:

    Graph Annotationtitle plot titlexlabel x-axis labelylabel y-axis labelzlabel z-axis labelgrid draw grid linestext arbitrarily positioned textgtext mouse-positioned textginput graphics input

    The following commands

    13

  • produce the graph in Figure 1.

    7.2 Graphic window control

    Graph axes are automatically scaled by default, but you can control the axes scaling by the command axis. Typingaxis([-10,10,0,20]) scales the x axis from -10 to 10 and the y axis from 0 to 20.

    Normally, each plotting command starts by clearing the graph window and finding fresh auto-ranging axis limits beforedrawing the new lot. You can hold the current plot on the graph window and freeze the axis scaling with the commandhold. Subsequent plot commands will plot on top of the previously plotted curves with the already established axislimits. With this facility, you can compare the plot of one calculation result to plots of other results. Typing hold onsets holding on, and hold off turns holding off. Typing hold by itself toggles the hold states.

    You can show several plots in one graph window. The command subplot(m,n, p), where m,n, p is a three digit number,specifies m 2 subplots in a column, n 2 subplots in a row, and the subplot number p to be referenced in thecommand that follows the suplot command. The subplots are numbered from left to right, top to bottom. For examplesubplot(2,2,3); plot(x,y) plots x versus y in the lower left subplot of a 2 by 2 graph window.

    You can open more than one figure window. Calling the figure function without any arguments opens a new figurewindow. Typing figure(N) makes the N-th figure the current figure; the result of subsequent graphics commands is thendisplayed in that window. If Figure N does not exist, MATLAB creates it using the next available figure number (whichis not necessarily N).

    The graphics features discussed so far comprise the high level interface to MATLABs graphics system. However, thissystem also provides a set of low-level functions that allow you to create and manipulate the lines, surfaces, and othergraphics objects MATLAB uses to produce sophisticated plots. This system is called Handle Graphics. The graphicsobjects include the root screen, figures, axes, lines, patches, surfaces, images, text, user interface controls, and userinterface menus. For further information on this, please consult the MATLAB Users Guide and MATLAB ReferenceGuide.

    Complete and incomplete gamma function

    Graph Window Controlaxis manual axis scalinghold hold plot on screenshg show graph screenfigure create figure (graph window)clf clear current figurecla clear current axessubplot split graphic windowuicontrol create user interface controluimenu create user interface menuset set object propertiesget get object propertiesreset reset object properties

    7.3 Movies

    You can save any sequence of plots and then play the sequence back in a short movie with the getframe and moviefunctions. The following code generates a 16 frame moveie showing the fft(eye(n)) example.

    The getframe function returns a pixel snapshot of the current figure window. Each frame consists of byte oriented data

    14

  • packed into a MATLAB column vector. The complexity of the plot does not affect the length of the column required,but the size of the current window does. Larger windows require more storage.

    The moviein(n) function creates a matrix large enough to hold n columns, each of which holds a frame. This step isnot required, but it your do not initialize M , the code runs more slowly because the storage for M is reallocated eachtime a new column is appended.

    Once the movie has been generated, you can play it back. To play it back thirty times, type

    You can readily generate and smoothly play back movies with a few dozen frames. Longer movies require large amountsof primary memory or a very effective virtual memory system.

    7.4 Graphic input

    The ginput function allows you to use the mouse or the arrow keys to select points on a plot. It returns the coordinatesof the pointers position, either the current position or the position when a mouse button or key is pressed. Used cleverly,ginput can be a powerful tool for manipulating graphics.

    gets N points from the current figure window and returns the X- and Y-coordinates in length N vectors x and y. You canposition the cursor using a mouse; enter data points by pressing a mouse button or any key on the keyboard. A carriagereturn terminates the input before N points are entered.

    gathers an unlimited number of points until the return key is pressed.

    7.5 Creating hardcopy of MATLAB figures

    You can generate PostScript output of the contents of any MATLAB figure window using the print command. Typingprint sends the output directly to your default printer or writes it to the specified file, if you supply a filename. If youdo not want to print with the burst (header) page, use the -h option. You can also specify the type of PostScript file.Supported types include

    PostScript (-dps)

    Color PostScript (-dps2)

    Level 2 PostScrpt(-dps2)

    Level 2 Color PostScript (-dpsc2)

    Encapsulated PostScript (-deps)

    Encapsulated Color PostScript (-depsc)

    Encapsulated Level 2 PostScript (-deps2)

    Encapsulated Level 2 Color PostScript (-depsc2)

    Encapsulated PostScript with Preview Image (-depsi)

    Encapsulated Color PostScript with Preview Image (-depsic)

    Encapsulated Level 2 PostScript with Preview Image (-depsi2)

    Encapsulated Level 2 Color Postscript with Preview Image (-depsic2)

    For example, the statement

    saves the contents of the current figure window as level 2 color Encapsulated PostScript in the file called meshdata.eps.

    In general, level 2 files are smaller and render more quickly when printing. However, not all PostScript printers sup-port level 2, so you should know the capabilities of your printer before using the print command. all printers in the

    15

  • UltraSPARC cluster labs support PostScript level 2.

    7.6 Line and mark styles

    After each coordinate specification in the plotting statement, you can place the desired attribute(s) in quotes to specifyline types. Available linea nd point types, and colors are:

    Complete and incomplete gamma function

    Line Types Point Types Colorssolid - point . red rdashed -- plus + blue bdotted : star green gdashdot -. circle o white w

    x-mark x invisible i

    For example,

    plots x and y in a linear graph using dashed lines,

    plots x and y in a log-log scale using read x-marks,

    plots x and y in a semilog scale using dots and circles, and

    plots x versus y using solid lines and x versus z using dotted lines on the same graph.

    7.7 Polar plot

    To plot in polar coordinates of the angle theta versus the radius rho, use polar(theta,rhoh). Use the grid commandto draw polar grid lines, if desired.

    7.8 3-D line plot

    The three dimensional analog of the plot function is plot3. If x, y, and z are three vectors of the same length,

    generates a line in 3-D space through the points whose coordinates are the elements of x, y, and z and then produces atwo-dimensional projection of that line on the screen. For example

    produces the helix in Figure 2.

    In 3-D graphics you can use xlabel, ylabel, and zlabel to add text to the x-, y-, and z-axis, respectively. Similarly, theaxis command in the 3-D graphics also sets the minimum and maximum values of the z-axis, that is,

    7.9 3-D mesh surface

    Given a matrix Z, the statement mesh(Z) creates a 3-dimensional perspective plot of the elements of the matrix.Coordinates of points of the mesh surface are above a rectangular grid in the X-Y plane. The mesh surface is formed byjoining adjacent points with straight lines both in X and in Y directions.

    16

  • Use the mesh command to plot functions of two variables. Suppose you want to plot the function Z = f(X,Y ). Firstgenerate special X and Y matrices that consist of repeated rows and columns over the domain of the function. The rowsof X are copies of the vector x, and the columns of Y are the copies of the vector y. Then the X and Y matrices can beused to evaluate the function f over the domain of the function. Use the function meshgrid to create these matrices.The function Z can then be evaluated directly and plotted.

    The following example shows the function sin(r)/r or sinc(r) where r =x2 + y2.

    These statements draw the sombrero surface shown in Figure 3. You can also use mesh to view the content of amatrix, especially a large one that is difficult to print in numerical form. What does an identity matrix look like as amesh surface? Try mesh(eye(14)).

    7.10 Viewpoint

    MATLAB allows you to specify the angle from which you view a 3-D graph. The view function sets the angle ofview in spherical coordinates by specifying the azimuth and elevation of the viewpoint (both in degrees) with respectto the axis origin. The azimuth is a polar angle in the x- y plane, with positive angles indicating counterclockwiserotation of the viewpoint. The elevation is the angle above (positive angle) or below (negative angle) the x-y plane. Forexample, Figure 4, which shows four different view of Figure 3, is produced by view(-37.5,30), view(-7,80), view(-90,0),view(-7,10), respectively.

    Typing view(2) sets the default 2-D view, view(0,90). Typing view(3) sets the default 3-D view, view(-37.5,30).

    7.11 Contour plot

    An alternative way of viewing the contents of a matrix is the contour plot. MATLAB supports both 2-D and 3-D functionsfor generating contour plots. the contour and contour3 functions generate plots composed of lines of constant datavalues obtained from a matrix input argument.

    contour(Z,N), where N is a vector which contains the contour level, plots the contour of Z at the values specified in N.

    plots the contour of Z at the values of -0.2, 0.0, 0.2, 0.4, 0.6, 0.8, and 1.0 as shown in Figure 5. To see which contourlines correspond to 0.0, as shown in Figure 6, enter

    The 3-D version of Figure 5 is created by the command

    C = contour(...) returns the contour matrix C to be used by clabel to label the contour elevation. The functionclabel(C) adds height labels to the current contour plot using the contour structure C. The function clabel(C,V)labels just those contour levels given in vector V. The default action is to label all known contours. The functionclabel(C,manual) places contour labels at the locations selected with a mouse. Press the Return key to terminatelabeling. Use the space bar to enter contours.

    7.12 Color maps

    A color map is an m-by-3 matrix of real numbers between 0.0 and 1.0. The k-th row of the color map defines the k-thcolor by specifying the intensity of red, green and blue, that is, map(k,:)=[r(k) g(k) b(k)]. For example, [0 0 0] is black,[1 1 1] is white, [1 0 0] is pure red, [.5 1 .83] is aquamarine.

    The command colormap displays the content of the default color map, which is called the hsv (hue saturation value)

    17

  • color map. In addition to the default color map, MATLAB provides a number of other color maps, such as hot, cool,bone, and copper, which vary hue according to certain models and are useful for certain applications. For example,the bone color map is useful for displaying the image of X-ray results. To replace the default color map with anotherone, call the name of the color map, for example, hot.

    You can use colors to add another dimension to mesh or surface plots. With Z and C as matrices,

    generates a wire-frame view of the surface Z and independently specifies the color using the second argument, C. Foreach point C(i,j), a scaled value of the matrix element, C(i,j), is used as an index to a color map to determine the colorto display at that point. That way, one attribute is shown by the Z-value of the surface plot, and another attribute byits color. For example, you can show the Z-value of the surface in Figure 3 and its curvature by entering

    You can draw a lit and shaded surface using the surf1 function. MATLAB calculates the surface reflectance based on acombination of diffuse, specular and ambient lighting models. You can specify the direction of the single light source inCartesian or spherical coordinates.

    For example, the following statements create a surface and light it from azimuth=-10 degrees and elevation =50 degrees.

    You can also get a menu for changing color maps by typing colormenu. A menu will come up on top of the graphicswindow, and you can choose different color maps from that menu.

    7.13 Images

    The function image displays an image by mapping each element in a matrix to an entry in the current color map. Imagestypically have their own color maps. The color map associated with an image is likely to be quite different from a colormap that is independent of any particular set of data. Only the colors found in a particular image comprise its colormap, which is referred to as a color palette.

    7.14 Bar charts, stairstep plots, and histograms

    You can display vector x by a bar chart with bar(x) or by a stairstep plot by stairs(x). (A stairstep plot is a bar chartwithout the vertical lines.)

    Complete and incomplete gamma function

    Graph Paperplot3 3-D plotpolar polar plotmesh 3-dimensional mesh surfacemeshdom domain for mesh plotscontour 2-D contour plotcontour3 3-D contour plotsurfl shaded surface with lightingbar bar chartsstairs stairstep grapherrorbar add errorbars

    8 Sound

    In addition to the visual supports in terms of graphics, MATLAB provides audio support in terms of sounds. The functionsound(y) sends the signal in vector y out the speaker on the Sun UltraSPARC computer. The vector is autoscaled to

    18

  • provide maixmum amplitude. The sound is played at the default sample rate, which is 8192 Hz. Thus each samplerepresents a 1/8192 second time step. For demonstration, there is a laughter.mat file available on the system.

    These commands load the file laughter.mat, play the sound, and print the visual representation of the sound in theform of an X-Y plot. The variable t is the time, where values are the sample indices divided by the frequency (8192 Hz).Using this function, you can hear your data, after you interpolate the data to be one sample per 1/8192 seconds. Ofcourse if the sound is below or above your threshold of hearing, you will not be able to hear it.

    Complete and incomplete gamma function

    Graph Papersound convert vector into soundsaxis sound axis scalingauwrite write Sun audio fileauread read Sun audio file

    9 Control Flow

    MATLAB has control flow statements that carry it beyond the level of a simple desk calculator, allowing it to be usedas a complete high-level programming language.

    9.1 For loop

    Syntax:

    For example,

    9.2 While loop

    Syntax:

    Example: The following code finds the average of two numbers entered from the keyboard. The loop ends after anon-positive first number is entered.

    19

  • 9.3 If statement

    Syntax:

    Relational operators are used in a condition. Note that the equal sign (=) is used in an assignment statement whilethe double equal sign (==) is used in a relation. You can connect two or more relations by logical operators.

    Example: The following code finds how many points of an array of data are negative.

    Relational and Logical Operators< less than & AND greater than>= greater than or equal== equal= not equal

    Control Flowif conditionally execute statementselseif used with ifelse used with ifend terminate if, for, whilefor repeat statements a number of timeswhile do whilebreak break out of for and while loopsreturn return from functionspause pause until key pressed

    Relational and Logical Functionsany logical conditionsall logical conditionsfind find array indices of logical valuesexist check if variables existisnan detect NaNsfinite detect infinitiesisempty detect empty matricesisstr detect string variablesstrcmpt compare string variables

    10 M-files

    You can put a sequence of MATLAB statements into a disk file. Such a file is called an m-file, because it has a file typeof .m as the last part of the file name. For example, the sequence to evaluate Bessel functions is put into a file named

    20

  • bessel.m. An m-file can include reference to other m-files and can call itself recursively.

    There are two types of m-files: script files and function files. Script files automate long sequences of commands, whilefunction files allow you to add new functions to existing functions. The ability to create new functions contributes greatlyto the power of MATLAB.

    To put a comment in an m-file, use the symbol %. MATLAB ignores anything after the symbol %. The first commentline in an m-file is called the H1 line; it is usually the first line in a script file and the second line in a function file (theline in a function file is reserved for function declaration). Usually the H1 line is used to give a short description of thefunction of the m-file. This line is read by the lookfor function. If an m-file has consecutive comment lines after the H1line, these lines are read by the help function.

    10.1 Script file

    Consider the file fibo.m below:

    To run it, type

    On multiuser or networked systems, a script file called matlabrc.m is reserved for system managers, who can use it toimplement system-wide definitions and messages. On our systems, the file

    /usr/local/src/matlab4.2/toolbox/local/matlabrc.m

    sets a default graphic window position and starts a file named startup.m. You can create your own startup.m file andenter physical constants, engineering conversion factors, or anything else you want predefined in your workspace.

    10.2 Function file

    A function file starts with the word function, the file is a function file. Arguments are passed to a function, and variablesinside the function are local. This means that if there are variables in the calling program with the same names asthe variables in the function, the values of these variables will not be altered by what happens to the variables in thefunction.

    As an example, consider the function file mymean.m:

    note that the name of a function, as defined in the first line of the m file, must be the same as the name of the filewithout the .m extension. Select a descriptive function name that is not used elsewhere either as a variable or functionname. In general, using a single character as a function name is not recommended.

    21

  • To calculate the

    Programming and M-filesinput get numbers from keyboardkeyboard call keyboard as m-fileerror display error messagefunction define functioneval interpret text in variablesfeval evaluate function given by stringecho enable command echoingexist check if variables existcasesen set case sensitivityglobal define global variablesstartup startup m-filegetenv get environment stringmenu select item from menuetime elapsed time

    11 The MATLAB debugger

    MATLAB finds syntax errors during compilation. These errors are usually easy to fix. MATLAB can also encountererrors at run-time; these errors tend to be more difficult to track down, because the workspace local to the function islost when the error forces a return to the MATLAB prompt and the base workspace. If you use the semicolon to suppressthe display of intermediate results, you wont know where the error occurred.

    With MATLAB, you can display the intermediate results using the debugging commands. Note that these commandswork on m-file functions, not scripts.

    Debugging Commandsdbstop set breakpointdbclear remove breakpointdbcont resume executiondbdown change local workspace contextdbstack list who called whomdbstatus list all breakpointsdbstep execute one or more linesdbtype list M-file with line numbersdbup change local workspace contextdbquit quit debug mode

    A typical debugging session for a function file called test.m usually starts with the command

    to list the file. Use dbstop commands to set breakpoints, and the function file is executed normally, for example, y =test(x). The execution of the function file stops at breakpoints. If you type dbcont, the execution will continue untilthe next breakpoint is encountered. Type dbstep for step-by-step (statement-by-statement) execution. Some variables

    22

  • are checked by calling the variable names until the source of the problem is found. Sometimes you have to clear somebreakpoints by dbclear and set new breakpoints. End the session by dbquit.

    It is beyond the scope of this document to explain all the debugging commands, but with the help facility and somepractice, these commands will become clear. Some experience with other debuggers such as dbx will be helpful.

    12 Order of calls

    When you type

    MATLAB does the following (in this order):

    displays the value of the variable xyz, if it exists; or

    runs an internal command xyz, if it exists; or

    runs an m-file named xyz.m in the current directory, if such a file exists; or

    runs an m-file from one of the toolboxes, if such a file exists; or

    runs an m-file names xyz.m in a directory called matlab in your home directory, if it exists.

    Other than the current directory, the order of calls for m-files is set up in the environmental variable MATLABPATH.TO look at the current MATLAB search path setting, type

    You can add other directories to be included in front of the default MATLABPATH by putting

    or

    in your .cshrc file. You an also do that using MATLABs path function.

    One common mistake in MATLAB is to name a variable with the same name as one of the MATLAB internal commandsor one of the m-files; for example, creating an xyz variable while there exists an m-file called xyz.m. Then, when youtype

    you expect the m-file xyz.m to be executed, but instead you get the listing of the value of the xyz variable. The generalrule here is not to name a variable or an m-file with a name that has already been used, unless you really want tooverwrite a variable.

    There may be times when you want to run your own script or function file instead of the one provided by the system.You can create files with the same name as the system files; for example, you can overwrite the system matlabrc.mdefaults by creating your own matlabrc.m file.

    13 Running MATLAB in the background

    If you have a dedicated machine, you can run MATLAB in the background. To do so, create an m-file (say batch.m)that does not contain any statement that needs interactive input. Make sure that you include a statement to save theresults and end the m-file with the quit statement. To run MATLAB in the background, at the UNIX prompt type

    A very simple example of batch.m file is

    23

  • 14 Other MATLAB functions and toolboxes

    ]

    There are many more MATLAB functions. MATLAB has functions for text and strings, polynomials, decompositions andfactorizations, interpolation, differential equation solution, numerical integration, nonlinear equation and optimization,data analysis, signal processing, and more.

    In addition to these functions, there are toolboxes collections of m-files intended for specific application areas. You canuse the functions in these toolboxes interactively or build them into your own m-files. Some of the commercially avail-able toolboxes include signal processing toolbox, system identification toolbox, control toolbox, robust control toolbox,and chemometrics toolbox (for chemical engineering). In the Sun UltraSPARC cluster, the control toolbox and signalprocessing toolbox are available.

    Finally, the cluster has a separate package called simulink, with which you can draw block diagrams to simulate linearor nonlinear systems.

    References

    MATLAB Users Guide. The MathWorks Inc., 1992.

    MATLAB Reference Guide. The MathWorks Inc., 1992.

    MATLAB New Features Guide. The MathWorks Inc., 1992.

    If you would like to join the MATLAB Users Group and receive the email MATLAB newsgroup digest, send youremail address to matlab-users-requestmcs.anl.gov. Send submissions to matlab-usersmcs.anl.gov. Note, however, thatthis mailing list is not very active, so you may get only one mailing (MATLAB digest) every few months. Send librarycontributions to matlab-librarymcs.anl.gov. A more active source for MATLAB discussions is the newsgroup comp-soft-sys.matlab on the Usenet news.

    24