Home
UVIC CSC MATLAB Manual - Department of Computer Science
Contents
1. 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 computed solution gt gt plot t y 1 o MarkerEdgeColor r MarkerFaceColor r 58 MATLAB USER MANUAL 0 35 7 1 i 0 4 0 45 a 0 5 ba 0 55 0 6 a 0 65 d 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 2 5 0 5 0 5 oer Peeccccccoeeoe 59 MATLAB USER MANUAL e 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
2. 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 The class of parabolic and elliptic partial differential equations that MATLAB can solve is of the form Ou u OT n Ou Ou c x t u x x f x t u 5 x t u Ox j Ot Ox Ox Ox where to St lt t aS 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 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 saans xnu 0 Ox 60 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 icfun evaluates the initial conditions bcfun evaluates the terms p and g 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 fy and f Example The example below illustrates the steps to solve a given parabolic partial differential equation problem Consider the heat equation GH 2H oy 1 0 O0
3. 38 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 38 38 40 41 42 44 46 46 48 54 54 56 56 60 64 64 64 67 MATLAB USER MANUAL Chapter Accessing and Quitting MATLAB Accessing MATLAB M access to SHELL for example in ECS 242 Starting MATLAB ona Windows Desktop 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 Programs MATLAB 7 0 4 When MATLAB opens there are 3 windows two on the left Current Directory and Command History and one larger one on the right Command Window Click inside the top left window the Current Directory so that it is selected You must change the current directory to be C students instead of the one it defaults to when MATLAB starts up Thus when you save M files to the C students directory MATLAB can find them To do this click repeatedly on the yellow file folder icon with the up arrow the leftmost icon until it grays out Then scroll down and double click the studen
4. 49 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 Z 1 lt i lt mand1 lt jsm if p x yj z fori 1 2 nand j 1 2 m Methods Four methods are available for two dimensional interpolation 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 gt 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 50 MATLAB USER MANUAL Enter the command surf XX YY ZZ to generate a plot of the interpolated data e Spline Function The spline function can be used to do cubic spline interpolation Thi
5. w 2 3 6 1 V 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 0000i 1 0000 1 0000 1 00001 2 0000 2 0000 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 m n 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 9630 gt gt y 5 2 0 y l gt gt x 0 2 5 x 02 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 c
6. be factored as A R R where R is an upper triangular matrix The function chol A in MATLAB is used to compute the Cholesky factor for a matrix A For example PP A 111 123 136 A 1 11 1 2 3 13 6 gt gt R chol A R 1 1 1 0 1 2 0 0 1 gt gt R R ans 1 1 1 1 2 3 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 Suppose A f 0 1 2 2 3 0 1 3 39 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 O 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 p 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
7. lt x lt l t gt 0 a ae i l gt with boundary conditions u 0 t ul t 0 t gt 0 and initial conditions u x 0 sin zx O lt x lt l 1 Rewrite the PDE in the required form Ou ae fa a 9 Ot Ox Ox Given the form above m 0 and meS c x t u 1 Ox 61 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 c 1 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 u 0 t 0 24 0 1 0 at x 0 Ox u l t 0 4 1 0 at x 1 X Write the function that represents the boundary conditions M 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 62 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 W pdeHeatic pdeHeatbe 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
8. 4 0 6 4 0 8 Figure 2 6a Generating Multiple Plots Using a Matrix a e S a 22 ost oel oat 02 o 02 0 4 06 os 4 van a a oC A oS A4 ae ee aL 0 1 2 3 4 5 6 7 Figure 2 6b Multiple Plots 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 cutrent 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 J gt gt plot sin t 31 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 4 0 6 0 8 L So ae a is _ 0 100 200 300 400 500 600 700 Figure 2 7 Generating Multiple Plots Using hold For online help To ptint 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 d devicetype options filename For example the following statement will save the current graph into a file named as my
9. A V 1 ans 4 7472 8 8666 1 1429 40 MATLAB USER MANUAL gt gt D 1 1 V 51 ans 4 7472 8 8666 1 1429 Singular Values of a Matrix If A is an m x n matrix with rank r then there exist real 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 Liss 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 I 2 2 0 2 gt gt U D V svd A U 0 4472 0 8944 0 8944 0 4472 ow l N O eoe VS 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 41 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 whos Suppose A 1 00 0 00 0 2 ip A nd B spar TEF a sparse 0 030 gt gt whos Name Size Bytes Class A 4
10. Example 13 MATLAB USER MANUAL gt gt ifx gt 10 z elseify gt 0 z else Z end e switch and case Statements The switch statement evaluates an expression and then executes a group of statements under the first matching case statement If no matching case statement is found then the statements under the optional otherwise statement are executed Syntax switch expression case test_expression1l 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 y 10 end e for Statement The for loop repeatedly executes a group of statements a fixed and predetermined number of times Syntax for variable expression statements end 14 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 e 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 th
11. 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 ax Run the following 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 63 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 64 MATLAB USER MANUAL e Maximum and Minimum Entries of an Array The functions max and min return the largest and th
12. Other Useful Functions The table below lists some useful polynomial functions COMMAND DESCRIPTION conv Polynomial multiplication decony Polynomial division polyder Polynomial derivative polyvalm Matrix polynomial evaluation residue Partial fraction expansion e One Dimensional Interpolation A polynomial p x in one variable x interpolates a given set of values x y 1S in if p x y fori 2rth Methods There ate six methods available for one dimensional interpolation The default interpolation method is linear 48 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 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
13. 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 Table of Contents CHAPTER 1 Accessing and Quitting MATLAB Accessing MATLAB 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 Precedence Rules for Operators Character Strings Variables Declaration Global Variables Flow of Control Relational and Logical Operators Control Statements N N FF Be aoan aoa A 10 10 11 11 12 12 12 13 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 Determinants 16 16 20 20 21 21 23 23 24 26 24 26 27 28 29 32 33 34 34 35 37
14. am in this window For example to create a vector e with two elements type gt gt e 1 0 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 programs 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 Launc
15. an be used to select all of the row or column indices For example gt gt A 123 456789 A 1 2 3 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 3 gt gt D A 1 2 D 12 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 section Flow of Control MATLAB USER MANUAL OPERATOR DESCRIPTION Addition Subtraction X Matrix multiplication ti Entry wise multiplication 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 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 1 3 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 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 preced
16. bug 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 20 MATLAB USER MANUAL Input Output and Data Formatting ATLAB allows user input during runtime saves 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
17. coordinate style option is a Help from Help parameter that defines the line style the marker and the color men 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 24 MATLAB USER MANUAL LINE STYLE COLOR y Yellow m magenta c Cyan r Red Green none Blue w White Black Solid Dashed Dotted Dash dot No line MARKER o Circle x Asterisk Point Plus x Cross s Square d Diamond 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 04 06 Figure 2 1 x y Plot 25 MATLAB USER MANUAL MATLAB provides commands ezplot and fplot for plotting mathematical functions The syntaxes for the commands ate 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 myFunction m and then use the command ezp
18. e execution of the loop Syntax while expression statements continue statements end 15 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 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 ile 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 16 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 polyno
19. e 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 Sum 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 57 9 O 4 1 gt gt sum A ans 6 13 13 gt gt cumsum A ans le Der 3 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 65 MATLAB USER MANUAL gt gt A 123 579 041 A 12 3 57 9 O 4 1 gt gt prod A ans 0 56 27 gt gt cumprod A ans Pe 2 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 2 58 16 103 675 G 2 5 8 1 6 10 3 6 5 gt gt diff C ans a ae 2 2 0 FD 66 MATLAB USER MANUAL References 1 Desmond J Higham and Nicholas J Higham MATLAB Guide Society for Industrial and Applied Mathematics Phi
20. ed 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 MtAx R 7 Ax R 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 45 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 gt gt y A yx The entries of the vector y should all be equal to 1 Polynomial Roots and Interpolation l 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 roots p In the case of the above polynomial the roots are ca
21. ence 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 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 10 MATLAB USER MANUAL COMMAND char blanks n deblank s eval findstr s1 s2 int2str n ischar s isletter s lower mat2str num2str stremp s1 s2 strcmpi s1 s2 strncmp s1 s2 n strncmpi s1 s2 n strcat strvcat upper s Variables DESCRIPTION Create character array A string of n blanks Strip trailing blan
22. graph 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 32 MATLAB 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 33 MATLAB USER MANUAL Chapter 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 ate scalars are measures of the size of vectors and matrices P norm of a Vector T
23. 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 MarkerEdgeColor r 52 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 O 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 53 MATLAB USER MANUAL Quadrature M ATLAB provides a set of functions for evaluating definite integral
24. h 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 who or whos in the Command Window Similarly to clear the variables type clear or clear yourvariablename The content of the Workspace Window is equivalent of the whos command Directory Browser This directory management 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 A 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 gt gt x 0 75 x 0 7500 gt gt y 3 4i 3 0000 4 00001 Definition A vector is a special case of a matrix with one row or one column For example 1 0000 1 1000 0 gt gt
25. he p norm of a vector x is l p frl lt p lt P Xx l kl p n 2 i l 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 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 34 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 X ETT n l max tf gt gt norm x inf ans 8 P norm of a Matrix The p norm of a matrix A is Ax Al max 4 P x20 P The maximum column sum matrix norm p 1 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 ajj gt 1 isj lt n jay n A max gt la and isisn j A max vA Ais an eigenvalueof A A Suppose matrix A 1 2 5 4 To use the function norm A p to compute these mattix norms t
26. ion is In 2 0 69314718055995 Summary of Quadrature Functions The table below lists the quadrature functions in MATLAB 55 MATLAB USER MANUAL SOLVERS DESCRIPTION METHOD quad Adaptive Simpson quadrature Simpson quadrature quad1 Adaptive Lobatto quadrature Lobatto quadrature 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 subjectto y to Yo where f 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 Example1 Solve the initial value problem y y t l1 O lt t lt 2 yO 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 56 MATLAB USER MANUAL dy y t t 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 prob
27. ks 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 Convert string to lower case Convert a matrix into a string Convert numbers to a string Compare strings Compare strings ignoring case Compare the first n characters of two strings Compare the first n characters of two strings ignoring case String concatenation Vertical concatenation of strings 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 variable 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 11 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 variable You must declare the variable as global at the beginning of every function that requires acce
28. ladelphia 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 tutorial 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 67 68
29. lculated 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 ri 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 Suppose A l 2 3 4 5 6 7 8 Ol 46 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 Soy O47 13428 tat T yr 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 47 MATLAB USER MANUAL n e
30. lem 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 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 O lt x lt 1 y 0 04 y 0 0 6 1 Rewrite the problem as a first order system 57 MATLAB USER MANUAL Set y y and y y and rewrite the second order equation as a system of two first order equations Yi Y2 y e sint 2y 2y y 0 04 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 yl y2 y2 exp 2t sin t 2y2 2y1 y10 0 4 y2 0 0 6 dy y exp t sin 2 y 2 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
31. lot 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 xr Note that xr means a dotted red line with cross markers is used in the plot The output 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 0 12 Figure 2 2a Plot of a Function Using ezplot gt gt fplot myFunction 0 2 pi 0 12 xr 26 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 3 t gt gt text 0 2 0 4 A symmetry graph 27 MATLAB USER MANUAL cos 2 t o 1 0 8 0 6 X Y Plot A symmetry graph 04 02 o o2 04 o6 08 1 sin 3 t Figure 2 3 x y Plot with Title and Labels ma m Al em mmanqs F
32. mial det AI A 3 Compute the roots of this polynomial eigenvalues of matrix A A 123 456 780 ie eee ey rt 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 only 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 M file EigValues m 17 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 c
33. n 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 pe on the command line For example p The following table illustrates the additional format types supported by MATLAB FORMAT EXAMPLES format short 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 23 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 Y_Values contains the points on the y
34. oefficients 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 1 235456780 C a A e 2 5 8 O o w gt gt eig coef EigValues C eig 12 1229 5 7345 0 3884 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 M 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 18 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 e 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 M file BigT
35. or online help type help axis or select MATLAB Help from Help menu rCnntrallinn tha Avac r CONTSO line J tne Axes After you generate a graph you can modify or change an axis range with the command axis The most basic syntax is axis xmin xmax ymin ymax xmin and xmax define the smallest and largest end points for x axis similarly ymin and ymax define the smallest and largest end points for y axis For example we can change the ranges for the axes in Figure 2 2a to 0 4 and 0 8 as follows The output is shown in Figure 2 4 gt gt ezplot myFunction 0 2 pi 0 12 gt gt axis 0 4 0 8 28 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 fo
36. ous 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 find spalloc sprank speys svds eigs choline luinc bicg bicstab cgs gmres minres pcg qmr 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 True if matrix is sparse Find indices and values of nonzero entries Allocate space for sparse matrix Structure rank Sparse identity matrix A few singular values A few eigenvalues Incomplete Cholesky factorization Incomplete LU factorization Biconjugate gradient iterative linear equation solution Biconjugate gradient stabilized iterative linear equation solution Conjugate gradient squared iterative linear equation solution Generalized minimum residual iterative linear equation solution Minimum residual iterative linear equation solution Preconditioned conjugate gradient iterative linea
37. output functions are available Here are a few examples 21 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 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 ut3 e 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 22 MATLAB USER MANUAL For online help type help format or select MATLAB Hel from Help menu gt gt format long MATLAB stores numbers to a relative precisio
38. plex 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 37 MATLAB USER MANUAL gt gt A ans 1 0000 1 00001 3 0000 2 0000 1 00001 0 2 00001 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 Zed 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 1 2 38 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 3 2 4 gt gt L U P lu A L 1 0000 0 0 5000 1 0000 U 2 4 0 1 38 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
39. r equation solution Quasi minimal residual iterative linear equation solution MATLAB functions based on iterative methods e Description The functions in MATLAB are intended to solve Ax b or A linear system is usually replaced by an equivalent system M Ax Mtb where M is a preconditioner that is chosen to make computation of the solution more efficient The goal is to find a simple matrix M so that M7Ax is near to the identity matrix The table below lists a min b Ax set of MATLAB functions corresponding to iterative methods 44 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 tol 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 generaliz
40. r 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 29 MATLAB USER MANUAL gt gt subplot 2 2 4 gt gt fplot sin x cos 2 x 1 1 x 0 5 pi 1 5 1 5 0 5 0 5 05 i j J e 0 z 6 8 o 2 4 6 8 i 15 M AANA i of Hy AN eo AA MEET VEY A AN l 1 a V VY F A i j Y Y U l J y sal 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 o plots replace plot x Y with for example plot x Y 1 xY 2 x Y 3 The result is shown in Figure 2 6b 30 MATLAB USER MANUAL 08 4 06 0 4 0 2 4 0
41. race 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 calls 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 19 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 SupposeA 1 2 3 4 5 6 7 8 OlandB 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 de
42. s In the following section examples are given to illustrate the basic usage of these functions Description The numerical approximation of the definite integral i ix dx is called quadrature The basic syntax of the MATLAB quadrature functions is q quad fun a b where fun is the function to be integrated a and b specify the interval of integration e Examplel 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 mylntegral m function y mylntegral x Example for Quadrature el Bey A A he 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 54 MATLAB USER MANUAL gt gt b linspace 0 1 1 5 15 gt gt plot b Int Example2 Another quadrature function in MATLAB is trapz x y This function computes a numerical approximation of the definite integral f x dx by applying the trapezoidal rule Consider the example below 2d Suppose F x a An approximation of this integral using trapz 1 Xx can be obtained as follows gt gt format long gt gt x linspace 1 2 50 Soy 1 gt gt area trapz x y area 0 69317321002551 Note that the exact solut
43. s 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 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 51 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 lee 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
44. ss to it Similarly you must declare it as global 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 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 oe Not Examples 12 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 2 34 lt 1 5 6 2 ans 1 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 aeei 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 expressionl statements elseif expression2 statements else statements end
45. ts folder This will change the default directory to C students ATLAB is available on both MS Windows and UNIX platforms in the Department of Computer Science The MS Windows version can be accessed from the PCs located for example in ECS 250 258 or 266 The UNIX version can be accessed from any UNIX workstation that allows MATLAB USER MANUAL 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 Some Useful Help Commands COMMAND help helpwin help sopic quit version type filename what more DESCRIPTION List all help topics in the Command Window List all help topics in the Help Window Give help on the specified topic Terminate MATLAB Version of MATLAB Display the contents of the specified file List MATLAB specific files in the current directory Control paged output for the Command Window MATLAB USER MANUAL Chapter 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 MATLA D VAhAAR Ure D WINGOWS 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 progr
46. x4 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 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 i 1233 gt gt j 1423 gt gt s 1215 gt gt B sparse i j S 4 B 1 1 G 2 6 3 4 3 2 4 NW UTR rR Note that the resulting matrix above is the same as the one obtained using sparse A 42 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 entries 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 43 MATLAB USER MANUAL Sparse Matrix Functions There are numer
47. ype 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 ata AA 1 where I is the identity matrix The 35 MATLAB USER MANUAL function inv A is used to compute the inverse of a square matrix A For example gt gt A 1 2 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 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 3 5 7 9 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 36 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 gt gt A 12 3 4 Conjugate Transpose of a Complex Matrix In addition to interchanging the rows and columns the conjugate transpose of a com
Download Pdf Manuals
Related Search
Related Contents
X 6 4 0 - C o m p a c t T h e rm a l Im a g e r Korenix JetPort Commander Manual de utilização - SMA Solar Technology AG "user manual" Sony CD Player CDP-XE270B CAPITULO 2 - Repositorio Digital ESPE Samsung 24" SyncMaster SA650D Bruksanvisning Title 大腸菌におけるGC-CG transversion型突然変異の抑制機構 の Emploi - Quelnet Fabrication et mode d`emploi du Lunoscope Après avoir collé la Copyright © All rights reserved.
Failed to retrieve file