Statistical Signal Processing I
Statistical Signal Processing I EE 262
Popular in Course
Popular in Electrical Engineering
This 38 page Class Notes was uploaded by Amiya Haley on Monday September 7, 2015. The Class Notes belongs to EE 262 at University of California - Santa Cruz taught by Staff in Fall. Since its upload, it has received 86 views. For similar materials see /class/182337/ee-262-university-of-california-santa-cruz in Electrical Engineering at University of California - Santa Cruz.
Reviews for Statistical Signal Processing I
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 09/07/15
MATLAB Primer Third Edition Kermit Sigmon Department of Mathematics University of Florida Department of Mathematics 0 University of Florida 0 Gainesville FL 32611 sigmonmathufledu Copyright 19897 19927 1993 by Kermit Sigmon ON THE THIRD EDITION The Third Edition of the MATLAB Primer is based on version 40 41 of MATLAB While this edition re ects an extensive general revision of the Second Edition most sig ni cant is the new information to help one begin to use the major new features of version 40 41 the sparse matrix and enhanced graphics capabilities The plain TEX source and corresponding PostScript le of the latest printing of the MATLAB Primer are always available via anonymous ftp from Address math ufl edu Directory pubmatlab Files primer tex primer ps You are advised to download anew each term the latest printing of the Primer since minor improvements and corrections may have been made in the interim If ftp is unavailable to you the Primer can be obtained via listserv by sending an email message to list seermathufl edu containing the single line send matlabprimer tex Also available at this ftp site are both English primer35tex primer35ps and Spanish primerSSsptex primerSSspps versions of the Second Edition of the Primer which was based on version 35 of MATLAB The Spanish translation is by Celestino Montes University of Seville Spain A Spanish translation of the Third Edition is under development Users of the Primer usually appreciate the convenience and durability of a bound copy with a cover copy center style 12 93 Copyright 1989 1992 1993 by Kermit Sigmon The MATLAB Primer may be distributed desired subject to the following con ditions 1 It may not be altered in any way except possibly adding an addendum giving information about the local computer installation or MATLAB toolboxes 2 It or any part thereof may not be used part of a document distributed for a commercial purpose In particular it may be distributed via a local copy center or bookstore Department of Mathematics 0 University of Florida 0 Gainesville FL 32611 sigmonmathufledu INTRODUCTION MATLAB is an interactive matrix based system for scienti c and engineering numeric computation and visualization You can solve complex numerical problems in a fraction of the time required with a programming language such Fortran or C The name MATLAB is derived from MATrix LABoratory The purpose of this Primer is to help you begin to use MATLAB It is not intended to be a substitute for the User s Guide and Reference Guide for MATLAB The Primer can best be used hands on You are encouraged to work at the computer you read the Primer and freely experiment with examples This Primer along with the on line help facility usually suf ce for students in a class requiring use of MATLAB You should liberally use the on line help facility for more detailed information When using MATLAB the command help functionname will give information about a speci c function For example the command help eig will give information about the eigenvalue function eig By itself the command help will display a list of topics for which on line help is available then help topic will list those speci c functions under this topic for which help is available The list of functions in the last section of this Primer also gives most of this information You can preview some of the features of MATLAB by rst entering the command demo and then selecting from the options offered The scope and power of MATLAB go far beyond these notes Eventually you will want to consult the MATLAB User s Guide and Reference Guide Copies of the complete documentation are often available for review at locations such consulting desks terminal rooms computing labs and the reserve desk of the library Consult your instructor or your local computing center to learn where this documentation is located at your institution MATLAB is available for a number of environments SunApolloVAXstationHP workstations VAX MicroVAX Gould PC and AT compatibles 80386 and 80486 com puters Apple Macintosh and several parallel machines There is a relatively inexpensive Student Edition available from Prentice Hall publishers The information in these notes applies generally to all of these environments MATLAB is licensed by The MathWorks Inc 24 Prime Park Way Natick MA 01760 508653 1415 Fax 508653 2997 Email infomathworkscom Copyright 1989 1992 1993 by Kermit Sigmon ii CONTENTS Page 1 Accessing MATLAB 1 2 Entering matrices 1 3 Matrix operations array Operations 2 4 Statements expressions variables saving a session 3 5 Matrix building functions 4 6 For While if and relations 4 7 Scalar functions 7 8 Vector functions 7 9 Matrix functions 7 10 Command line editing and recall 8 11 Submatrices and colon notation 8 12 M les script les function les 9 13 Text strings error messages input 12 14 Managing M les 13 15 Comparing efficiency of algorithms ops tic toc 14 16 Output format 14 17 Hard copy 15 18 Graphics 15 planar plots 15 hardcopy 17 3 D line plots 18 mesh and surface plots 18 Handle Graphics 20 19 Sparse matrix computations 20 20 Reference 22 iii 1 Accessing MATLAB On most systems after logging in one can enter MATLAB with the system command matlab and exit MATLAB with the MATLAB command quit or exit However your local installation may permit MATLAB to be accessed from a menu or by clicking an icon On systems permitting multiple processes such a Unix system or MS Windows you will nd it convenient for reasons discussed in section 14 to keep both MATLAB and your local editor active If you are working on a platform which runs processes in multiple windows you will want to keep MATLAB active in one window and your local editor active in another You should consult your instructor or your local computer center for details of the local installation 2 Entering matrices MATLAB works with essentially only one kind of object a rectangular numerical matrix with possibly complex entries all variables represent matrices In some situations 1 by 1 matrices are interpreted scalars and matrices with only one row or one column are interpreted vectors Matrices can be introduced into MATLAB in several different ways 0 Entered by an explicit list of elements 0 Generated by built in statements and functions 0 Created in a disk le with your local editor 0 Loaded from external data les or applications see the User s Guide For example either of the statements A 123456789 and A 1 4 O303r I 2 5 7 8 9 creates the obvious 3 by 3 matrix and assigns it to a variable A Try it The elements within a row of a matrix may be separated by commas well a blank When listing a number in exponential form eg 234e 9 blank spaces must be avoided MATLAB allows complex numbers in all its operations and functions Two convenient ways to enter complex matrices are A 1 23 4 15 6 8 A 151 261371 4481 When listing complex numbers eg 26i in a matrix blank spaces must be avoided Either 239 or j may be used the imaginary unit If however you use 239 and j vari ables and overwrite their values you may generate a new imaginary unit with say ii sqrt1 Listing entries of a large matrix is best done in an ASCII le with your local editor where errors can be easily corrected see sections 12 and 14 The le should consist of a rectangular array of just the numeric matrix entries If this le is named say dataext where 910 is any extension the MATLAB command load dataext will read this le to the variable data in your MATLAB workspace This may also be done with a script le see section 12 The built in functions rand magic and 11111 for example provide an easy way to create matrices with which to experiment The command rand n will create an n X 77 matrix with randomly generated entries distributed uniformly between 0 and 1 while rand mn will create an m X 77 one magic n will create an integral n X 77 matrix which is a magic square rows columns and diagonals have common sum 11111 n will create the n X n Hilbert matrix the king of ill conditioned matrices m and n denote of course positive integers Matrices can also be generated with a for loop see section 6 below Individual matrix and vector entries can be referenced with indices inside parentheses in the usual manner For example A23 denotes the entry in the second row third column of matrix A and denotes the third coordinate of vector 3 Try it A matrix or a vector will only accept positive integers indices 3 Matrix operations array operations The following matrix operations are available in MATLAB addition subtraction multiplication A power conjugate transpose left division right division These matrix operations apply of course to scalars l by l matrices well If the sizes of the matrices are incompatible for the matrix operation an error message will result except in the case of scalar matrix operations for addition subtraction and division well for multiplication in which case each entry of the matrix is operated on by the scalar The matrix division operations deserve special comment If A is an invertible square matrix and b is a compatible column resp row vector then a Ab is the solution of A a b and resp a bA is the solution of a A b In left division if A is square then it is factored using Gaussian elimination and these factors are used to solve A a b If A is not square it is factored using Householder orthogonalization with column pivoting and the factors are used to solve the under or over determined system in the least squares sense Right division is de ned in terms of left division by bA A b Array operations The matrix operations of addition and subtraction already operate entry wise but the other matrix operations given above do not they are matrix operations It is impor tant to observe that these other operations A and can be made to operate entry wise by preceding them by a period For example either 1234 1234 or 1234 A2 will yield 14916 39Dry it This is particularly useful when using Matlab graphics 4 Statements expressions and variables saving a session MATLAB is an expression language the expressions you type are interpreted and evaluated MATLAB statements are usually of the form variable expression or simply expression Expressions are usually composed from operators functions and variable names Eval uation of the expression produces a matrix which is then displayed on the screen and assigned to the variable for future use If the variable name and sign are omitted a variable ans for answer is automatically created to which the result is assigned A statement is normally terminated with the carriage return However a statement can be continued to the next line with three or more periods followed by a carriage return On the other hand several statements can be placed on a single line if separated by coanas or semicolons If the last character of a statement is a semicolon the printing is suppressed but the assignment is carried out This is essential in suppressing unwanted printing of intermediate results MATLAB is case sensitive in the names of commands functions and variables For example solveUT is not the same solvent The command who or whos will list the variables currently in the workspace A variable can be cleared from the workspace with the command clear variablename The command clear alone will clear all nonpermanent variables The permanent variable eps epsilon gives the machine unit roundo 39 about 10 16 on most machines It is useful in specifying tolerences for convergence of iterative processes A runaway display or computation can be stopped on most machines without leaving MATLAB with CTRL C CTRL BREAK on a PC Saving a session When one logs out or exits MATLAB all variables are lost However invoking the command save before exiting causes all variables to be written to a non human readable disk le named matlabmat When one later reenters MATLAB the command load will restore the workspace to its former state 5 Matrix building functions Convenient matrix building functions are eye identity matrix zeros matrix of zeros ones matrix of ones diag create or extract diagonals triu upper triangular part of a matrix tril lower triangular part of a matrix rand randomly generated matrix hilb Hilbert matrix magic magic square toeplitz see help toeplitz For example zeros mn produces an m by n matrix of zeros and zeros n produces an n by n one If A is a matrix then zerossize 10 produces a matrix of zeros having the same size A If a is a vector diagx is the diagonal matrix with a down the diagonal if A is a square matrix then diagA is a vector consisting of the diagonal of A What is diagdiagA Try it Matrices can be built from blocks For example if A is a 3 by 3 matrix then B A zeros 32 zeros23 eye 2 will build a certain 5 by 5 matrix Try it 6 For while if and relations In their basic forms these MATLAB ow control statements operate like those in most computer languages For For example for a given n the statement x U for i 1n xxiA2 end or x 1 f or i 1 n x xiA 2 end will produce a certain n vector and the statement x 1 for i n11 xxiA2 end will produce the same vector in reverse order Try them Note that a matrix may be empty such x J The statements for i 1m for j 1n Hi j 1ij1 will produce and print to the screen the m by n hilbert matrix The semicolon on the inner statement is essential to suppress printing of unwanted intermediate results While the last H displays the nal result The for statement permits any matrix to be used instead of 1 n The variable just consecutively assumes the value of each column of the matrix For example 3 O for c A s s sumc end computes the sum of all entries of the matrix A by adding its column sums Of course sumsumA does it more ef ciently see section 8 In fact since 1 n 1 23 n see section 11 this column by column assigment is What occurs with if i 1 n While The general form of a while loop is while relation statements end The statements will be repeatedly executed long the relation remains true For exam ple for a given number a the following will compute and display the smallest nonnegative integer n such that 2 2 a n 0 while 2An lt a n n 1 end n If The general form of a simple if statement is if relation statements end The statements will be executed only if the relation is true Multiple branching is also possible is illustrated by if n lt O parity O elseif rem n 2 parity 2 else parity 1 end In two way branching the elseif portion would of course be omitted Relations The relational operators in MATLAB are lt less than gt greater than lt less than or equal gt greater than or equal 22 equal not equal Note that is used in an assignment statement while is used in a relation Relations may be connected or quanti ed by the logical operators 85 and i or N not When applied to scalars a relation is actually the scalar 1 or 0 depending on whether the relation is true or false Try entering 3 lt 5 3 gt 5 5 and 3 3 When applied to matrices of the same size a relation is a matrix of 0 s and 1 s giving the value of the relation between corresponding entries Try a rand5 b triua a A relation between matrices is interpreted by while and if to be true if each entry of the relation matrix is nonzero Hence if you wish to execute statement when matrices A and B are equal you could type if A B statement end but if you wish to execute statement when A and B are not equal you would type if anyanyA 13 statement end or more simply if A B else statement end Note that the seemingly obvious if A N B statement end will not give what is intended since statement would execute only if each of the correspond ing entries of A and B differ The functions any and all can be creatively used to reduce matrix relations to vectors or scalars Two any s are required above since any is a vector operator see section 8 7 Scalar functions Certain MATLAB functions operate essentially on scalars but operate element wise when applied to a matrix The most common such functions are sin asin exp abs round cos acos log natural log sqrt oor tan atan rem remainder sign ceil 8 Vector functions Other MATLAB functions operate essentially on a vector row or column but act on an m by n matrix m 2 2 in a column by column fashion to produce a row vector containing the results of their application to each column Row by row action can be obtained by using the transpose for example mean A A few of these functions are max sum median any min prod mean all sort std For example the maximum entry in a matrix A is given by max max A rather than maxA Try it 9 Matrix functions Much of MATLAB s power comes from its matrix functions The most useful ones are eig eigenvalues and eigenvectors chol cholesky factorization svd singular value decomposition inv inverse lu LU factorization qr QR factorization hess hessenberg form schur schur decomposition rref reduced row echelon form expm matrix exponential sqrtm matrix square root poly characteristic polynomial det determinant size size norm l norm 2 norm F norm oo norm cond condition number in the 2 norm rank rank MATLAB functions may have single or multiple output arguments For example y eigA or simply eigA produces a column vector containing the eigenvalues of A while UD eigA produces a matrix U whose columns are the eigenvectors of A and a diagonal matrix D with the eigenvalues of A on its diagonal Try it 10 Command line editing and recall The command line in MATLAB can be easily edited The cursor can be positioned with the left right arrows and the Backspace or Delete key used to delete the character to the left of the cursor Other editing features are also available On a PC try the Home End and Delete keys on a Unix system or a PC the Emacs commands Ctl a Ctl e Ctl d and Ctl k work on other systems see help cedit or type cedit A convenient feature is use of the up down arrows to scroll through the stack of previous commands One can therefore recall a previous command line edit it and execute the revised command line For small routines this is much more convenient that using an M le which requires moving between MATLAB and the editor see sections 12 and 14 For example opcounts see section 15 for computing the inverse of matrices of various sizes could be compared by repeatedly recalling editing and executing a rand8 flops 0 inva flops If one wanted to compare plots of the functions y sin ma and y sin 773 on the interval 0 2 for various m and 77 one might do the same for the command line m2 113 x0012pi ysinmx zcosnx plotxyxz 11 Submatrices and colon notation Vectors and submatrices are often used in MATLAB to achieve fairly complex data manipulation effects Colon notation which is used both to generate vectors and refer ence submatrices and subscripting by integral vectors are keys to efficient manipulation of these objects Creative use of these features to vectorize operations permits one to minimize the use of loops which slows MATLAB and to make code simple and readable Special E OT t should be made to become familiar with them The expression 1 5 met earlier in for statements is actually the row vector 1 2 3 4 5 The numbers need not be integers nor the increment one For example 0 2 O 2 1 2 gives 02 04 06 08 10 12 and 511 gives 5 4 3 2 1 The following statements will for example generate a table of sines Try it x 000120 y 31110 x y Note that since sin operates entry wise it produces a vector y from the vector as The colon notation can be used to access submatrices of a matrix For example A1 4 3 is the column vector consisting of the rst four entries of the third column of A A colon by itself denotes an entire row or column A 3 is the third column of A and A1 4 is the rst four rows Arbitrary integral vectors can be used subscripts A 2 4 contains columns columns 2 and 4 of A Such subscripting can be used on both sides of an assignment statement A 2 4 5 B 1 3 replaces columns 245 of A with the rst three columns of B Note that the entire altered matrix A is printed and assigned Try it Columns 2 and 4 of A can be multiplied on the right by the 2 by 2 matrix 1 23 4 Mi 24 A 241 23 4 Once again the entire altered matrix is printed and assigned If a is an n vector what is the effect of the statement 1 xn11 Try it Also try y fliplrx andy flipudx To appreciate the usefulness of these features compare these MATLAB statements with a Pascal FORTRAN or C routine to effect the same 12 M les MATLAB can execute a sequence of statements stored in disk les Such les are called M les because they must have the le type of m the last part of their lename Much of your work with MATLAB will be in creating and re ning M les M les are usually created using your local editor There are two types of M les script les and function les Script les A script le consists of a sequence of normal MATLAB statements If the le has the lename say rotatem then the MATLAB command rotate will cause the statements in the le to be executed Variables in a script le are global and will change the value of variables of the same name in the environment of the current MATLAB session Script les may be used to enter data into a large matrix in such a le entry errors can be easily corrected If for example one enters in a disk le datam A 1 3 7 05h 4 5 8 J then the MATLAB statement data will cause the assignment given in datam to be carried out However it is usually easier to use the MATLAB function load see section 2 An M le can reference other M les including referencing itself recursively 9 Function les Function les provide extensibility to MATLAB You can create new functions speci c to your problem which will then have the same status other MATLAB functions Vari ables in a function le are by default local A variable can however be declared global see help global We rst illustrate with a simple example of a function le function a randint mn ZRANDINT Randomly generated integral matrix X randint mn returns an mbyn such matrix with entries 2 between 0 and 9 a floor10randmn A more general version of this function is the following function a randintmnab ZRANDINT Randomly generated integral matrix X randintmn returns an mbyn such matrix with entries 7 between 0 and 9 Z randmnab return entries between integers a and b if nargin lt 3 a O b 9 end a floor ba1 rand mm a This should be placed in a disk le with lename randint m corresponding to the function name The rst line declares the function name input arguments and output arguments without this line the le would be a script le Then a MATLAB statement 2 randint 45 for example will cause the numbers 4 and 5 to be passed to the variables m and n in the function le with the output result being passed out to the variable 2 Since variables in a function le are local their names are independent of those in the current MATLAB environment Note that use of nargin number of input arguments permits one to set a default value of an omitted input variable such a and b in the example A function may also have multiple output arguments For example function mean stdev stat x Z STAT Mean and standard deviation For a vector x statx returns the mean of x 7 mean stdev statx both the mean and standard deviation 2 For a matrix x statx acts columnwise m n sizex if m 1 m n X handle case of a row vector end mean sumxm stdev sqrtsumxA2m meanA2 Once this is placed in a disk le stat m a MATLAB command xm xd statx for example will assign the mean and standard deviation of the entries in the vector as to 10 33m and 33d respectively Single assignments can also be made with a function having multiple output arguments For example mm stat x no brackets needed around will assign the mean of a to 33m The quotI symbol indicates that the rest of the line is a comment MATLAB will ignore the rest of the line Moreover the rst few contiguous comment lines which document the M le are available to the on line help facility and will be displayed if for example help stat is entered Such documentation should always be included in a function le This function illustrates some of the MATLAB features that can be used to produce efficient code Note for example that xA2 is the matrix of squares of the entries of as that sum is a vector function section 8 that sqrt is a scalar function section 7 and that the division in sumxm is a matrix scalar operation Thus all operations are vectorized and loops avoided If you can t vectorize some computations you can make your for loops go faster by preallocating any vectors or matrices in which output is stored For example by including the second statement below which uses the function zeros space for storing E in memory is preallocated Without this MATLAB must resize E one column larger in each iteration slowing execution M magic6 E zeros650 for j 150 Ej eigMAi end Some more advanced features are illustrated by the following function As noted earlier some of the input arguments of a function such tol in this example may be made optional through use of nargin number of input arguments The variable nargout can be similarly used Note that the fact that a relation is a number 1 when true 0 when false is used and that when while or if evaluates a relation nonzero means true and 0 means false Finally the MATLAB function feval permits one to have an input variable a string naming another function Also see eval function Eb steps bisectfun x tol ZBISECT Zero of a function of one variable via the bisection method Z bisectfunx returns a zero of the function fun is a string Z containing the name of a realvalued MATLAB function of a Z single real variable ordinarily functions are defined in Z Mfiles x is a starting guess The value returned is near Z a point where fun changes sign For example Z bisect sin 3 is pi Note the quotes around sin 2 Z An optional third input argument sets a tolerence for the Z relative accuracy of the result The default is eps Z An optional second output argument gives a matrix containing a Z trace of the steps the rows are of form c fc 11 a Initialization if nargin lt 3 tol eps end trace nargout 2 if x 0 dx 1120 else dx 120 end a x dx fa fevalfuna b x dx fl fevalfunb Z Find change of sign while fa gt 0 fb gt 0 dx 20dx a x dx fa fevalfuna if fa gt o fb gt 0 break end 1 x dx fl fevalfunb end if trace steps a fa b fb end 2 Main loop while absb a gt 20tolmaxabsb10 c a O5b a fc fevalfunC if trace steps steps c fcll end if fb gt 0 fc gt O b c fl fc else a c fa fc end end Some of MATLAB s functions are built in While others are distributed M les The actual listing of any non built in M le MATLAB s or your own can be Viewed with the MATLAB coanand type functianname Try entering type eig type vander and type rank 13 Text strings error messages input Text strings are entered into MATLAB surrounded by single quotes For example s This is a test assigns the given text string to the variable s Text strings can be displayed with the function disp For example disp this message is hereby displayed Error messages are best displayed with the function error error Sorry the matrix must be symmetric since when placed in an M File it aborts execution of the M le In an M le the user can be prompted to interactively enter input data with the function input When for example the statement iter input Enter the number of iterations is encountered the prompt message is displayed and execution pauses while the user keys in the input data Upon pressing the return key the data is assigned to the variable iter and execution resumes 14 Managing M les While using MATLAB one frequently wishes to create or edit an M le with the local editor and then return to MATLAB One wishes to keep MATLAB active while editing a le since otherwise all variables would be lost upon exiting This can be easily done using the l feature If while in MATLAB you precede it with an any system command such those for editing printing or copying a le can be executed without exiting MATLAB If for example the system command ed accesses your editor the MATLAB command gtgt ed rotatem will let you edit the le named rotate m using your local editor Upon leaving the editor you will be returned to MATLAB just where you left it However noted in section 1 on systems permitting multiple processes such one running Unix or MS Windows it may be preferable to keep both MATLAB and your local editor active keeping one process suspended while working in the other If these processes can be run in multiple windows you will want to keep MATLAB active in one window and your editor active in another You should consult your instructor or your local computing center for details of the local installation Many debugging tools are available See help dbtype or the list of functions in the last section When in MATLAB the command pwd will return the name of the present working directory and Cd can be used to change the working directory Either dir or ls will list the contents of the working directory while the command what lists only the M les in the directory The MATLAB coanands delete and type can be used to delete a disk le and print an M le to the screen respectively While these coanands may duplicate system commands they avoid the use of an You may enjoy entering the command why a few times M les must be in a directory accessible to MATLAB M les in the present work ing directory are always accessible On most mainframe or workstation network installa tions personal M les which are stored in a subdirectory of one s home directory named matlab will be accessible to MATLAB from any directory in which one is working The current list of directories in MATLAB s search path is obtained by the command path This command can also be used to add or delete directories from the search path See help path 15 Comparing ef ciency of algorithms ops tie and toe Two measures of the efficiency of an algorithm are the number of oating point oper ations ops performed and the elapsed time The MATLAB function flops keeps a running total of the ops performed The command flops0 not flops 0 will reset ops to 0 Hence entering flops 0 immediately before executing an algorithm and flops immediately after gives the op count for the algorithm For example the number of ops required to solve a given linear system via Gaussian elimination can be obtained with flops O x Ab flops The elapsed time in seconds can be obtained with the stopwatch timers tie and too tic the timer and too returns the elapsed time Hence the commands tic any statement too will return the elapsed time for execution of the statement The elapsed time for solving the linear system above can be obtained for example with tic x Ab too You may wish to compare this time and op count with that for solving the system using 1 invA b Try it It should be noted that on timesharing machines elapsed time may not be a reliable measure of the efficiency of an algorithm since the rate of execution depends on how busy the computer is at the time 16 Output format While all computations in MATLAB are performed in double precision the format of the displayed output can be controlled by the following commands format short xed point with 4 decimal places the default format long xed point with 14 decimal places format short 9 scienti c notation with 4 decimal places format long 9 scienti c notation with 15 decimal places format rat approximation by ratio of small integers format hex hexadecimal format format bank xed dollars and cents format blank Once invoked the chosen format remains in effect until changed The command format compact will suppress most blank lines allowing more infor mation to be placed on the screen or page The command format loose returns to the non compact format These commands are independent of the other format commands 17 Hardcopy Hardcopy is most easily obtained with the diary command The command diary lename causes what appears subsequently on the screen except graphics to be written to the named disk le if the lename is omitted it will be written to a default le named diary until one gives the command diary off the command diary on will cause writing to the le to resume etc When nished you can edit the le desired and print it out on the local system The l feature see section 14 will permit you to edit and print the le without leaving MATLAB 18 Graphics MATLAB can produce planar plots of curves 3 D plots of curves 3 D mesh surface plots and 3 D faceted surface plots The primary commands for these facilities are plot plots mesh and surf respectively An introduction to each of these is given below To preview some of these capabilities enter the command demo and select some of the graphics options Planar plots The plot command creates linear x y plots if a and y are vectors of the same length the command plotxy opens a graphics window and draws an x y plot of the elements of 3 versus the elements of y You can for example draw the graph of the sine function over the interval 4 to 4 with the following commands x 4 014 y sinx plotxy Try it The vector as is a partition of the domain with meshsize 001 while y is a vector giving the values of sine at the nodes of this partition recall that sin operates entrywise You will usually want to keep the current graphics window gure exposed but moved to the side and the command window active One can have several graphics gures one of which will at any time be the designated current gure where graphs from subsequent plotting commands will be placed If for example gure 1 is the current gure then the command figure 2 or simply figure will open a second gure if necessary and make it the current gure The command figure1 will then expose gure 1 and make it again the current gure The command gcf will return the number of the current gure As a second example you can draw the graph of y e x2 over the interval 15 to 15 follows 1 15 0115 y expxA2 plotxy Note that one must precede A by a period to ensure that it operates entrywise see section MATLAB supplies a function fplot to easily and efficiently plot the graph of a function For example to plot the graph of the function above one can rst de ne the function in an M le called say expnormal ml containing 15 function y exphormalx y expxA2 Then the command fplot exphormal 1 5 1 5 will produce the graph Try it Plots of parametrically de ned curves can also be made Try for example tO 0012pi xcos 3t ysih2t plotxy The graphs can be given titles axes labeled and text placed within the graph with the following commands which take a string an argument title graph title xlabel x axis label ylabel y axis label gtext place text on the graph using the mouse text position text at speci ed coordinates For example the command title Best Least Squares Fit gives a graph a title The command gtext The Spot allows one to interactively place the designated text on the current graph by placing the mouse pointer at the desired position and clicking the mouse To place text in a graph at designated coordinates one would use the command text see help text The command grid will place grid lines on the current graph By default the axes are auto scaled This can be overridden by the command axis Some features of axis are axis Xmin Xmax Ymin YIuax set axis scaling to prescribed limits axisaxis freezes scaling for subsequent graphs axis auto returns to auto scaling v axis returns vector 2 showing current scaling axis square same scale on both axes axis equal same scale and tic marks on both axes axis off turns off axis scaling and tic marks axis on turns on axis scaling and tic marks The axis command should be given after the plot command Two ways to make multiple plots on a single graph are illustrated by xO 012piy1sihx y2sih2x y3sih4x plotxy1 xy2xy3 and by forming a matrix Y containing the functional values columns xO 012pi Y sihx sih2x sih4x J plot xY Another way is with hold The command hold on freezes the current graphics screen so that subsequent plots are superimposed on it The axes may however become rescaled Entering hold off releases the hold One can override the default linetypes pointtypes and colors For example xO 012pi y1sinx y2sin2x y3sin4x plotxy1 xy2 xy3 renders a dashed line and dotted line for the rst two graphs while for the third the symbol is placed at each node The line and mark types are Linetypes solid dashed dotted z dashdot Marktypes point plus star circle 0 x mark 1 Colors can be speci ed for the line and mark types Colors yellow y magenta m cyan 6 red r green g blue 1 white w black k For example plot 1 y r plots a red dashed line The command subplot can be used to partition the screen so that several small plots can be placed in one gure See help subplot Other specialized 2 D plotting functions you may wish to explore via help are polar bar hist quiver compass feather rose stairs fill Graphics hardcopy A hardcopy of the current graphics gure can be most easily obtained with the MAT LAB command print Entered by itself it will send a high resolution copy of the current graphics gure to the default printer The printopt M le is used to specify the default setting used by the print command If desired one can change the defaults by editing this le see help printopt The command print lename saves the current graphics gure to the designated lename in the default le format If lename has no extension then an appropriate extension such ps eps or jet is appended If for example PostScript is the default le format then print lissaj ous will create a PostScript le lissaj ous ps of the current graphics gure which can subse quently be printed using the system print command If filename already exists it will be overwritten unless you use the append option The command print append lissaj ous will append the hopefully different current graphics gure to the existing le lissaj ous ps In this way one can save several graphics gures in a single le The default settings can of course be overwritten For example print deps f3 saddle will save to an Encapsulated PostScript le saddle eps the graphics gure 3 even if it is not the current gure 3D line plots Completely analogous to plot in two dimensions the command plots produces curves in three dimensional space If as y and z are three vectors of the same size then the command plot3xyz will produce a perspective plot of the piecewise linear curve in 3 space passing through the points whose coordinates are the respective elements of as y and 2 These vectors are usually de ned parametrically For example t1 0120pi xcos t ysint ztA3 plot3xyz will produce a helix which is compressed near the af y plane slinky Try it Just for planar plots a title and axis labels including zlabel can be added The features of axis command described there also hold for 3 D plots setting the axis scaling to prescribed limits will of course now require a G vector 3D mesh and surface plots Three dimensional wire mesh surface plots are drawn with the command mesh The command meshz creates a three dimensional perspective plot of the elements of the matrix 2 The mesh surface is de ned by the z coordinates of points above a rectangular grid in the af y plane Try mesheye10 Similarly three dimensional faceted surface plots are drawn with the command surf Try surf eye 10 To draw the graph of a function 2 f31 y over a rectangle one rst de nes vectors 333 and yy which give partitions of the sides of the rectangle With the function meshgrid one then creates a matrix as each row of which equals 333 and whose column length is the length of yy and similarly a matrix y each column of which equals yy follows xy meshgridxxyy One then computes a matrix 2 obtained by evaluating f entrywise over the matrices a and y to which mesh or surf can be applied You can for example draw the graph of z ff 3 2 over the square 2 2 X 2 2 follows try it xx 2 22 yy xx xy meshgridxxyy z expxA2 yA2 meshz One could of course replace the rst three lines of the preceding with xy meshgrid2 22 2 22 Try this plot with surf instead of mesh As noted above the features of the axis command described in the section on planar plots also hold for 3 D plots do the commands for titles axes labelling and the coanand hold The color shading of surfaces is set by the shading command There are three settings for shading faceted default interpolated and flat These are set by the commands 18 shading faceted shading interp or shading flat Note that on surfaces produced by surf the settings interpolated and flat remove the superimposed mesh lines Experiment with various shadings on the surface produced above The command shading well colormap and view below should be entered after the surf command The color profile of a surface is controlled by the colormap command Available pre de ned colormaps include hsv de nih hot cool jet pink copper flag gray bone The command colormapcool will for example set a certain color profile for the current gure Experiment with various colormaps on the surface produced above The command view can be used to specify in spherical or cartesian coordinates the viewpoint from which the 3 D object is to be viewed See help View The MATLAB function peaks generates an interesting surface on which to experiment nth shadingcolormapand view Plots of parametrically de ned surfaces can also be made The MATLAB functions sphere and cylinder will generate such plots of the named surfaces See type sphere and type cylinder The following is an example of a similar function which generates a plot of a torus function xyz torusrna ZTDRUS Generate a torus Z torusrna generates a plot of a torus with central Z radius a and lateral radius r n controls the number Z of facets on the surface These input variables are optional X with defaults r 05 n 30 a 1 Z Xyz torusrna generates three n1byn1 2 matrices so that surfxyz will produce the torus Z See also SPHERE CYLINDER if nargin lt 3 a 1 end if nargin lt 2 n 30 end if nargin lt 1 r 05 end theta piO22nn phi 2pi02n n xx a rcosphicostheta yy a rcosphisintheta 22 rsinphionessizetheta if nargout 0 surfxxyyzz ar a rsqrt2 axisarararararar else 19 xxxyyyzzz Other 3 D plotting functions you may wish to explore via help are meshz surfc surfl contour pcolor Handle Graphics Beyond those described above MATLAB s graphics system provides low level functions which permit one to control virtually all aspects of the graphics environment to produce sophisticated plots Enter the command set1 and gcasetans to see some of the properties of gure 1 which one can control This system is called Handle Graphics for which one is referred to the MATLAB User s Guide 19 Sparse Matrix Computations In performing matrix computations MATLAB normally assumes that a matrix is dense that is any entry in a matrix may be nonzero If however a matrix contains suf ciently many zero entries computation time could be reduced by avoiding arithmetic operations on zero entries and less memory could be required by storing only the nonzero entries of the matrix This increase in efficiency in time and storage can make feasible the solution of signi cantly larger problems than would otherwise be possible MATLAB provides the capability to take advantage of the sparsity of matrices Matlab has two storage modes full and sparse with full the default The functions full and Sparse convert between the two modes For a matrix A full or sparse nnzA returns the number of nonzero elements in A A sparse matrix is stored a linear array of its nonzero elements along with their row and column indices If a full tridiagonal matrix F is created via say F floor10rand6 F triutril F 1 1 then the statement S sparseF will convert F to sparse mode Try it Note that the output lists the nonzero entries in column major order along with their row and column indices The statement F full S restores S to full storage mode One can check the storage mode of a matrix A with the command issparse A A sparse matrix is of course usually generated directly rather than by applying the function sparse to a full matrix A sparse banded matrix can be easily created via the function spdiags by specifying diagonals For example a familiar sparse tridiagonal matrix is created by m 6 n 6 e onesn1 d 2e T spdiagsede 39101 mdl Try it The integral vector 401 speci es in which diagonals the columns of ede should be placed use full T to view Experiment with other values of m and n and say 302 instead of 401 See help spdiags for further features of spdiags The sparse analogs of eye zeros ones and randn for full matrices are respectively speye sparse spones sprandn The latter two take a matrix argument and replace only the nonzero entries with ones and normally distributed random numbers respectively randn also permits the sparsity structure to be randomized The command sparsemn creates a sparse zero matrix The versatile function sparse permits creation of a sparse matrix via listing its nonzero entries Try for example i 123444j 123123 s 5678910 S sparseijs43 fu11S In general if the vector 3 lists the nonzero entries of S and the integral vectors 239 and j list their corresponding row and column indices then sparseij smn will create the desired sparse m X 77 matrix S As another example try n 6 e floor10randn11 E sparse2n1n1enn The arithmetic operations and most MATLAB functions can be applied independent of storage mode The storage mode of the result Operations on full matrices always give full results Selected other results are Ssparse Ffull Sparse 88 SS SS SF SAn SAn SS Full SF SF SF FS Sparse invS cholS 1118 diagS maXS sumS For sparse S eigS is full if S is symmetric but unde ned if S is unsymmetric svd requires a full argument A matrix built from blocks such ABCD is sparse if any constituent block is sparse You may wish to compare for the two storage modes the efficiency of solving a tridi agonal system of equations for say 77 20 50 500 1000 by entering recalling and editing the following two command lines n20eonesn 1 d2e Tspdiags e de 1 0 1 nn Afull T bones n 1 ssparse b tic Ts sparsetimetoc tic Ab fulltimetoc 20 Reference There are many MATLAB features which cannot be included in these introductory notes Listed below are some of the MATLAB functions and operators available grouped by subject areal Use the on line help facility or consult the Reference Guide for more detailed information on the functions There are many functions beyond these There exist in particular several toolboxes of functions for speci c areas2 Included among such are signal processing control systems robust control system identi cation optimization splines chemometrics u analysis and synthesis state space identi cation neural networks image processing symbolic math Maple kernel and statistics These can be explored via the command help MANAGING COMMANDS AND FIINGTIGNS help help facility what list M files on disk type list named M file lookfor keywork search through the help entries which locate functions and files demo run demonstrations path control MATLAB s search path cedit set parameters for command line editing and recall Version display MATLAB version you are running whatsnew display toolbox README files info info about MATLAB and The Math Norks why receive ippant answer MANAGING VARIABLES AND THE WORKSPACE who list current variables whos list current variables long form save save workspace variables to disk load retrieve variables from disk clear clear variables and functions from memory pack consolidate workspace memory size size of matrix length length of vector disp display matrix or text 1 Source MATLAB Reference Guide version 41 2 The toolboxes which are optional may not be installed on your system 22 WORKING WITH FILES AND THE OPERATING SYSTEM cd change current working directory pwd show current working directory dir ls directory listing delete delete le getenv get environment variable execute operating system command unix execute operating system command return result diary save text of MATLAB session CONTROLLING THE COMMAND WINDOW clc clear command window home send cursor homeito top of screen format set output format echo echo commands inside script commands more control paged output in command window STARTING ANI QIIITTING FROM MATLAB quit terminate MATLAB startup M le executed when MATLAB is started matlabrc master startup M le MATRIX OPERATORS ARRAY OPERATORS addition addition subtraction subtraction multiplication multiplication A power A power right division left division conjugate transpose right division left division transpose kron Kronecker tensor product RELATIONAL ANI LOGICAL OPERATORS lt less than amp and lt2 less than or equal or gt greater than N not gt greater than or equal xor exclusive or equal N not equal SPECIAL CHARACTERS V assignment statement used to form vectors and matrices enclose multiple function output variables arithmetic expression precedence enclose function input variables decimal point parent directory continue statement to next line separate subscripts function arguments statements end rows suppress printing comments subscripting vector generation execute operating system command SPECIAL VARIABLES AND CONSTRAINTS ans answer when expression not assigned eps oating point precision realmax largest oating point number reammin smallest positive oating point number pi 7r i j imaginary unit inf in nity NaN Not a Number ops oating point operation count margin number of function input arguments nargout number of function output arguments computer computer type TIME AND DATE date current date clock wall clock etime elapsed time function tic toe stopwatch timer functions cputime elapsed CPU time 24 SPECIAL lVIATRICES zeros matrix of zeros ones matrix of ones eye identity diag diagonal toeplitz Toeplitz magic magic square compan companion linspace linearly spaced vectors logspace logarithmically spaced vectors meshgrid array for 3 D plots rand uniformly distributed random numbers randn normally distributed randon numbers hilb Hilbert invhilb inverse Hilbert exact vander Vandermonde pascal Pascal hadamard Hadamard hankel Hankel rosser symmetric eigenvalue test matrix Wilkinson Wilkinson s eigenvalue test matrix gallery two small test matrices MATRIX MANIPIILATION diag create or extract diagonals rot90 rotate matrix 90 degrees iplr ip matrix left to right ipud ip matrix up to dovvn reshape change size tril lower triangular part triu upper triangular part transpose convert matrix to single column A LOGICAL FUNCTIONS exist check if variables or functions exist any true if any element of vector is true all true if all elements of vector are true nd find indices of non zero elements isnan true for NaNs isinf true for in nite elements nite true for finite elements isieee true for IEEE floating point arithmetic isempty true for empty matrix issparse true for sparse matrix isstr true for text string strcmp compare string variables CONTROL FLOW if conditionally execute statements else used With if elseif used with if end terminate if for while for repeat statements for a specific number of times while repeat statments While condition is true break terminate execution of for or while loops return return to invoking function error display message and abort function PROGRAMMING input prompt for user input keyboard invoke keyboard as if it were a script file menu generate menu of choices for user input pause wait for user response function define function eval execute string With MATLAB expression feval evaluate function specified by string global de ne global variables nargchk validate number of input arguments 26 TEXT AND STRINGS string abs blanks eval numZStr intZStr str2num isstr strcmp upper lower hex2num hex2dec dec2hex about character strings in MATLAB convert string to numeric values a string of blanks evaluate string with MATLAB expression convert number to string convert integer to string convert string to number true for string variables compare string variables convert string to uppercase convert string to lowercase convert hex string to oating point number convert hex string to decimal integer convert decimal integer to hex string DEBIIGGING dbstop dbcont dbstep dbquit dbclear dbdown dbstack dbstatus set breakpoint remove breakpoint remove execution change local workspace context list who called whom list all breakpoints execute one or more lines list M le with line numbers change local workspace context opposite of dbup quit debug mode S ITND PROCESSING FUNCTIONS saxis sound auread auwrite lin2mu mu21in sound axis scaling convert vector to sound Read Sun audio le Write Sun audio le linear to mu law conversion mu law to linear conversion 27 ELEMENTARY MATH FUNCTIONS abs absolute value or complex magnitude angle phase angle sqrt square root real real part imag imaginary part conj complex conjugate gcd greatest common divisor 1cm least common multiple round round to nearest integer x round toward zero oor round toward OO ceil round toward 00 sign signum function rem remainder exp exponential base e log natural logarithm log10 log base 10 TRIGONOMETRIC FUNCTIONS sin asin sinh asinh cos acos cosh acosh tan atan tanh atanh cot acot coth acoth sec asec sech asech csc acsc csch acsch sine arcsine hyperbolic sine hyperbolic arcsine cosine arccosine hyperbolic cosine hyperbolic arccosine tangent arctangent hyperbolic tangent hyperbolic arctangent cotangent arccotangent hyperbolic cotan hyperbolic arccotan secant arcsecant hyperbolic secant hyperbolic arcsecant cosecant arccosecant hyperbolic cosecant hyperbolic arccosecant SPECIAL FUNCTIONS bessel bessel function beta beta function gamma gamma function rat rational approximation rats rational output erf error function erfinv inverse error function ellipke complete elliptic integral ellipj J acobian elliptic integral expint exponential integral log2 dissect oating point numbers pow2 scale oating point numbers 28 MATRIX DECOMPOSITIONS ANI FACTORIZATIONS inv inverse lu factors from Gaussian elimination rref reduced row echelon form chol Cholesky factorization qr orthogonal triangular decomposition nnls nonnegative least squares lscov least squares in presence of know covariance null null space orth orthogonalization eig eigenvalues and eigenvectors hess Hessenberg form schur Schur decomposition cdf2rdf complex diagonal form to real block diagonal form rsf2csf real block diagonal form to complex diagonal form balance diagonal scaling for eigenvalue accuracy qz generalized eigenvalues polyeig polynomial eigenvalue solver svd singular value decomposition pinv pseudoinverse MATRIX CONDITIONING cond condition number in 2 norm rcond LINPACK reciprocal condition number estimator condest HagerHigham condition number estimator norm 1 norm2 normF normOO norm normest 2 norm estimator rank rank ELEMENTARY MATRIX FIINCTIONS expm matrix exponential expml M file implementation of expm expm2 matrix exponential via Taylor series expm3 matrix I 39 39 via 39 and logm matrix logarithm sqrtm matrix square root funm evaluate general matrix function poly characteristic polynomial det determinant trace trace POLYNOMIALS poly construct polynomial With specified roots roots polynomial rootsicompanion matrix method roots1 polynomial rootsiLaguerre s method polyval evaluate polynomial polyvalm evaluate polynomial With matrix argument conv multiply polynomials deconv divide polynomials residue partial fraction expansion residues poly t fit polynomial to data polyder differentiate polynomial COLIINLVWBE DATA ANALYSIS max largest component min smallest component mean average or mean value median median value std standard deviation sort sort in ascending order sum sum of elements prod product of elements cumsum cumulative sum of elements cumprod cumulative product of elements hist histogram SIGNAL PROCESSING abs complex magnitude angle phase angle conv 39 andr 39 quot quotquot deconv deconvolution and polynomial division corrcoef correlation coef cients cov covariance matrix lter one dimensional digital filter lter2 two dimensional digital filter cplxpair sort numbers into complex pairs unwrap remove phase angle jumps across 360 boundaries nextpow2 next higher power of 2 ft radix 2 fast Fourier transform t2 two dimensional FFT i t inverse fast Fourier transform i t2 inverse 2 D FFT tshift zero th lag to center of spectrum 30 FINII E DIFFERENCES AND DATA INTERPOIIATION diff approximate derivatives gradient approximate gradient de12 five point discrete Laplacian subspace angle between two subspaces spline cubic spline interpolation interpl 1 D data interpolation interp2 2 D data interpolation interpft 1 D data interpolation via FFT method griddata data gridding NUMERICAL INTEGRATION quad adaptive 2 panel Simpson s Rule quad8 adaptive 8 panel Newton Cotes Rule trapz trapezoidal method DIFFERENTIAL EQUATION S OLIITION ode23 2nd3rd order Runge Kutta method 0de23p solve via 0de23 displaying plot ode45 4th 5th order Runge Kutta Fehlberg method NONLINEAR EQUATIONS ANI OPTIMIZATION fmin minimize function of one variable fmins minimize function of several variables fsolve solution to a system of nonlinear equations find zeros of a function of several variables fzero find zero of function of one variable fplot plot graph of a function TWO DIMENSIONAL GRAPHS plot linear plot loglog log log scale plot semilogx semilog scale plot semilogy semilog scale plot ll draW filled 2 D polygons polar polar coordinate plot bar bar graph stairs stairstep plot errorbar error bar plot hist histogram plot rose angle histogram plot compass compass plot feather feather plot fplot plot function GRAPH ANNOTATION title graph title xlabel x axis label ylabel y axis label zlabel z axis label for 3 D plots grid grid lines text text annotation gtext mouse placement of text ginput graphical input from mouse FIGURE WINDOWAXIS CREATION AND CONTROL gure gcf clf close hold ishold subplot axes gca axis caxis whitebg cinvert create figure graph Window get handle to current figure clear current figure close figure hold current graph return hold status create axes in tiled positions create axes in arbitrary positions get handle to to current axes control axis scaling and appearance control pseudocolor axis scaling change default background color to White invert blackWhite objects 32 GRAPH HARDCOPY AND STORAGE print print graph or save graph to file printopt con gure local printer defaults orient set paper 39 THREE DIMENSIONAL GRAPHS mesh 3 D mesh surface meshc combination mesh contour plot meshz 3 D mesh with zero plane surf 3 D shaded surface surfc combination surfacecontour plot surfl 3 D shaded surface with lighting plot plot lines and points in 3 D space ll draw filled 3 D polygons in 3 D space contour contour plot contour 3 D contour plot clabel contour plot elevation labels contourc contour plot computation used by contour pcolor pseudocolor checkerboard plot quiver quiver plot image display image waterfall waterfall plot slice volumetric visualization plot 3 D GRAPH APPEARANCE view 3 D graph viewpoint speci cation viewmtx view transformation matrices hidden mesh hidden line removal mode shading color shading mode axis axis scaling and apearance caxis pseudocolor axis scaling specular specular re ectance diffuse diffuse re ectance surfnorm surface normals colormap color lookup table see below brighten brighten or darken color map spinmap spin color map rgbplot plot colormap hsv2rgb hsv to rgb color map conversion rgb2hsv rgb to hsv color map conversion 33 COLOR MAPS hsv hue saturation value default jet variant of hsv gray linear gray scale hot black red yellow White cool shades of cyan and magenta bone gray scale With tinge of blue copper linear copper tone pink pastel shades of pink ag 39 red White blue and black 3 D OBJECTS sphere generate sphere cylinder generate cylinder peaks generate demo surface lVIOVIES ANI ANIMATION moviein initialize movie frame memory getframe get movie frame movie play recorded movie frames HANDLE GRAPHICS OBJECTS gure create figure Window axes create axes line create line text create text patch create patch surface create surface image create image uicontrol create user interface control uimenu create user interface menu I IANDLE GRAPHICS OPERATIONS set set object properties get get object properties reset reset object properties delete delete object drawnow ush pending graphics events 34
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'