Home
MATLAB Users Manual - University of Victoria
Contents
1. 1 0000 1 00001 3 0000 2 0000 1 0000i1 0 2 0000i Determinant of a Square Matrix The determinant of a square matrix A is calculated using the triangular factors obtained from Gaussian elimination and can be computed by det A Suppose A 1 23 4 gt gt det A ans 2 Rank of a Matrix The rank of a matrix A is the largest number of columns or rows of A that constitutes a linearly independent set To compute the rank of a matrix use the function rank A in MATLAB For example for the matrix A i 2 3 4 gt gt rank A ans 2 LU Factorization of a Matrix For every square matrix A there exist a lower triangular matrix L an upper triangular matrix U and a permutation matrix P such that PA LU To compute the LU factors for a matrix by Gaussian elimination with partial pivoting use the function lu A in MATLAB For example suppose A 1 Sx 32 4 gt gt L U P lu A L 1 0000 0 0 5000 1 0000 U 2 4 0 1 40 MATLAB USER MANUAL Cholesky Factorization of a Matrix The Cholesky factorization is a special case of LU factorization Suppose A is a real symmetric matrix If A is positive definite that is x Ax gt 0 for all nonzero column vectors x then A can be factored as A R R where R is an upper triangular matrix The function chel A in MATLAB is used to compute the Cholesky factor for a matrix A For example PP A 111 123 136 A 1 1 1 1 2 3 1 3 6 gt gt
2. b and R A is better conditioned than A gt gt R cholinc A 0 gt gt condest A ans 86 2192 gt gt condest inv R A ans 31 8511 47 MATLAB USER MANUAL Complete the computation of the solution x by typing the following command gt gt x gmres A b 12 1e 5 3 R To verify the solution type Says AY s The entries of the vector y should all be equal to 1 Polynomial Roots and Interpolation examples are given to illustrate their use ATLAB provides a number of functions for manipulating polynomials gt such as for root finding and curve fitting In the following section some Representation of a Polynomial MATLAB stores the coefficients of a polynomial in a row vector ordered by descending powers For example the coefficients of the polynomial p x x 1 can be entered in MATLAB as follows gt gt p 1 0 1 1 0 1 Find the Roots of a Polynomial Equation The roots of a polynomial equation p x 0 are the real or complex values for which p X 0 The roots can be computed using the command reots p In the case of the above polynomial the roots are calculated as follows gt gt r roots p t 1 1 Characteristic Polynomial of a Matrix The characteristic polynomial of an n x n matrix A is defined as det rl A where r is a variable and I is the n x n identity matrix The characteristic polynomial is calculated using the command poly A Suppo
3. For example mayne Determine the Name of Your Computer At the prompt type who am i This command will give you a result back similar to the line below username termid date hostname Set Environment Variable for the Output Display Simply type the UNIX command below MATLAB USER MANUAL setenv DISPLAY hostname 0 For example setenv DISPLAY boxter 0 4 Start MATLAB Type the command below matlab Ina ft Enviror nt Starting MATLAB on a Windows Desktop MATLAB for Windows is available in ELW B228 and B203 To start the Windows version of MATLAB on a PC click on the Start button on the taskbar at the bottom of the desktop and then select Productivity MATLAB 6 1 Starting MATLAB Using X Windows on the NT 2000 Workstations This is the environment available in ELW B228 and B203 The basic steps to access the UNIX version of MATLAB on SHELL are as follows 1 Start Up An X Window Session Click on the Start button and then select networl X Win32 An icon should appear on the taskbar at the bottom of the desktop 2 Start Up An SSH Client to SHELL Click on the Start button and then select network SSH Client After this step a SSH Client window should appear To complete the connection to shell ese uvie ca follow the steps from a to d below a Click on Quick Connect on the menu bar at the top of the SSH widow ot click on File on the menu bar and then select Connect b Type the name for the remote ser
4. MARKER y Yellow Solid o Circle m magenta Dashed 7 Asterisk c Cyan Dotted Point r Red Dash dot Plus Green none No line X Cross Blue s Square w White d Diamond Black Upward triangle Downward triangle Right triangle Left triangle Five point star Six point start Here is an example of a simple plot The output is shown in Figure 2 1 gt gt t 0 0 001 2 pi gt gt x cos 3 t gt gt y sin 2 t gt gt plot x y 08 0 6 0 4 0 4 0 6 0 8 06 04 02 o 0 2 04 06 Figure 2 1 x y Plot 27 MATLAB USER MANUAL MATLAB provides commands ezplet and fplot for plotting mathematical functions The syntaxes for the commands are ezplot function xmin xmax ymin ymax and fplot function xmin xmax ymin ymax respectively Both commands plot a function in a specified range However if a line style different from the default is required then fplot function xmin xmax ymin ymax style option should be used For example let us first create a function in an M file called myFunetion m and then use the command ezplot myFunction 0 2 pi 0 12 to generate the graph on the specified range The output is shown in Figure 2 2a To generate the same plot using a dotted line instead of a solid line default use fplot myFunction 0 2 pi 0 12 J xr Note that xt means a dotted red line with cross markers is used in the plot The out
5. R chol A R 1 1 1 0 12 0 0 1 gt gt R R ans 1 1 1 r23 1 3 6 QR Factorization of a Matrix Any matrix A can be factored as a product QR where Q is orthogonal or unitary and R is upper triangular This decomposition is used for example to compute the eigenvalues of a matrix and to solve least squares problems To compute the QR factorization of a matrix A use the function qr A SupposeA 1 0 1 2 2 3 0 1 3 41 MATLAB USER MANUAL gt gt Q R qr A Q 0 4472 0 5963 0 6667 0 8944 0 2981 0 3333 0 0 7454 0 6667 R 2 2361 1 7889 3 1305 0 1 3416 2 5342 0 0 1 6667 Eigenvalues and Eigenvectors of a Matrix If A is a square matrix and if a scalar and a nonzero vector x satisfy the equation Ax ax then A is called an eigenvalue and x is called an eigenvector of the matrix A The function eig A allows you to compute eigenvalues and eigenvectors of a matrix Suppose A 5 3 2 3 8 4 1 3 9 gt gt V D eig A V 0 4690 0 8714 0 1763 0 8760 0 4583 0 2421 0 1129 0 1751 0 9541 D 10 1218 0 0 0 3 8243 0 0 0 9 9461 To verify that 10 1218 is an eigenvalue of A with corresponding 0 4690 eigenvector 0 8760 enter the following 0 1129 gt gt A V 1 ans 4 7472 8 8666 1 1429 42 MATLAB USER MANUAL gt gt D 1 1 V1 ans 4 7472 8 8666 1 1429 e Singular Values of a Matrix If A is an m x n matrix with rank r then there exist r
6. compare corresponding entries of matrices with the same dimensions The Boolean values true and false are stored and displayed as 1 and 0 respectively Relational Operators OPERATOR DESCRIPTION lt Less then gt Greater then lt Less than or equal gt Greater than or equal Equal Not equal Logical Operators OPERATOR DESCRIPTION amp And Or 5 Not Examples 14 MATLAB USER MANUAL gt gt 293 lt 9 3 2 gt 9 ans 2 gt gt 235 gt 034 ns 1 0 1 D gt gt 1 23 3 4 lt 1 5 6 2 ans 1 1 0 Note To test if two matrices are identical use isequal For example if A 1 2 1 2 and C then o a e h o gt gt isequal A C ans 0 if statement The if statement executes a group of statements if the evaluated expression is true The optional elseif and else provide alternatives for execution of different groups of statements Syntax if expression statements else statements end if expression1 statements elseif expression2 statements else statements end Example 15 MATLAB USER MANUAL gt gt ifx gt 10 zZ 1 else if y gt 0 z else Z end switch and case Statements The switch statement evaluates an expression and then executes a group of statements under the first matching ease statement If no matching ease statement is found then the statements under the optional otherwise statement are execu
7. form above m 0 and seme c x t u 1 Ox a eee Ox Ox T 0 Ox ff st 63 MATLAB USER MANUAL 2 Write a function that evaluates the terms c f and s in the differential equation as follows M file pdeHeat m function c f s pdeHeat x t u DuDx Set required c f s for the equation Cok DuDx s 0 3 Write the function that represents the initial conditions as follows M file pdeHeatic m function u0 pdeHeatic x inital condition u x 0 sin pr x u0 sin pr x 4 Rewrite the boundary conditions in the required form Ou u 0 t 0 0 t 0 at x 0 Ox sie e0 C0 0 at x 1 Ox Write the function that represents the boundary conditions N file pdeHeatbc m function pl ql pr gr pdeHeatbe xlulxr ur t Set boundary conditions u 0 t u 1 t 0 pl ul ql 0 64 MATLAB USER MANUAL pr ur qr 0 6 Run the following script to solve the given problem gt gt m 0 gt gt x linspace 0 1 20 gt gt t linspace 0 2 5 gt gt sol pdepe m pdeHeat pdeHeatic pdeHeatbc x t The following script generates a plot of the numerical solution gt gt u sol 1 gt gt surf x t u gt gt title Numerical solution to Heat Equation gt gt xlabel Distance x gt gt ylabel Time t Numerical soktion to Heat Equation Timet The actual solution to this problem is u x t e sin zx Run the fo
8. gt hold on gt gt Plot the computed solution gt gt plot t y o MarkerEdgeColor r MarkerFaceColor r Example2 Solve the second order initial value problem y 2y t2y e sint O0 lt x lt 1 y 0 0 4 y 0 0 6 1 Rewrite the problem as a first order system 59 MATLAB USER MANUAL Set y y and y y and rewrite the second order equation as a system of two first order equations Yi Vo yy e sint 2y 2y y 0 0 4 y 0 0 6 2 Write a function that evaluates the differential equations as follows M file myODE2 m function dy myODE2 t y Initial Value Problem for a Second order Equation y1 y2 y2 exp 2t sin t 2y2 2y1 y10 0 4 y2 0 0 6 dy y exp t sin t 2 y8 2 y 3 Run the following script to solve the given problem gt gt tspan 0 1 gt gt yzeto 0 4 0 6 gt gt jt y ode45 myODE2 tspan yzeto 4 View the computed solutions The exact solution to the problem is y t 0 2e sint 2cost and y t 0 2e 4sint 3cost The following script generates a plot which compares the approximate computed solution with the exact solution To plot the actual values and the computed values of y type gt gt w 0 0 05 1 gt gt f 0 2 exp 2 w sin w 2 cos w gt gt Plot the exact solution gt gt plot w f gt gt hold on gt gt Plot the co
9. the spline function returns a data structure pp that contains the piecewise polynomial form of the cubic spline interpolant This data structure is called the pp form and can be used by other functions such as ppval For example gt gt x 0 pi 4 3 pi 8 pi 2 3 pi 4 pil gt gt y cos x gt gt xx linspace 0 pi 40 gt gt yy spline x y xx 53 MATLAB USER MANUAL gt gt z linspace 0 pi 50 gt gt plot z cos z x y MarkerSize 20 gt gt hold on gt gt plot xx yy gt gt axis 0 3 5 1 1 gt gt hold off The resulting plot is shown below This is the same example as the one in the one dimensional interpolation except that the spline function is used instead 19ers If there is more than one set of interpolated values the pp form of the spline function can be used in combination with the function ppval pp xx For example gt gt x 0 pi 4 3 pi 8 pi 2 3 pi 4 pil gt gt y cos x gt gt pp spline x y gt gt xx1 linspace 0 pi 2 20 gt gt yyl ppval pp xx1 gt gt z linspace 0 pi 50 gt gt plot z cos z gt gt hold on gt gt plot xx1 yy1 MarkerSize 10 The statements above compute interpolated values yy1 on the interval 0 pi 2 Similarly gt gt xx2 linspace pi 2 pi 20 gt gt yy2 ppval pp xx2 gt gt plot xx2 yy2 o MarkerSize 10 Mark
10. 00 1 00001 3 0000 The Colon Notation The colon notation is useful for constructing vectors with equally spaced entries The syntax for using the colon notation to generate a vector is m s n which generates entries from m to n with an increment for each step of s If the required increment is 1 then the syntax becomes min Note that m s and n need not be integers For example gt gt v 1 4 y 1234 gt gt w 12 3 0 wW 12 9 630 gt gt y 5 2 0 y 5 3 1 gt gt x 0 2 5 x 0 2 4 gt gt z 0 2 0 3 1 2 Z 0 2000 0 5000 0 8000 1 1000 Subscripting Each of the entries in a matrix A can be accessed by A i j where i gt 1 andj 21 If vis a vector of the row indices of a matrix A and w is a vector of the column indices of A then A v w is the submatrix of MATLAB USER MANUAL A from the selected rows and columns If the row and column indices are consecutive then A r s p q denotes the submatrix from rows r S and from columns p q A colon can be used to select all of the row or column indices For example gt gt A 123 456789 A I 28 4 5 6 7 8 9 gt gt A 3 3 ans 9 gt gt B A 1 3 2 3 B gt gt C A 1 2 2 3 G 2 3 5 6 gt gt D A 1 2 D 1 2 4 5 7 8 Arithmetic Operators The table below lists all of the MATLAB arithmetic operators Other operators such as logical and relational operators are described in the sectio
11. 2 x 1 1 x 0 5 pi 1 5 1 5 1 A 7 2i i 0 5 Ey fi 1 5 OF 1 mn j 547 bh 44 0 5 f J lt 1 l x 0 oS 0 2 4 6 8 0 2 4 6 8 12 15 10 in j J i f y TE t___ i of A i J j i l 0 5 A owe dy AN 1 1 fl i 2 N i I igi 1 L a XJ J V V V V U J j U U cal 0 2 4 6 5 10 15 Figure 2 5 Generating Multiple Plots Using subplot Using a Matrix To create multiple plots in a single graph as in the last sub region in Figure 2 5 one can also use a matrix Each column of the matrix contains the functional values that are to be plotted as one graph In the following note that cos x is a row vector of functional values and cos x is a column vector is the transpose operator The following example is illustrated in Figure 2 6a gt gt x 0 0 01 2 pi gt gt Y cos x cos 2 x cos 4 x J gt gt plot x Y If different styles are desired for different plots replace plot x Y with for example plot x Y 1 x Y 2 x Y 3 The result is shown in Figure 2 6b 32 MATLAB USER MANUAL 4 Figure 2 6a Generating Multiple Plots Using a Matrix 08 06 0 4 0 2 0 4 0 6 0 8 Figure 2 6b Multiple Plot
12. 22 23 23 23 25 26 26 26 28 29 30 31 34 35 36 36 37 39 Determinants Rank Factorizations Eigenvalues Singular Value Decomposition Sparse Matrices Iterative Methods Polynomial Roots and Interpolation Polynomials Polynomial Interpolation Quadrature Integrating Functions of One Variable Ordinary Differential Equations Initial Value Problems Partial Differential Equations Parabolic and Elliptic Equations Other Useful Functions Functions for Nonlinear Algebraic Equations Functions for Data Analysis References 40 40 40 42 43 44 46 48 48 50 56 56 58 58 62 66 66 69 MATLAB USER MANUAL Accessing and Quitting MATLAB Accessing MATLAB M MATLAB is located ATLAB is available on both UNIX and MS Windows platforms in the Department of Computer Science MATLAB can be accessed from the workstations located in ELW B215 B228 and B203 or from any UNIX workstation that allows access to SHELL where the UNIX version of The PCs in ELW B228 and B203 can be used to access MATLAB from a Windows Environment In a UNIX Environment Starting MATLAB on an X Windows Desktop This is the environment available in ELW B215 The basic steps to access MATLAB are as follows 1 Start Up A SSH Client Session to SHELL In an X Terminal type ssh shell csc uvic ca at the prompt and then enter your password You should get a UNIX prompt on the remote server after this step
13. 884 coef 1 0000 6 0000 72 0000 27 0000 Note that a function can be called with a different number of input or output arguments by using the built in functions nargin and nargout The example below is the same function as EigValues above except the output of the coefficients is optional N file EigValues m Script M file EigValues m This function takes a matrix A as input returns a list of the eigenvalues of A and optionally returns the coefficients of the characteristic polynomial det rI A 20 MATLAB USER MANUAL To call this function type eigvalues coeffs EigValues A function eigvalues coeffs EigValues A p poly A eigvalues roots p if nargout 2 coeffs p end gt gt eig EigValues C eig 12 1229 5 7345 0 3884 Subfunctions As mentioned earlier an M file can contain subfunctions besides the primary function Any subfunction must appear after the primary function Subfunctions are local and can be called only by the primary function and other subfunctions in the same M file N file BigTrace m function result Big Trace A B Primary function The variable result is set to equal maximum of trace A and trace B result max trace A trace B function t trace C Subfunction Return the sum of the diagonal elements of the matrix C t sum diag C Recursive Functions Note that MATLAB supports recursive function cal
14. AB USER MANUAL COMMAND DESCRIPTION area Create an area graph bar Create a bar graph barh Create a horizontal bar graph compass Create an arrow graph for complex numbers contour Make a contour graph hist Create a histogram graph pie Create a pie graph scatter Create a scatter graph stairs Create a stair step graph polar Plot polar coordinates plotmatrix Draw scatter plots plo Create a 2 D plot fplot Plot a function between specified ranges with line styles ezplot Plot a function between specified ranges subplot Create and control multiple axes grid Grid lines for two dimensional plots xlabel ylabel Create labels for x axis and y axis title Add titles to current axes legend Create a legend on a graph hold Hold current graph in a figure text Create text objects in current axes fill Filled two dimensional polygons line Create a line object axis Set ranges for x axis and y axis 35 MATLAB USER MANUAL Ci i Basic Functions for Linear Algebra and Numerical Analysis Linear Algebra M these MATLAB functions to solve linear algebra problems Vector and Matrix Norms Norms which are scalars are measures of the size of vectors and matrices P norm of a Vector The p norm of a vector x is 1 p x forl lt p lt o L n 2 i l Ix p The sum norm p 1 and the Euclidean norm p 2 are particular cases of p norms In MATLAB a norm is calculated by using the function norm x p
15. Suppose x 2 4 6 8 gt gt norm x 1 norm x 2 ans 20 0000 10 9545 Note that norm x 2 can be computed by norm x 36 ATLAB has an extensive set of functions for computations in linear algebra such as functions for computing the inverse and the determinant of a matrix In the following section several fundamental concepts from linear algebra are defined and some examples are given to illustrate how to use MATLAB USER MANUAL When p gt the p norm becomes the max norm defined as For example to compute the max norm of the vector x used in the previous example type Xx el max tf Josh gees gt gt norm x inf ans 8 P norm of a Matrix The p norm of a matrix A is Ax max a p The maximum column sum matrix norm p the maximum row sum matrix norm p and the spectral norm p 2 are particular cases of the p norms and they can be computed respectively by n A max ai gt 1 i lt j lt n jal n A max gt ay and oe I lt i lt n j A max vA Ais an eigenvalueof A A Suppose matrix A 1 25 33 4 To use the function norm A p to compute these matrix norms type gt gt norm A 1 norm A inf norm A 2 ans 6 0000 7 0000 5 4650 Note that norm A 2 can be computed by norm A Inverse of a Square Matrix The inverse of a square matrix A is the matrix A such that a a AA 1 wher
16. Volume UNIVERSITY OF VICTORIA Department of Computer Science MATLAB User Manual DEPARTMENT OF COMPUTER SCIENCE MATLAB User Manual Lanjing Li Department of Computer Science University of Victoria PO Box 3055 STN CSC Victoria BC Canada V8W 3P6 Phone 250 721 7209 Fax 250 721 7292 Table of Content CHAPTER 1 Accessing and Quitting MATLAB Accessing MATLAB In a UNIX Environment In a MS Windows Environment Quitting MATLAB Some Useful Help Commands CHAPTER 2 Basics of MATLAB MATLAB Environment MATLAB Windows Other Features of the MATLAB Desktop Data Structures and The Operators Scalars Vectors Matrices The Colon Notation and Subscripting Operators gt A O N a VV VN VN 8 9 Precedence Rules for Operators 12 Character Strings Variables Declaration Global Variables Flow of Control Relational and Logical Operators 12 13 13 14 14 14 Control Statements M File Basics Creating M Files Running M Files Summary of Useful Commands Input Output and Data Formatting Input Output Format Summary of Useful Commands Graphics Basic Plots Graph of a Function Define Titles Labels and Text in a Graph Commands for Controlling the Axes Multiple Plots in One Figure Save and Print a Figure Commands for 2D Plotting Functions Chapter 3 Basic Functions for Linear Algebra and Numerical Analysis Linear Algebra Vector and Matrix Norms Inverses Transposes 15 18 18 22
17. anagement system can be used to search open view and edit files To launch the Directory Browser select Current Directory from the View menu on the desktop or type filebrowser in the Command Window Alternatively you can use the following file management commands COMMAND DESCRIPTION cd Changes the current working directory pwd Shows the current working directory dir Lists contents of the current directory Is Lists contents of the current directory mkdir Creates a directory MATLAB USER MANUAL Data Structures and The Operators N matrix is the fundamental data structure in MATLAB scalars and vectors are special cases of a matrix The entries of a matrix can be either real numbers or complex numbers Definition A scalar is a number that can be either a real or complex number A scalar is a special case of a 1 x 1 matrix For example Definition A vector is a special case of a matrix with one row or one column For example gt gt u 1 2 u 1 0000 1 1000 0 gt gt w 2 3 6 1 y 2 0000 3 6000 1 0000 Definition An m x n matrix is a two dimensional array of scalars consisting m rows and n columns A space or a comma separates consecutive entries in a row and a semicolon or a carriage return separates consecutive rows For example MATLAB USER MANUAL gt gt A 1 2 3 4 A 1 2 3 4 gt gt B 1 1 1 1 2 2 i 3 B 0 1 00001 1 0000 1 0000 1 0000 2 0000 2 00
18. ation The default interpolation method is linear METHOD DESCRIPTION linear Bilinear interpolation spline Cubic spline interpolation nearest Nearest neighbor interpolation cubic Bicubic interpolation Functions Similar to the command interp1 the command interp2 X Y Z XX YY method performs two dimensional interpolation of the type specified by the parameter method see above The matrices X Y and Z specify the given data to be interpolated for example Zj f x yoy The arrays XX and YY specify the points at which the interpolating polynomial is evaluated For example gt gt x 4 0 5 4 gt gt y 0 0 5 8 gt gt X Y meshgrid x y gt gt Z peaks X Y gt gt xx linspace 4 4 50 gt gt yy linspace 0 8 50 gt gt XX YY meshgrid xx yy gt gt ZZ interp2 X Y Z XX YX bicubic Enter the command surf X Y Z to generate a plot of the original data 52 MATLAB USER MANUAL Enter the command surf XX YY ZZ to generate a plot of the interpolated data Spline Function The spline function can be used to do cubic spline interpolation This function has two forms yy spline x y xx and pp spline x y Given vectors x and y the function computes the cubic spline interpolating polynomial S that interpolates the given data specified by the vectors x and y and then it returns the values S xx in the vector yy Alternatively
19. conditioner that is chosen to make computation of the solution more efficient The goal is to find a simple matrix M so that M Ax is neat to the identity matrix The table below lists a set of MATLAB functions corresponding to iterative methods 46 MATLAB USER MANUAL COMMAND DESCRIPTION bicg Biconjugate gradient bicgstab Biconjugate gradient stabilized cgs Conjugate gradient squared gmres Generalized minimum residual Isqr Conjugate Gradients on the normal equations minres Minimum residual peg Preconditioned conjugate gradient qmr Quasiminimal residual symmlq Symmetric LQ The basic syntax of the functions above is function_name A b restart tol maxit M where function_name is the name of a function in the table above restart defines the number of inner iterations such that the method restarts after evety restart inner iterations tel specifies the error tolerance of the method maxit specifies the maximum number of outer iterations and M is the preconditioner Example Suppose A is a 139 x 139 five point discrete negative Laplacian and b is a 139 x 1 column vector Solve the linear system Ax b using the generalized minimum residual method gmres Note that A is a symmetric positive definite sparse matrix gt gt A delsq numerid C 15 gt gt b ones 1 139 Perform the incomplete Cholesky factorization and use the factor R of the matrix A as the preconditioner M Note that M Ax R Ax R
20. division matrix left division 5 Addition subtraction 6 Colon operator 7 Less than lt less than or equal to lt greater than gt greater than or equal to gt equal to not equal to 8 Logical AND amp 9 Logical OR Definition A character string which is enclosed by a pair of single quotes is an array of characters The internal representation of each character is a numerical value and requires 2 bytes for storage For example gt gt myString This is my first string mysString This is my first string String Functions The most common commands that manipulate character strings ate summarized in the table below 12 MATLAB USER MANUAL COMMAND char blank n deblank s eval findstr s1 s2 int2str n ischar s isletter s isstting s lower mat2str num2str strcmp s1 s2 strempi s1 s2 strncmp s1 s2 n strncmpi s1 s2 n DESCRIPTION Create character array A string of n blanks Strip trailing blanks from the end of a string Execute a string containing an expression Find one string within another Integer to string conversion True for character arrays True for alphabetical characters True for if the argument is a string version 5 Convert string to lower case Convert a matrix into a string Convert numbers to a string Compare strings Compate strings ignoring case Compare the first n characters of two strings Compare the first n charact
21. drature dblquad Evaluate double integral Double integral trapz Trapezoidal numerical integration Trapezoidal Rule Ordinary Differential Equations M ATLAB provides software for solving both initial value and boundary value problems In the following section examples are given to illustrate how to solve initial value problems a single differential equation and a system of differential equations Description These problems have the form y f t y subject to y ty Yo where t is a scalar variable the independent variable y y t and the initial condition is y t Yo The functions y t and f t y and the constant y can be vectors with more than one component Example Solve the initial value problem ye y t 1 0 lt t lt 2 y 0 05 First create the function myODE below and save the function in the file myODE m M file myODE m function dy myODE ty Initial Value Problem Voy y t t 1 0 lt t lt 2 y 0 0 5 58 MATLAB USER MANUAL dy y t t 1 To run the function myODE enter the following gt gt tspan 0 2 gt gt yzero 0 5 gt gt t y ode45 myODE tspan yzero The exact solution to the problem is y t t 1 0 5e The following script generates a plot which compares the approximate computed solution with the exact solution gt gt w 0 1 2 gt gt f wt1 2 0 5 exp w gt gt Plot the exact solution gt gt plot w f gt
22. e I is the identity matrix The 37 MATLAB USER MANUAL function inv A is used to compute the inverse of a square matrix A For example gt gt A 12 3 4 A 1 2 3 4 gt gt B inv A B 2 0000 1 0000 1 5000 0 5000 gt gt I B A 1 0000 0 0 0000 1 0000 Pseudo inverse If a matrix A is a square and singular matrix or a rectangular matrix it does not have an inverse However A has a unique pseudo inverse which can be computed using pinv A For example gt gt A 123 579 A 5 gt gt B pinv A 1 3889 0 4444 0 2222 0 1111 0 9444 0 2222 gt gt B A ans 0 8333 0 3333 0 1667 0 3333 0 3333 0 3333 0 1667 0 3333 0 8333 38 MATLAB USER MANUAL gt gt A B ans 1 0000 0 0000 0 0000 1 0000 gt gt A B A ans 1 0000 2 0000 3 0000 5 0000 7 0000 9 0000 gt gt B A B ans 1 3889 0 4444 0 2222 0 1111 0 9444 0 2222 The transpose of a matrix A is obtained by interchanging the rows and columns of A and is computed by A in MATLAB Transpose of a Real Matrix For example SS AH ji A 1 2 3 4 gt gt A ans Conjugate Transpose of a Complex Matrix In addition to interchanging the rows and columns the conjugate transpose of a complex matrix A also replaces each entry by its complex conjugate For example gt gt A 1 i 2 3 2i A 1 0000 1 0000i 2 0000 1 0000i 3 0000 0 2 00001 39 MATLAB USER MANUAL gt gt A ans
23. e class of parabolic and elliptic partial differential equations that MATLAB can solve is of the form Ou Ou mO f m Ou Ou c x t u x x f x t u s x t u Ox j Ot Ox Ox Ox where fy St lt t a lt x lt b and m 0 1 or 2 The vector valued function uis a function of a space variable x and a time variable t At the initial time t the solution must satisfy initial conditions of the form u x t U x In addition at the boundaries x aandx b the solution must satisfy a boundary condition of the form p x t u ats stan 0 Ox 62 MATLAB USER MANUAL MATLAB provides a PDE solver pdepe The basic syntax of this solver 1S sol pdepe m pdefun icfun bcfun xmesh tspan where m corresponds to m in the form of PDE pdefun computes the terms c f and s in the form of PDE iefun evaluates the initial conditions befun evaluates the terms p and q in the form of the boundary condition xmesh is a vector specifying the points between a and b and tspan is a vector specifying the points between f and f Example The example below illustrates the steps to solve a given parabolic partial differential equation problem Consider the heat equation Dip Oty 5G O lt x lt l t gt 0 Op Gees i gt with boundary conditions u 0 t u 1 t 0 t gt 0 and initial conditions u x 0 sin z 0 lt x lt l 1 Rewrite the PDE in the required form Ou EP 0 x 1 4 0 Ox Ox Ox Given the
24. eal numbers 6 2 6 2 2 6 gt 0 an orthonormal basis v Vm and an orthonormal basis u u such that Av Ou t Lisa A u ov T derf Av 0 i rt 1 m A u 0 i t 1 gt gt In MATLAB the function svd A computes the singular value decomposition for a matrix A Suppose A is the 2 x 3 matrix p 2 0 2 02 gt gt U D V svd A ve 0 4472 0 8944 0 8944 0 4472 ow ll N o o o WS 0 7454 0 0000 0 6667 0 2981 0 8944 0 3333 0 5963 0 4472 0 6667 The function returns two orthogonal matrices U and V and a matrix D that contains the singular values of A in its diagonal entries To verify A uDV enter the following statement gt gt U D V ans 1 0000 2 0000 0 0000 2 0000 0 0000 2 0000 43 MATLAB USER MANUAL A sparse matrix is a matrix that contains a relatively large number of zero entries MATLAB provides a set of functions that stores only the nonzero entries of a sparse matrix and eliminates arithmetic operations on the zero entries Storage Information To find out the information about sparse and full versions of the same matrix use the command whes Suppose A 1 00 0 0 0 0 ip A nd B spar os a eG a sparse 003 0 gt gt whos Name Size Bytes Class A 4x4 128 double array B 4x4 80 sparse array Create a Sparse Matrix For a sparse matrix MATLAB uses three arrays to store only the nonzero entries their row indices and their column indices To create a
25. erEdgeColor r 54 MATLAB USER MANUAL MarkerFaceColor t gt gt axis 0 3 5 1 1 gt gt hold off compute interpolated values yy2 on the interval pi 2 pi Note that there is no need to recompute the same set of cubic spline coefficients a second time the previously computed pp form can be used The resulting plot is shown below e 0 cc 0 4 e e 06 e e 08 e To get details of the piecewise polynomial or the pp form use the function unmkpp pp For example to print the knots and the coefficients of the computed spline function above type the commands below gt gt breaks coefs unmkpp pp breaks 0 0 7854 1 1781 1 5708 2 3562 3 1416 coefs 0 1159 0 6123 0 0365 1 0000 0 1159 0 3392 0 7108 0 7071 0 1858 0 2026 0 9236 0 3827 0 1356 0 0163 0 9968 0 0000 0 1356 0 3357 0 7203 0 7071 Note that the values of the breaks are the entries of the vector x above and each row of the matrix coefs contains the coefficients of one of the cubic polynomials of the spline function 55 MATLAB USER MANUAL Quadrature M ATLAB provides a set of functions for evaluating definite integrals In the following section examples are given to illustrate the basic usage of these functions Description The numerical approximation of the definite integral i f x dx is called quadrature The basic syntax of the MATLAB quadrature functions is q quad fun a b where fun
26. ers of two strings ignoring case strcat String concatenation sttvcat Vertical concatenation of strings upper s Convert string to upper case s in other programming languages you can use variables to store values in the current session or in an M file There are two types of variables local and global Implicit Declaration MATLAB does not require explicit declarations for its variables with the exception of global variables used in MATLAB functions see Global Variables below When MATLAB encounters a new vatiable name it automatically creates the variable and allocates the appropriate amount of storage Length of a Variable A variable name begins with a letter optionally followed by a number of letters digits or underscores to a maximum of 31 characters Variable names are case sensitive 13 MATLAB USER MANUAL Explicit Declaration A global variable can be declared using the global command so that more than one function can share a single copy of the vatiable You must declare the variable as global at the beginning of every function that requires access to it Similarly you must declare it as glebal from the command line to enable your active workspace to access it Using uppercase characters for a global variable name is recommended Flow of Control n MATLAB flow of control depends on the results of evaluating logical expressions using relational and logical operators defined in the tables below These operators
27. g X Window Session Click on the icon X Win32 on the taskbar at the bottom of the desktop and then select Close MATLAB USER MANUAL Some Useful Help Commands COMMAND DESCRIPTION help List all help topics in the Command Window helpwin List all help topics in the Help Window help opic Give help on the specified topic quit Terminate MATLAB version Version of MATLAB type filename Display the contents of the specified file what List MATLAB specific files in the current directory more Control paged output for the Command Window MATLAB USER MANUAL Ci i Basics of MATLAB The General Structure of the MATLAB Environment he Command Window Graphics Window and Edit Window are the three basic windows available in MATLAB MATLAB Windows Command Window This is the primary and default window in which a user interacts with MATLAB Similar to any other command shells the prompt gt gt is displayed and a blinking cursor appears to the right of the prompt A user can type an individual command on the command line or run a program in this window For example to create a vector e with two elements type Se 110 e 1 0 Graphics Window This is a graphics editor as well as an output window for graphs or figures generated from commands entered in the Command Window To invoke the graphics editor type figure in the Command Window Edit Window This is a program editor where you create and modify your own program
28. gt disp B1 B2 disp B B1 B2 3 4 5 6 Similarly if x 0 756 then to display the formatted value of x type gt gt fprintf 7 2f n x 0 76 Note that the number 7 in the format string is the field width the number 2 is the number of decimal digits after the decimal point and the escape character n is a new line terminator Suppress Output from MATLAB Commands If you place a semicolon at the end of a statement line MATLAB executes the statement but does not display any output For example gt gt u 1 2 gt gt v ut 3 Keep a Session Log The diary command can be used to save the entire working session This command spools all the activities or events in the Command Window to a text file For example to save the current session type gt gt diary filename To suspend the diary type gt gt diary off If diary is used without a specified file name then MATLAB uses a default file name diary 24 MATLAB USER MANUAL For online help type help format or select MATLAB Help from Help menu gt gt format long MATLAB stores numbers to a relative precision of approximately 16 decimal digits By default MATLAB displays numbers in the short format 4 decimal places To print a value in any of the formats given below enter format Ape on the command line For example The following table illustrates the additional format types supported by MATLAB FORMAT EXAMPLES format sho
29. gt while n lt 1000 m m 3 if 1 m gt 1 n ntl continue end m m 3 break end m 1 7989e 016 M File Basics esides using the interactive computational environment you can also write programs in the MATLAB language and store them in files These files are called M files An M file is just an ordinary text file and hence it can be created using any text editor As mentioned earlier MATLAB provides a default M file editor for all platforms To open the default editor select New and then M File from the File menu of type edit in the Command Window To save an M file from the File menu select Save for an existing file or Save as for a new file An M file name 18 MATLAB USER MANUAL must have a m extension after the file name There are two types of M files script files and function files Scripts A script file is a file that contains a sequence of valid MATLAB commands and has no input or output arguments For example M file myScriptFile m Script M file myScriptFile m 1 Create a 3 x 3 matrix A 2 Compute the coefficients of the characteristic polynomial det AI A 3 Compute the roots of this polynomial eigenvalues of matrix A A 123 456 780 p poly A r roots p Function Files Similar to a script file a function file is a file that contains one or more functions The first function in the file is the primary function and the rest are subfunctions A subfunction can on
30. ial and reference Prentice Hall Upper Saddle River New Jersey USA 2001 ISBN 0 13 019468 9 4 Rudra Pratap Getting Started with MATLAB 5 A Quick Introduction for Scientists and Engineers Oxford University Press Inc New York New York USA 1999 ISBN 0 19 512947 4 5 Richard L Burden and J Douglas Faires Numerical Analysis PWS Publishing Company USA 1993 ISBN 0 534 93219 3 6 Usine MATLAB Version 6 The Math Works Inc Natick MA USA 2000 7 Roger A Horn Matrix Analysis Cambridge University Press Cambridge United Kingdom 1985 ISBN 0 521 38632 2 8 David S Watkins Fundamentals of Matrix Computations Jon Wiley amp Sons Inc New York New York USA 1991 ISBN 0 471 61414 9 69 70
31. is the function to be integrated a and b specify the interval of integration Example1 Consider the function below dx 2x 3 F x f 1 Write a MATLAB function for the function to be integrated Note that the MATLAB function should allow the argument x to be a vector that is the and operators are required in this function M file myintegral m function y mylntegral x Example for Quadrature ae Wy CO Sea OD 2 Run the following script to solve the given problem gt gt n 15 gt gt form 1 n b m 0 1 Int m quad myIntegral 0 b end 3 View the result 56 MATLAB USER MANUAL gt gt x linspace 1 1 5 15 gt gt plot x Int Example2 Another quadrature function in MATLAB is trapz x y This function computes a numerical approximation of the definite integral f f x dx by applying the trapezoidal rule Consider the example below 2 Suppose F x j d An approximation of this integral using trapz 1 X can be obtained as follows gt gt format long gt gt x linspace 1 2 50 gt gt y 1 x gt gt area trapz x y area 0 69317321002551 Note that the exact solution is In 2 0 69314718055995 Summary of Quadrature Functions The table below lists the quadrature functions in MATLAB 57 MATLAB USER MANUAL SOLVERS DESCRIPTION METHOD quad Adaptive Simpson quadrature Simpson quadrature quad Adaptive Lobatto quadrature Lobatto qua
32. llowing script to generate a plot of this solution and compare the two solutions gt gt ureal exp pi t sin pi x gt gt surf x t ureal gt gt title Actual solution to Heat Equation gt gt xlabel Distance x gt gt ylabel Time t MATLAB USER MANUAL Actual solution to Heat Equation Timet Other Useful Functions T here are a few other useful algebraic functions and functions for numerical analysis which are described as follows Functions for Nonlinear Algebraic Equations Find a Zero of a Function of One Variable The function fzero finds a zero of a function of one variable near a point x or within a given range For example gt gt fzero sin 2 4 ans 3 1416 Functions for Data Analysis Minimize a Function of One Variable The function fminbnd finds a local minimizer of a function of one variable within a given range A local minimizer X of f x is a value of x such that f X is minimum in an interval around For example gt gt fminbnd sin pi pi ans 1 5708 Note that the minimum value returned is pi 2 MATLAB USER MANUAL Maximum and Minimum Entries of an Array The functions max and min return the largest and the smallest entries respectively along a specified dimension of an array For example gt gt w 1 3 3 56 4 1 gt gt min w ans 3 5600 gt gt max w ans 4 1000 Sum and Cumulative Su
33. ls Syntax of Comments In an M file MATLAB treats all text after a percent sign as a comment statement Comments can appear anywhere in an M file as shown in the examples above 21 MATLAB USER MANUAL From the Command Line To invoke an M file either a function file or a script file type the name of the file without the m extension from the command line in the Command Window For example you can call the function BigTrace from the command line as follows Suppose A 1 2 3 4 5 6 7 8 OjandB 3 4 5 6 gt gt BigTrace A B ans 9 Within Another M file A function or a script can similarly be called from another M file COMMAND DESCRIPTION type filename Display the contents of a specified file edit filename Invoke the default editor path Display the current MATLAB search path tic toc tic starts a timer and toc returns elapsed time profile A debugging utility lookfor Search for the specified keyword in all help entries dbstop Set breakpoints in an M file function dbclear Clear breakpoints in an M file function dbcont Resume execution dbquit Quit debug mode keyboard return Invoke and terminate the keyboard mode in an M file nargin Number of input function arguments nargout Number of output function arguments which Locate functions and files pcode Create pre parsed pseudocode file 22 MATLAB USER MANUAL Input Output and Data Formatting ATLAB allows user input during runtime save
34. ly be called by the primary function and other subfunctions within the same file The primary function or a subfunction can contain any valid MATLAB statements A function or subfunction starts with a function definition line which specifies a list of input and or output arguments The syntax of the function definition line is defined as follows function output variables function_name input variables The output variables and the input variables are both optional Note that MATLAB function names are specified in the same way as variable names that is they begin with a letter and are up to 31 characters long To save a function file one must use the primary function name for the M file For example if the primary function name is EigValues the file name is EigValues m Passing Parameters to and Returning Parameters from a Function Below are two simple examples to illustrate how a MATLAB function works N file EigValues m 19 MATLAB USER MANUAL Script M file EigValues m This function takes a matrix A as input and returns a list of the eigenvalues of A and the coefficients of the characteristic polynomial det rI A To call this function type eigvalues coeffs EigValues A function eigvalues coeffs EigValues A p poly A eigvalues roots p coeffs p gt gt C 123 456780 C a fe 2 3 5 6 8 0 gt gt eig coef EigValues C eig 12 1229 5 7345 0 3
35. m The function sum computes the sum of the entries of an array along a specified dimension Similarly the function cumsum computes the cumulative sum of the entries of an array For example gt gt A 123 579 041 A 1 2 3 579 04 1 gt gt sum A ans 6 13 13 gt gt cumsum A ans P23 6 9 12 6 13 13 Product and Cumulative Product The function prod computes the product of the entries of an array along a specified dimension Similarly the function cumprod computes the cumulative product For example 67 MATLAB USER MANUAL gt gt A 123 579 041 A T 2 3 579 04 1 gt gt prod A ans 0 56 27 gt gt cumprod A ans G2 3 3 5 14 27 0 56 27 Sort Elements The function sort sorts elements in ascending order For example gt gt w 1 6 4 0 gt gt sort w ans 4 1 0 6 Differences The function diff computes differences between adjacent entries of an array along a specified dimension For example gt gt C 258 16 10 3 65 Ge 2 5 8 1 6 10 3 6 5 gt gt diff C ans 1 1 2 2 0 5 MATLAB USER MANUAL References 1 Desmond J Higham and Nicholas J Higham MATLAB Guide Society for Industrial and Applied Mathematics Philadelphia PA USA 2000 ISBN 0 89871 469 9 2 Getting Started with MATLAB Version 6 The Math Works Inc Natick MA USA 2000 3 Duane Hanselman and Bruce Littlefield Mastering MATLAB 6 a comprehensive tutor
36. mial p x in one variable x interpolates a given set of values x y 1 lt i lt n if p x y fori Dat fi Methods There ate six methods available for one dimensional interpolation The default interpolation method is linear 50 MATLAB USER MANUAL METHOD DESCRIPTION linear Linear interpolation spline Cubic spline interpolation nearest Nearest neighbor interpolation pchip Piecewise cubic Hermite interpolation cubic Piecewise cubic Hermite interpolation v5cubic Cubic interpolation used in MATLAB 5 e Use The command interp1 x y xx method computes an interpolating polynomial p x of the type specified by the parameter method see above for the data specified in the vectors x and y and returns the interpolated values p xx For example gt gt x 0 pi 4 3 pi 8 pi 2 3 pi 4 pil gt gt y cos x gt gt xx linspace 0 pi 40 gt gt yy interp1 x y xx linear gt gt z linspace 0 pi 50 gt gt plot z cos z x y MarkerSize 20 gt gt hold on gt gt plot xx yy plot interpolated data gt gt hold off The result is shown in the figure below 51 MATLAB USER MANUAL e Two Dimensional Interpolation A polynomial p x y in two variables x and y interpolates a given set of values x y 2 1 lt i lt nand1 lt jsm if p x y Z fori 1 2 nand j 1 2 m Methods Four methods are available for two dimensional interpol
37. mputed solution gt gt plot t y 1 o MarkerEdgeColor r MarkerFaceColor r MATLAB USER MANUAL 0 35 1 i gt 0 4 0 45 a 0 5 ba 0 55 0 6 a 0 65 ad 0 7 5 To plot the actual values and the computed values of y type gt gt w 0 0 05 1 gt gt f 0 2 exp 2 w 4 sin w 3 cos w gt gt Plot the exact solution gt gt plot w f gt gt hold on gt gt Plot the computed solution gt gt plot t y 2 o MarkerEdgeColor t MarkerFaceColor r 25 0 5 0 5 e t Peeccccccoseoe 4 n 1 1 i i 0 0 1 0 2 03 04 0 5 06 07 08 0 9 1 61 MATLAB USER MANUAL ODE Function Summary The table below lists the MATLAB initial value problem solvers SOLVERS DESCRIPTION METHOD ode45 Nonstiff differential equations Runge Kutta ode23 Nonstiff differential equations Runge Kutta ode113 Nonstiff differential equations Adams ode15s Stiff differential equations and DAEs NDFs BDFs ode23s Stiff differential equations Rosenbtock ode23t Moderately stiff differential equations and DAEs Trapezoidal rule ode23tb Stiff differential equations TR BDF2 Partial Differential Equations ersion 6 of MATLAB provides a solver for solving certain classes of parabolic and elliptic partial differential equations In the following section examples are given to illustrate how to use the solver Description Th
38. n Flow of Control MATLAB USER MANUAL OPERATOR DESCRIPTION Addition E Subtraction X Matrix multiplication ti Entry wise multiplication jA Matrix left division Left entry wise Division Matrix right division A Right entry wise division Matrix exponentiation Entry wise exponentiation Matrix transpose Nonconjugated transpose Examples 1 1 1 1 2 Suppose that x 0 75 v 1 1 w 0 u A 3 3 4 0 0 1 3 and B 2 gt gt 2 x 5 ans 0 3000 gt gt v W ans 0 1 1000 0 gt gt x 10 v ans 10 7500 10 2500 0 7500 10 MATLAB USER MANUAL gt gt 2 A 2 ans 2 5000 3 0000 3 5000 4 0000 gt gt A u ans 1 0 gt gt A u ans 15 gt gt u u ans 3 9 gt gt u u ans gt gt u u ans 10 gt gt A B ans 1 0000 0 6667 0 4286 2 0000 gt gt A B ans 0 6316 0 0526 1 1579 0 2632 11 MATLAB USER MANUAL gt gt A B ans 15 7 31 17 gt gt A 1 2 2 B 2 2 ans 8 Operator precedence The precedence rules for MATLAB operators are summarized in the table below They are ordered from the highest Level 1 to the lowest Level 9 LEVEL OPERATOR 1 Parentheses Transpose power complex conjugate transpose matrix power Unary plus unary minus logical negation A o N Multiplication right division left division matrix multiplication matrix right
39. or the menui axes in Figure 2 2a to 0 4 and 0 8 as follows The output is shown in Figure 2 4 For online help type help axis or gt gt ezplot myFunction 0 2 pi 0 12 gt gt axis 0 4 0 8 30 MATLAB USER MANUAL Figure 2 4 Plot of a Function myFunction with Modified Axis Ranges There are three ways to create multiple plots on a single graph For online help Using the Command subplot The MATLAB function type help subplot subplot can be used to plot data into different sub or select MATLAB regions within the same graphics window The Help from Help command subplot m n i divides the graphics window menu into an m by n matrix of small sub regions and generates the next figure in the ith sub region The sub regions are numbered tow wise For example the following statements plot a set of data in four different sub regions of the graphics window in Figure 2 5 The command subplot 2 2 1 is set for plot t z to be generated in the first sub region in first row Similarly subplot 2 2 2 is set for plot t 2 q in the second sub region in the first row and so on gt gt t 0 pi 20 2 pi gt gt z cos 3 t gt gt subplot 2 2 1 gt gt plot t z gt gt subplot 2 2 2 gt gt q exp t gt gt plot t 2 q gt gt subplot 2 2 3 gt gt fplot myFunction 0 2 pi 31 MATLAB USER MANUAL gt gt subplot 2 2 4 gt gt fplot sin x cos
40. put is shown in Figure 2 2b M file myFunction m function y myFunction x y exp sqrt x sin 12 x gt gt ezplot myFunction 0 2 pi 012 Figure 2 2a Plot of a Function Using ezplot gt gt fplot myFunction 0 2 pi 0 12 xr 28 MATLAB USER MANUAL Figure 2 2b Plot of a Function Using fplot You can add a title to a graph and add labels to axes The general syntax for the title function is title string and the syntax for the xlabel and ylabel commands are xlabel string and ylabel string Moreover you can also add a text object to a graph The syntax for the command text is text x y string For example we add a title labels and a text object to Figure 2 1 The output is shown in Figure 2 3 gt gt plot x y gt gt title X Y Plot gt gt ylabel cos 2 t gt gt xlabel sin t gt gt text 0 2 0 4 A symmetry graph 29 MATLAB USER MANUAL X Y Plot 0 4 A symmetry graph cos 2 t o 1 08 06 04 02 o 02 04 06 08 1 sin 3 t Figure 2 3 x y Plot with Title and Labels After you generate a graph you can modify or change an axis range with the command axis The most basic syntax is axis bamin xmax ymin ymax xmin and xmax define the smallest and largest end points for x axis Ale similarly ymin and ymax define the smallest and largest end Help from Help points for y axis For example we can change the ranges f
41. rt 17 3205 format short e 1 7321e 001 format short g 17 321 format long 17 32050807568877 format long e 1 732050807568877e 001 format long g 17 3205080756888 format bank 17 32 format hex 4031520cd1372fea format rat 1351 78 25 MATLAB USER MANUAL COMMAND DESCRIPTION save filename Save variables load filename Restore variables cle Clear the Command Window disp Display text or array input Wait for input from the keyboard pause n Halt execution temporarily diary Save a session to a disk file format Control the output format Graphics ATLAB has extensive tools for displaying various data as graphs It also provides facilities for annotating and printing graphs In the following section some examples are presented to illustrate how a graph can be created using these tools To invoke the graphics editor type figure in the Command Window The most basic graph is a simple 2 D plot One form of the syntax for the plot command is plot x_values y values style option x_values is a vector that contains the points on the x coordinate while or select MATLAB _Yalues contains the points on the y coordinate style option is a Help from Help parameter that defines the line style the marker and the color moni used in a graph If this parameter is not entered MATLAB uses the default style Style options are summarized in the following For online help type help graph2d table 26 MATLAB USER MANUAL COLOR LINE STYLE
42. s a copy of a MATLAB session in a file and saves data files in a variety of formats In addition there are commands to control how data are displayed User Input User input can be prompted and obtained interactively during runtime The syntax for the command input is given below The value entered by a user can be any valid MATLAB expression or a character string if the second argument s is used inValues input prompt_string inValues input prompt_string s Example gt gt isQuit input Do you want to exit the current session Y N Y g J gt gt if isQuit Y isempty isQuit save quit else quit cancel end Save and Load Variables Before you exit or quit the current workspace you can use the save command to save all the variables and their current values In a new session you can use the load command to restore them For example gt gt save filename To restore the variables type gt gt load filename Note that if save and load are used without a specified file name MATLAB uses a default file name matlab mat Output to the Screen Several output functions are available Here are a few examples 23 MATLAB USER MANUAL When you type a variable name MATLAB displays the variable name and its value by default Sometimes it is desirable to display only the value For example suppose B 3 4 5 6 Then to display the value of the matrix B with column labels type gt
43. s called M files To invoke the editor type edit in the Command Window MATLAB USER MANUAL MATLAB Desktop In addition to the three basic windows above MATLAB also has a number of other windows including Command History Launch Pad Workspace and Directory Browser These windows which make up the MATLAB Desktop are opened automatically after MATLAB gets started They can be closed or reopened by clicking on the corresponding menu entry from the View menu on the desktop Command History The commands that you have previously entered in the Command Window are listed in the Command History Window You can view and run the previous commands by selecting and pasting them into the Command Window Or you can use the up arrow key Tin the Command Window to recall previous commands Launch Pad Launch Pad provides easy access to all of the MATLAB products installed in your system To view a list of all the products select Launch Pad from the View menu on the desktop To run a product double click on the selected product listed in the Launch Pad Window Workspace The data and variables created in the Command Window are stored in the system memory called the MATLAB Workspace To view the variables in the current Workspace type whe or whos in the Command Window Similarly to clear the variables type elear or clear yourvariablename The content of the Workspace Window is equivalent of the whes command Directory Browser This directory m
44. s with Different Styles Using the Command hold The third way to create multiple plots in the same graphics window is to use the command hold hold on freezes the current plot in a graphics window and allows subsequent plots to be generated in the same window An example is shown below and the output is displayed in Figure 2 7 gt gt t 0 0 01 2 pi gt gt plot sin t 33 MATLAB USER MANUAL gt gt hold on gt gt plot cos t gt gt hold off 0 8 0 6 0 4 0 2 0 2 0 4 0 6 0 8 0 100 200 300 400 500 600 700 Figure 2 7 Generating Multiple Plots Using hold For online help To print a hardcopy of a graph the simplest way is to select Print type help print or from the File menu in a graphics window or alternatively type type help saveas the print command directly in the Command Window Similarly select MATLAB Help to save a graph into a file select Save from the File menu or from Help menu enter the print command along with a file name in the Command Window The basic syntax of the print command is defined as follows print ddevicetype options filename For example the following statement will save the current graph into a file named as mygraph eps gt gt print deps mygraph eps You can export a graph with a specified format using the command saveas For example the command below saves the current graph in the jpg format gt gt saveas gcf myGraph jpg 34 MATL
45. se find Find indices and values of nonzero entries spalloc Allocate space for sparse matrix sprank Structure rank speys Sparse identity matrix svds A few singular values eigs A few eigenvalues choline Incomplete Cholesky factorization luinc Incomplete LU factorization bicg Biconjugate gradient iterative linear equation solution bicstab Biconjugate gradient stabilized iterative linear equation solution cgs Conjugate gradient squared iterative linear equation solution gmres Generalized minimum residual iterative linear equation solution minres Minimum residual iterative linear equation solution peg Preconditioned conjugate gradient iterative linear equation solution qmr Quasi minimal residual iterative linear equation solution Two classes of methods can be used to solve systems of simultaneous linear equations direct methods and iterative methods Direct methods are more efficient for small linear systems however they may be very costly in terms of storage and computational time for large sparse linear systems If convergent iterative methods compute an approximate solution to a linear system and this may be much more efficient than using a direct method In this section we describe how to solve a linear system using MATLAB functions based on iterative methods Description The functions in MATLAB are intended to solve Ax b or min b Ax A linear system is usually replaced by an equivalent system M Ax Mb where M is a pre
46. se A I 2 3 4 5 6 7 8 Ol 48 MATLAB USER MANUAL gt gt p poly A p 1 0000 6 0000 72 0000 27 0000 The roots of this characteristic polynomial are the eigenvalues of A gt gt roots p ans 12 1229 5 7345 0 3884 e Polynomial Evaluation To evaluate a polynomial at a specified point use the command polyval p x This function returns the value of the given polynomial p at the point x Suppose p x x 1 gt gt p 1 0 1 gt gt polyval p 2 ans 3 e Data Fitting The function polyfit x y n determines the polynomial p x of degree of n that best fits the given data x y 1 lt i lt n in the least squares sense That is p x y for i 1 2 n For example gt gt x 1 0 2 2 x 1 0000 1 2000 1 4000 1 6000 1 8000 2 0000 SSeS 21 7 13428 tai 1 y 2 0000 1 7000 1 3000 1 2800 1 1100 1 0000 gt gt p polyfit x y 3 p 0 9144 4 9494 9 4616 7 4432 To obtain a plot of the best least squares polynomial approximation of degree 3 to the data points enter the following gt gt plot X Y ija X polyval p x lt 49 MATLAB USER MANUAL N e Other Useful Functions The table below lists some useful polynomial functions COMMAND DESCRIPTION conv Polynomial multiplication deconv Polynomial division polyder Polynomial derivative polyvalm Matrix polynomial evaluation residue Partial fraction expansion e One Dimensional Interpolation A polyno
47. sparse matrix use the command sparse i j s m n where i and j are the vectors that contain row and column indices for the nonzero entries of the matrix s is a vector that contains a list of nonzero values whose indices are defined by the corresponding i j pairs m is the row dimension of the sparse matrix and similarly n is the column dimension To create a sparse matrix B of the above matrix A for example enter the following gt gt B sparse i j s 4 4 1 1 3 2 3 3 NW UTR rR Note that the resulting matrix above is the same as the one obtained using sparse A 44 MATLAB USER MANUAL View Sparse Matrices There are a few useful commands to compute additional information about a sparse matrix For example to find the number of nonzero entries in the above sparse matrix B use the command nnz B gt gt nnz B ans 5 To obtain the list of nonzero entties of B use the command nonzeros B gt gt nonzeros B ans 1 1 5 3 2 To view the distribution of the nonzero entries of B use the command spy B gt gt spy B 2 5 3 5 45 45 MATLAB USER MANUAL Sparse Matrix Functions There are numerous sparse matrix functions in MATLAB e g for the solution of simultaneous linear equations and for factorizations such as LU QR and Cholesky The table below lists a set of commonly used sparse matrix functions COMMAND DESCRIPTION isspars True if matrix is spar
48. ted Syntax switch expression case test_expression1 statements case test_expression2 statements otherwise statements end Example gt gt x input Enter a number gt gt switch x case 0 y 0 case 1 y xt2 otherwise yal end for Statement The for loop repeatedly executes a group of statements a fixed and predetermined number of times Syntax for variable expression statements end 16 MATLAB USER MANUAL Example gt gt forn 1 4 x n n 10 pi end gt gt x x 0 3142 0 6283 0 9425 1 2566 while Loop Statement The while loop allows a group of statements to be repeatedly executed as long as the evaluated expression is true Syntax while expression statements end Example gt gt p 1 u 1 while p lt 16 u u p end continue and break Statements The continue statement causes execution of a for or while loop to jump immediately to the next iteration of the loop and it skips any remaining statements in the loop In contrast to the continue statement the break statement terminates the execution of the loop Syntax while expression statements continue statements end 17 MATLAB USER MANUAL for variable expression statements continue statements end while expression statements break statements end for variable expression statements break statements end Example gt gt m 1 n 0 gt
49. ver and your user name in the popup window as illustrated below Then click on the Connect button Connect to Remote Host x m Host Name shellesc uvic ca User Name yourlogin_namel Guan Port Number 2 OoOO Authentication Method Password MATLAB USER MANUAL c When a popup window appears for Host Identification just click on the button No d Type your password when the last popup window appears Note After these steps a command line prompt in the remote server should appear in the SSH Client window For example mayne 3 Determine the Name of Your Computer At the prompt in the SSH Client window type who ami This command will give you a result back similar to the line below username termid date hostname 4 Set Environment Variable for the Output Display Simply type the UNIX command below setenv DISPLAY hostname 0 For example setenv DISPLAY boxter 0 5 Start MATLAB Type the command below matlab Quitting MATLAB elect Exit MATLAB from File on the menu bar to exit MATLAB Alternatively type exit or quit in the Command Window to quit MATLAB To quit MATLAB on SHELL from the NT 2000 workstations in ELW B228 or B203 do as follows 1 Quitting MATLAB In the MATLAB Command Window type exit or quit 2 Logout from SHELL In the SSH Client window type exit 3 Quitting SSH Client Session Click on File on the menu bar at the top of the SSH widow and then select Exit 4 Quittin
Download Pdf Manuals
Related Search
Related Contents
Asahi Pentax P-3N Instruction Manual 20 pages-3 (Page A) - Agence de l`Eau Seine Normandie Mode d`emploi : afficheur de données CLIMATSCOPE サービス情報 HS RiGHTPEOPLE User Manual Incipio DualPro ARIENS SNOW ENGINE EnGenius EUB-9701 Wireless-N (Draft 802.11n) USB Adapter Copyright © All rights reserved.
Failed to retrieve file