MATLAB BASICS

MATLAB BASICS
GregDeamons Profile Pic
GregDeamons,New Zealand,Professional
Published Date:03-08-2017
Your Website URL(Optional)
Comment
Chapter2 MATLAB BASICS    This Chapter is a brief introduction to MATLAB (an abbreviation of MATrix LABoratory) basics, registered trademark of computer software, version 4.0 or later developed by the Math Works Inc. The software is widely used in many of science and engineering fields. MATLAB is an interactive program for numerical computation and data visualization. MATLAB is sup- ported on Unix, Macintosh, and Windows environments. For more information on MATLAB, contact The MathWorks.Com. A Windows version of MATLAB is assumed here. The syntax is very similar for the DOS version. MATLAB integrates mathematical computing, visualization, and a powerful language to provide a flexible environment for technical computing. The open architecture makes it easy to use MATLAB and its companion products to explore data, create algorithms, and create custom tools that provide early insights and competitive advantages. Known for its highly optimized matrix and vector calculations, MATLAB offers an intui- tive language for expressing problems and their solutions both mathematically and visually. Typical uses include: • Numeric computation and algorithm development  Symbolic computation (with the built-in Symbolic Math functions)  Modeling, simulation, and prototyping  Data analysis and signal processing  Engineering graphics and scientific visualization In this chapter, we will introduce the MATLAB environment. We will learn how to cre- ate, edit, save, run, and debug m-files (ASCII files with series of MATLAB statements). We will see how to create arrays (matrices and vectors), and explore the built-in MATLAB linear alge- bra functions for matrix and vector multiplication, dot and cross products, transpose, determi- nants, and inverses, and for the solution of linear equations. MATLAB is based on the language C, but is generally much easier to use. We will also see how to program logic constructs and loops in MATLAB, how to use subprograms and functions, how to use comments (%) for ex- plaining the programs and tabs for easy readability, and how to print and plot graphics both two and three dimensional. MATLAB’s functions for symbolic mathematics are presented. Use of these functions to perform symbolic operations, to develop closed form expressions for solu- tions to algebraic equations, ordinary differential equations, and system of equations was pre- sented. Symbolic mathematics can also be used to determine analytical expressions for the derivative and integral of an expression. 26MATLAB BASICS 27 2.1.1 Starting and Quitting MATLAB To start MATLAB click on the MATLAB icon or type in MATLAB, followed by pressing the enter or return key at the system prompt. The screen will produce the MATLAB prompt (or EDU ), which indicates that MATLAB is waiting for a command to be entered. In order to quit MATLAB, type quit or exit after the prompt, followed by pressing the enter or return key. 2.1.2 Display Windows MATLAB has three display windows. They are 1. A Command Window which is used to enter commands and data to display plots and graphs. 2. A Graphics Window which is used to display plots and graphs 3. An Edit Window which is used to create and modify M-files. M-files are files that contain a program or script of MATLAB commands. 2.1.3 Entering Commands Every command has to be followed by a carriage return cr (enter key) in order that the command can be executed. MATLAB commands are case sensitive and lower case letters are used throughout. To execute an M-file (such as Project_1.m), simply enter the name of the file without its extension (as in Project_1). 2.1.4 MATLAB Expo In order to see some of the MATLAB capabilities, enter the demo command. This will initiate the MATLAB EXPO. MATLAB Expo is a graphical demonstration environment that shows some of the different types of operations which can be conducted with MATLAB. 2.1.5 Abort In order to abort a command in MATLAB, hold down the control key and press c to generate a local abort with MATLAB. 2.1.6 The Semicolon (;) If a semicolon (;) is typed at the end of a command the output of the command is not displayed. 2.1.7 Typing % When percent symbol (%) is typed in the beginning of a line, the line is designated as a comment. When the enter key is pressed the line is not executed. 2.1.8 The clc Command Typing clc command and pressing enter cleans the command window. Once the clc com- mand is executed a clear window is displayed. 2.1.9 Help MATLAB has a host of built-in functions. For a complete list, refer to MATLAB user’s guide or refer to the on line Help. To obtain help on a particular topic in the list, e.g., inverse, type help inv.28 ANALYSIS AND DESIGN OF CONTROL SYSTEMS USING MATLAB 2.1.10 Statements and Variables Statements have the form variable = expression The equals (“=”) sign implies the assignment of the expression to the variable. For in- stance, to enter a 2 × 2 matrix with a variable name A, we write A == 1 2 ; 3 4 ret The statement is executed after the carriage return (or enter) key is pressed to display A = 12 34      The symbols for arithmetic operations with scalars are summarized below in Table 2.1. Table 2.1 Arithmetic operation Symbol Example Addition + 6 + 3 = 9 Subtraction – 6 – 3 = 3 Multiplication 6 3 = 18 Right division / 6 / 3 = 2 Left division \ 6 \ 3 = 3 / 6 = 1 / 2 3 Exponentiation 6 3 (6 = 216)     MATLAB has several different screen output formats for displaying numbers. These formats can be found by typing the help command: help format in the Command Window. A few of these formats are shown in Table 2.2 for 2π. Table 2.2 Display formats Command Description Example Format short Fixed-point with 351/7 4 decimal digits ans = 50.1429 Format long Fixed-point with 351/7 14 decimal digits ans = 50.14285714285715 Format short e Scientific notation with 351/7 4 decimal digits ans = 5.0143e+001 Format long e Scientific notation with 15 351/7 decimal digits ans = 5.014285714285715e001MATLAB BASICS 29 Command Description Example Format short g Best of 5 digit fixed 351/7 or floating point ans = 50.143 Format long g Best of 15 digit fixed 351/7 or floating point ans = 50.1428571428571 Format bank Two decimal digits 351/7 ans = 50.14 Format compact Eliminates empty lines to allow more lines with information displayed on the screen Format loose Adds empty lines (opposite of compact)         MATLAB contains a number of functions for performing computations which require the use of logarithms, elementary math functions, and trigonometric math functions. List of these commonly used elementary MATLAB mathematical built-in functions are given in Tables 2.3 to 2.8. Table 2.3 Common Math Functions Function Description abs(x) Computes the absolute value of x. sqrt(x) Computes the square root of x. round(x) Rounds x to the nearest integer. fix(x) Rounds (or truncates) x to the nearest integer toward 0. floor(x) Rounds x to the nearest integer toward – ∞. ceil(x) Rounds x to the nearest integer toward ∞. sign(x) Returns a value of – 1 if x is less than 0, a value of 0 if x equals 0, and a value of 1 otherwise. rem(x,y) Returns the remainder of x/y. for example, rem(25, 4) is 1, and rem(100, 21) is 16. This function is also called a modulus function. x exp(x) Computes e , where e is the base for natural logarithms, or approxi- mately 2.718282. log(x) Computes ln x, the natural logarithm of x to the base e. log10(x) Computes log x, the common logarithm of x to the base 10. 10 Table 2.4 Exponential functions Function Description x exp(x) Exponential (e ) log(x) Natural logarithm log10(x) Base 10 logarithm sqrt(x) Square root30 ANALYSIS AND DESIGN OF CONTROL SYSTEMS USING MATLAB Table 2.5 Trigonometric and hyperbolic functions Function Description sin(x) Computes the sine of x, where x is in radians. cos(x) Computes the cosine of x, where x is in radians. tan(x) Computes the tangent of x, where x is in radians. asin(x) Computes the arcsine or inverse sine of x, where x must be between – 1 and 1. The function returns an angle in radians between – π/2 and π/2. acos(x) Computes the arccosine or inverse cosine of x, where x must be between – 1 and 1. The function returns an angle in radians between 0 and π. atan(x) Computes the arctangent or inverse tangent of x. The function returns an angle in radians between – π/2 and π/2. atan2(y, x) Computes the arctangent or inverse tangent of the value y/x. The function returns an angle in radians that will be between – π and π, depending on the signs of x and y. xx − ee − sinh(x) Computes the hyperbolic sine of x, which is equal to . 2 xx − ee + cosh(x) Computes the hyperbolic cosine of x, which is equal to . 2 sinh x tanh(x) Computes the hyperbolic tangent of x, which is equal to . cosh x 2 asinh(x) Computes the inverse hyperbolic sine of x, which is equal to ln(x + x + 1 ). 2 acosh(x) Computes the inverse hyperbolic cosine of x, which is equal to ln(x + x − 1 ). 1 x + atanh(x) Computes the inverse hyperbolic tangent of x, which is equal to ln 1 − x for x ≤ 1. Table 2.6 Round-off functions Function Description Example round(x) Round to the nearest integer round(20/6) ans = 3 fix(x) Round towards zero fix(13/6) ans = 2 ceil(x) Round towards infinity ceil(13/5) ans = 3 floor(x) Round towards minus infinity floor(– 10/4) ans = – 3 rem(x, y) Returns the remainder after rem(14,3) ans = 2 x is divided by y sign(x, y) Signum function. Returns 1 sign(7) ans = 1 if x 0, – 1 if x 0, and 0 if x – 0.MATLAB BASICS 31 Table 2.7 Complex number functions Function Description conj(x) Computes the complex conjugate of the complex number x. Thus, if x is equal to a + i b, then conj(x) will be equal to a – i b. real(x) Computes the real portion of the complex number x. imag(x) Computes the imaginary portion of the complex number x. abs(x) Computes the absolute value of magnitude of the complex number x. angle(x) Computes the angle using the value of atan2(imag(x), real(x)); thus, the angle value is between – π and π. Table 2.8 Arithmetic operations with complex numbers Operation Result c + c (a + a ) + i(b + b ) 1 2 1 2 1 2 c + c (a – a ) + i(b – b ) 1 2 1 2 1 2 c  c (a a – b b ) + i(a b – a b ) 1 2 1 2 1 2 1 2 2 1 c  1 aa +bb ab −b a 12 1 2 21 2 1 + i  c  22  22 2 ab + ab +  22  22 22 ab + c (magnitude or absolute value of c ) 1 11 1 c a – ib (conjugate of c ) 1 1 1 1 (Assume that c = a + ib and c = a + ib ) 1 1 1 2 2 2      A variable is a name made of a letter or a combination of several letters and digits. Variable names can be up to 63 (in MATLAB 7) characters long (31 characters on MATLAB 6.0). MATLAB is case sensitive. For instance, XX, Xx, xX, and xx are the names of four different variables. It should be noted here that not to use the names of a built-in functions for a variable. For instance, avoid using: sin, cos, exp, sqrt, ..., etc. Once a function name is used to define a variable, the function cannot be used.        MATLAB includes a number of predefined variables. Some of the predefined variables that are available to use in MATLAB programs are summarized in Table 2.9.32 ANALYSIS AND DESIGN OF CONTROL SYSTEMS USING MATLAB Table 2.9 Predefined variables Predefined variable Description in MATLAB ans Represents a value computed by an expression but not stored in variable name. pi Represents the number π. eps Represents the floating-point precision for the computer being used. This is the smallest difference between two numbers. inf Represents infinity which for instance occurs as a result of a divi- sion by zero. A warning message will be displayed or the value will be printed as ∞. i Defined as , which is: 0 + 1.0000i. − 1 j Same as i. NaN Stands for Not a Number. Typically occurs as a result of an ex- pression being undefined, as in the case of division of zero by zero. clock Represents the current time in a six-element row vector contain- ing year, month, day, hour, minute, and seconds. date Represents the current date in a character string format.          Table 2.10 lists commands that can be used to eliminate variables or to obtain informa- tion about variables that have been created. The procedure is to enter the command in the Command Window and the Enter key is to be pressed. Table 2.10 Commands for managing variables Command Description clear Removes all variables from the memory. clear x, y, z Clears/removes only variables x, y, and z from the memory. who Lists the variables currently in the workspace. whos Displays a list of the variables currently in the memory and their size together with information about their bytes and class.       In Tables 2.11 to 2.15 the useful general commands on on-line help, workspace informa- tion, directory information, and general information are given.MATLAB BASICS 33 Table 2.11 On-line help Function Description help Lists topics on which help is available. helpwin Opens the interactive help window. helpdesk Opens the web browser based help facility. help topic Provides help on topic. lookfor string Lists help topics containing string. demo Runs the demo program. Table 2.12 Workspace information Function Description who Lists variables currently in the workspace. whos Lists variables currently in the workspace with their size. what Lists m-, mat-, and mex-files on the disk. clear Clears the workspace, all variables are removed. clear x y z Clears only variables x, y, and z. clear all Clears all variables and functions from workspace. mlock fun Locks function fun so that clear cannot remove it. munlock fun Unlocks function fun so that clear can remove it. clc Clears command window, command history is lost. home Same as clc. clf Clears figure window. Table 2.13 Directory information Function Description pwd Shows the current working directory. cd Changes the current working directory. dir Lists contents of the current directory. ls Lists contents of the current directory, same as dir. path Gets or sets MATLAB search path. editpath Modifies MATLAB search path. copyfile Copies a file. mkdir Creates a directory. Table 2.14 General information Function Description computer Tells you the computer type you are using. clock Gives you wall clock time and date as a vector. date Tells you the date as a string. more Controls the paged output according to the screen size. ver Gives the license and the version information about MATLAB installed on your computer. bench Benchmarks your computer on running MATLAB compared to other com- puters.34 ANALYSIS AND DESIGN OF CONTROL SYSTEMS USING MATLAB Table 2.15 Termination Function Description c (Control-c) Local abort, kills the current command execution. quit Quits MATLAB. exit Same as quit.   An array is a list of numbers arranged in rows and/or columns. A one-dimensional array is a row or a column of numbers and a two-dimensional array has a set of numbers arranged in rows and columns. An array operation is performed element-by-element. 2.9.1 Row Vector A vector is a row or column of elements. In a row vector the elements are entered with a space or a comma between the elements inside the square brackets. For example, x = 7 – 1 2 – 5 8 2.9.2 Column Vector In a column vector the elements are entered with a semicolon between the elements inside the square brackets. For example, x = 7 ; – 1 ; 2 ; – 5 ; 8 2.9.3 Matrix A matrix is a two-dimensional array which has numbers in rows and columns. A matrix is entered row-wise with consecutive elements of a row separated by a space or a comma, and the rows separated by semicolons or carriage returns. The entire matrix is enclosed within square brackets. The elements of the matrix may be real numbers or complex numbers. For example to enter the matrix, 13 −4  A =  02 − 8  The MATLAB input command is A = 1 3 – 4 ; 0 – 2 8 Similarly for complex number elements of a matrix B −+ 5lxxn2 7sin3y  B =  35ii −13  The MATLAB input command is B = – 5 x log(2 x) + 7 sin (3 y) ; 3i 5 – 13iMATLAB BASICS 35 2.9.4 Addressing Arrays A colon can be used in MATLAB to address a range of elements in a vector or a matrix. 2.9.4.1 Colon for a vector Va(:) – refers to all the elements of the vector Va (either a row or a column vector). Va(m : n) – refers to elements m through n of the vector Va. For instance V = 2 5 – 1 11 8 4 7 – 3 11 u = V(2 : 8) u = 5 – 1 11 8 4 7 – 3 11 2.9.4.2 Colon for a matrix Table 2.16 gives the use of a colon in addressing arrays in a matrix. Table 2.16 Colon use for a matrix Command Description A(:, n) Refers to the elements in all the rows of a column n of the matrix A. A(n, :) Refers to the elements in all the columns of row n of the matrix A. A(:, m : n) Refers to the elements in all the rows between columns m and n of the matrix A. A(m : n, :) Refers to the elements in all the columns between rows m and n of the matrix A. A(m : n, p : q) Refers to the elements in rows m through n and columns p through q of the matrix A. 2.9.5 Adding Elements to a Vector or a Matrix A variable that exists as a vector, or a matrix, can be changed by adding elements to it. Addition of elements is done by assigning values of the additional elements, or by appending existing variables. Rows and/or columns can be added to an existing matrix by assigning values to the new rows or columns. 2.9.6 Deleting Elements An element, or a range of elements, of an existing variable can be deleted by reassigning blanks to these elements. This is done simply by the use of square brackets with nothing typed in between them. 2.9.7 Built-in Functions Some of the built-in functions available in MATLAB for managing and handling arrays as listed in Table 2.17.36 ANALYSIS AND DESIGN OF CONTROL SYSTEMS USING MATLAB Table 2.17 Built-in functions for handling arrays Function Description Example length (A) Returns the number of elements A = 5 9 2 4 ; in the vector A length(A) ans = 4 size (A) Returns a row vector m, n, where A = 2 3 0 8 11 ; 6 17 5 7 1 m and n are the size m × n of the A = array A. 2 3 0 8 11 6 17 5 7 1 size(A) ans = 2 5 reshape (A, m, n) Rearrange a matrix A that has r A = 3 1 4 ; 9 0 7 rows and s columns to have m A = rows and n columns. r times s must 3 1 4 be equal to m times n.9 0 7 B = reshape(A, 3, 2) B = 3 0 9 4 1 7 diag (v) When v is a vector, creates a square v = 3 2 1; matrix with the elements of v in the A = diag(v) diagonal A = 3 0 0 0 2 0 0 0 1 diag (A) When A is a matrix, creates a vector from the diagonal elements of A. A = 1 8 3 ; 4 2 6 ; 7 8 3 A = 1 8 3 4 2 6 7 8 3 vec = diag(A) vec = 1 2 3MATLAB BASICS 37       We consider here matrices that have more than one row and more than one column. 2.10.1 Addition and Subtraction of Matrices The addition (the sum) or the subtraction (the difference) of the two arrays is obtained by adding or subtracting their corresponding elements. These operations are performed with arrays of identical size (same number of rows and columns). For example if A and B are two arrays (2 × 3 matrices). aa a bb b   11 12 13 11 12 13 A = and B =   aa a bb b  21 22 23  21 22 23 Then, the matrix addition (A + B) is obtained by adding A and B is ab++ a b ab +  11 11 12 12 13 13  ab++ a b ab + 23 23  21 21 22 22 2.10.2 Dot Product The dot product is a scalar computed from two vectors of the same size. The scalar is the sum of the products of the values in corresponding positions in the vectors. For n elements in the vectors A and B: n dot product = A  B = ab ∑ ii i = 1 dot(A, B) Computes the dot product of A and B. If A and B are matrices, the dot product is a row vector containing the dot products for the corresponding columns of A and B. 2.10.3 Array Multiplication The value in position c of the product C of two matrices, A and B, is the dot product of i, j row i of the first matrix and column of the second matrix: n c = . ab i, j ∑ ik,, k j k = 1 2.10.4 Array Division The division operation can be explained by means of the identity matrix and the inverse matrix operation. 2.10.5 Identity Matrix An identity matrix is a square matrix in which all the diagonal elements are 1’s, and the remaining elements are 0’s. If a matrix A is square, then it can be multiplied by the identity matrix, I, from the left or from the right: AI = IA = A38 ANALYSIS AND DESIGN OF CONTROL SYSTEMS USING MATLAB 2.10.6 Inverse of a Matrix The matrix B is the inverse of the matrix A if when the two matrices are multiplied the product is the identity matrix. Both matrices A and B must be square and the order of multipli- cation can be AB or BA. AB = BA = I 2.10.7 Transpose The transpose of a matrix is a new matrix in which the rows of the original matrix are the T columns of the new matrix. The transpose of a given matrix A is denoted by A . In MATLAB, the transpose of the matrix A is denoted by A′. 2.10.8 Determinant A determinant is a scalar computed from the entries in a square matrix. For a 2 × 2 matrix A, the determinant is A = a a – a a 11 22 21 12 MATLAB will compute the determinant of a matrix using the det function: det(A) computes the determinant of a square matrix A. 2.10.9 Array Division MATLAB has two types of array division, which are the left division and the right divi- sion. 2.10.10 Left Division The left division is used to solve the matrix equation Ax = B where x and B are column –1 vectors. Multiplying both sides of this equation by the inverse of A, A , we have –1 –1 A Ax = A B –1 or Ix = x = A B –1 Hence x = A B In MATLAB, the above equation is written by using the left division character: x = A \ B 2.10.11 Right Division The right division is used to solve the matrix equation xA = B where x and B are row –1 vectors. Multiplying both sides of this equation by the inverse of A, A , we have –1 –1 x  AA = B  A –1 or x = B  A In MATLAB, this equation is written by using the right division character: x = B \ A 2.10.12 Eigenvalues and Eigenvectors Consider the following equation, AX = λX ...(2.1) Where A is an n × n square matrix, X is a column vector with n rows and λ is a scalar. The values of λ for which X are nonzero are called the eigenvalues of the matrix A, and the corresponding values of X are called the eigenvectors of the matrix A.MATLAB BASICS 39 Eq. (2.1) can also be used to find the following equation (A – λI)X = 0 ...(2.2) where I is an n × n identity matrix. Eq. (2.2) corresponding to a set of homogeneous equations and has nontrivial solutions only if the determinant is equal to zero, or A – λI = 0 ...(2.3) Eq. (2.3) is known as the characteristic equation of the matrix A. The solution to Eq. (2.3) gives the eigenvalues of the matrix A. MATLAB determines both the eigenvalues and eigenvectors for a matrix A. eig(A) Computes a column vector containing the eigenvalues of A. Q, d = eig(A) Computes a square matrix Q containing the eigenvectors of A as col- umns and a square matrix d containing the eigenvalues (λ) of A on the diagonal. The values of Q and d are such that Q Q is the identity matrix and A X equals λ times X. Triangular factorization or lower-upper factorization: Triangular or lower-upper factorization expresses a square matrix as the product of two triangular matrices – a lower triangular matrix and an upper triangular matrix. The lu function in MATLAB computes the LU factorization: L, U = lu(A) Computes a permuted lower triangular factor in L and an upper triangu- lar factor in U such that the product of L and U is equal to A. QR factorization: The QR factorization method factors a matrix A into the product of an orthonormal matrix and an upper-triangular matrix. The qr function is used to perform the QR factorization in MATLAB: Q, R = qr(A) Computes the values of Q and R such that A = QR.Q will be an orthonormal matrix, and R will be an upper triangular matrix. For a matrix A of size m × n, the size of Q is m × m, and the size of R is m × n. Singular Value Decomposition (SVD): Singular value decomposition decomposes a matrix A (size m × n) into a product of three matrix factors. A = USV where U and V are orthogonal matrices and S is a diagonal matrix. The size of U is m × m, the size of V is n × n, and the size of S is m × n. The values on the diagonal matrix S are called singular values. The number of nonzero singular values is equal to the rank of the matrix. The SVD factorization can be obtained using the svd function: U, S, V = svd(A) Computes the factorization of A into the product of three matrices, USV, where U and V are orthogonal matrices and S is a diagonal matrix. svd(A) Returns the diagonal elements of S, which are the singular values of A.       Element-by-element operations can only be done with arrays of the same size. Element- by-element multiplication, division, and exponentiation of two vectors or matrices is entered in MATLAB by typing a period in front of the arithmetic operator. Table 2.18 lists these opera- tions.40 ANALYSIS AND DESIGN OF CONTROL SYSTEMS USING MATLAB Table 2.18 Element-by-element operations Arithmetic operators Matrix operators Array operators + Addition + Addition – Subtraction – Subtraction Multiplication  Array multiplication Exponentiation  Array exponentiation / Left division / Array left division \ Right division \ Array right division 2.11.1 Built-in Functions for Arrays Table 2.19 lists some of the many built-in functions available in MATLAB for analyzing arrays. Table 2.19 MATLAB built-in array functions Function Description Example mean (A) If A is a vector, returns the mean A = 3 7 2 16; value of the elements mean (A) ans = 14 C = max (A) If A is a vector, C is the largest A = 3 7 2 16 9 5 18 13 0 4; element in A. If A is a matrix, C is a C = max (A) row vector containing the largest C = 18 element of each column of A. d, n = max (A) If A is a vector, d is the largest d, n = max (A) element in A, n is the position of d = 18 the element (the first if several have the max value). n = 7 min (A) The same as max(A), but for the A = 3 7 2 16; smallest element. min (A) ans = 2 d, n = min (A) The same as d, n = max(A), but for the smallest element. sum (A) If A is a vector, returns the sum of A = 3 7 2 16; the elements of the vector. sum (A) ans = 28MATLAB BASICS 41 Function Description Example sort (A) If A is a vector, arranges the elements A = 3 7 2 16; of the vector in ascending order. sort (A) ans = 2 3 7 16 median (A) If A is a vector, returns the median A = 3 7 2 16; value of the elements of the vector. median (A) ans = 5 std (A) If A is a vector, returns the standard A = 3 7 2 16; deviation of the elements of the std (A) vector. ans = 6.3770 det (A) Returns the determinant of a square A = 1 2 3 4; matrix A. det (A) ans = – 2 dot (a, b) Calculates the scalar (dot) product of a = 5 6 7; two vectors a and b. The vector can b = 4 3 2; each be row or column vectors. dot (a, b) ans = 52 cross (a, b) Calculates the cross product of two a = 5 6 7; vectors a and b, (a × b). The two b = 4 3 2; vectors must have 3 elements cross (a, b) ans = – 9 18 – 9 inv (A) Returns the inverse of a square a = 1 2 3; 4 6 8; – 1 2 3; matrix A. inv (A) ans = – 0.5000 0.0000 – 0.5000 – 5.0000 1.5000 1.0000 3.5000 – 1.0000 – 0.5000      There are many physical processes and engineering applications that require the use of random numbers in the development of a solution. MATLAB has two commands rand and rand n that can be used to assign random num- bers to variables. The rand command: The rand command generates uniformly distributed over the in- terval 0, 1. A seed value is used to initiate a random sequence of values. The seed value is initially set to zero. However, it can be changed with the seed function. The command can be used to assign these numbers to a scalar, a vector, or a matrix, as shown in Table 2.20.42 ANALYSIS AND DESIGN OF CONTROL SYSTEMS USING MATLAB Table 2.20 The rand command Command Description Example rand Generates a single random number rand between 0 and 1. ans = 0.9501 rand (1, n) Generates an n elements row vector of a = rand(1, 3) random numbers between 0 and 1. a = 0.4565 0.0185 0.8214 rand (n) Generates an n × n matrix with b = rand(3) random numbers between 0 and 1. b = 0.7382 0.9355 0.8936 0.1763 0.9165 0.0579 0.4057 0.4103 0.3529 rand (m, n) Generates an m × n matrix with c = rand(2, 3) random numbers between 0 and 1. c = 0.2028 0.6038 0.1988 0.1987 0.2722 0.0153 randperm (n) Generates a row vector with n randperm(7) elements that are random permutation ans = of integers 1 through n. 5 2 4 7 1 6 3 2.12.1 The Random Command MATLAB will generate Gaussian values with a mean of zero and a variance of 1.0 if a normal distribution is specified. The MATLAB functions for generating Gaussian values are as follows: randn(n) Generates an n × n matrix containing Gaussian (or normal) random numbers with a mean of 0 and a variance of 1. Randn(m, n) Generates an m × n matrix containing Gaussian (or normal) random num- bers with a mean of 0 and a variance of 1.     A polynomial is a function of a single variable that can be expressed in the following form: n n–1 n–2 1 f(x) = a x + a x + a x + … + a x + a 0 1 2 n–1 n where the variable is x and the coefficients of the polynomial are represented by the values a , 0 a , … and so on. The degree of a polynomial is equal to the largest value used as an exponent. 1 A vector represents a polynomial in MATLAB. When entering the data in MATLAB, simply enter each coefficient of the polynomial into the vector in descending order. For exam- ple, consider the polynomialMATLAB BASICS 43 5 4 2 5s + 7s + 2s – 6s + 10 To enter this into MATLAB , we enter this as a vector as x = 5 702– 6 10 x = 5702– 610 It is necessary to enter the coefficients of all the terms. MATLAB contains functions that perform polynomial multiplication and division, which are listed below: conv(a, b) Computes a coefficient vector that contains the coefficients of the product of polynomials represented by the coefficients in a and b. The vectors a and b do not have to be the same size. q, r = deconv(n, d) Returns two vectors. The first vector contains the coefficients of the quotient and the second vector contains the coefficients of the remainder polynomial. The MATLAB function for determining the roots of a polynomial is the roots function: root(a) Determines the roots of the polynomial represented by the coefficient vector a. The roots function returns a column vector containing the roots of the polynomial; the number of roots is equal to the degree of the polynomial. When the roots of a polynomial are known, the coefficients of the polynomial are determined when all the linear terms are multi- plied, we can use the poly function: poly(r) Determines the coefficients of the polynomial whose roots are contained in the vector r. The output of the function is a row vector containing the polynomial coefficients. The value of a polynomial can be computed using the polyval function, polyval (a, x). It evaluates a polynomial with coefficients a for the values in x. The result is a matrix the same size ad x. For instance, to find the value of the above polynomial at s = 2, x = polyval(5 702– 6 10, 2) x = 278 To find the roots of the above polynomial, we enter the command roots (a) which deter- mines the roots of the polynomial represented by the coefficient vector a. roots(5 7 0 2 – 6 10) ans = – 1.8652 – 0.4641 + 1.0832i – 0.4641 – 1.0832i 0.6967 + 0.5355i 0.6967 – 0.5355i44 ANALYSIS AND DESIGN OF CONTROL SYSTEMS USING MATLAB % or x = 5 702– 6 10 x = 5702– 610 r = roots(x) r = – 1.8652 – 0.4641 + 1.0832i – 0.4641 – 1.0832i 0.6967 + 0.5355i 0.6967 – 0.5355i To multiply two polynomials together, we enter the command conv. 2 The polynomials are: x = 2x + 5 and y = x + 3x + 7 x = 2 5; y = 1 3 7; z = conv(x, y) z = 2 11 29 35 To divide two polynomials, we use the command deconv. z = 2 11 29 35; x = 2 5 g, t = deconv (z, x) g = 1 3 7 t = 0 0 0 0       A system of equations is nonsingular if the matrix A containing the coefficients of the equations is nonsingular. A system of nonsingular simultaneous linear equations (AX = B) can be solved using two methods: (a) Matrix Division Method. (b) Matrix Inversion Method. 2.14.1 Matrix Division The solution to the matrix equation AX = B is obtained using matrix division, or X = A/B. The vector X then contains the values of x. 2.14.2 Matrix Inverse For the solution of the matrix equation AX = B, we premultiply both sides of the equation –1 by A . –1 –1 A AX = A B –1 or IX = A B where I is the identity matrix.MATLAB BASICS 45 –1 Hence X = A B In MATLAB, we use the command x = inv (A) B. Similarly, for XA = B, we use the command x = Binv (A). The basic computational unit in MATLAB is the matrix. A matrix expression is enclosed in square brackets, . Blanks or commas separate the column elements, and semicolons or carriage returns separate the rows. A = 1 234 ; 5678 ; 9101112 A = 12 3 4 56 7 8 9 101112 The transpose of a simple matrix or a complex matrix is obtained by using the apostrophe key B = A′ B = 159 2610 3711 4812 Matrix multiplication is accomplished as follows: C = A B C = 30 70 110 70 174 278 110 278 446 C = B A C = 107 122 137 152 122 140 158 176 137 158 179 200 152 176 200 224 The inverse of a matrix D is obtained as D = 1 2 ; 3 4 D = 12 34 E = inv (D) E = – 2.0000 1.0000 1.5000 – 0.5000

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.