Вы находитесь на странице: 1из 190

Model-Based Calibration Toolbox Calibrate complex powertrain systems

Control System Design and Analysis Control System Toolbox Design and analyze control systems

System Identification Toolbox Create linear and nonlinear dynamic models from measured input-output data

Fuzzy Logic Toolbox Design and simulate fuzzy logic systems

Robust Control Toolbox Design robust controllers for plants with uncertain parameters and unmodeled dynamics

Model Predictive Control Toolbox Design and simulate model predictive controllers

Aerospace Toolbox Aerospace reference standards, environmental models, and aerodynamic coefficient importing

Signal Processing and Communications Signal Processing Toolbox

Perform signal processing, analysis, and algorithm development

Communications Toolbox Design and analyze algorithms for the physical layer of communication systems

Filter Design Toolbox

Design and analyze fixed-point, adaptive, and multirate filters

Filter Design HDL Coder Generate HDL code for fixed-point filters

Wavelet Toolbox Analyze and synthesize signals and images using wavelet techniques

Fixed-Point Toolbox Design and execute fixed-point algorithms and analyze fixed-point data

RF Toolbox Design, model, and analyze networks of RF components

Image Processing Image Processing Toolbox Perform image processing, analysis, and algorithm development

Image Acquisition Toolbox Acquire images and video from industry-standard hardware

Mapping Toolbox Analyze and visualize geographic information

Computational Biology Bioinformatics Toolbox Read, analyze, and visualize genomic, proteomic, and microarray data

SimBiology Model, simulate, and analyze biological systems

Test and Measurement Data Acquisition Toolbox Acquire and send out data from plug-in data acquisition boards

Instrument Control Toolbox Control and communicate with test and measurement instruments

Image Acquisition Toolbox Acquire images and video from industry-standard hardware

SystemTest Manage tests and analyze results for system verification and validation

OPC Toolbox Read, write, and log data from OPC servers

Vehicle Network Toolbox Communicate with in-vehicle networks using CAN protocol

Computational Finance Financial Toolbox Analyze financial data and develop financial algorithms

Financial Derivatives Toolbox Model and analyze equity and fixed-income derivatives

Datafeed Toolbox Acquire financial data from data service providers

Fixed-Income Toolbox Model and analyze fixed-income securities

Econometrics Toolbox Model and analyze financial and economic systems using statistical methods

Application Deployment MATLAB Compiler Build standalone executables and software components from Matlab code

Spreadsheet Link EX (for Microsoft Excel) Use MATLAB from Microsoft Excel

Application Deployment Targets MATLAB Builder EX (for Microsoft Excel)

Deploy MATLAB code as Microsoft Excel add-ins

MATLAB Builder NE (for Microsoft .NET Framework) Deploy MATLAB code as .NET and COM components

MATLAB Builder JA (for Java language) Deploy MATLAB code as Java classes

Database Connectivity and Reporting Database Toolbox Exchange data with relational databases

MATLAB Report Generator Generate documentation for MATLAB applications and data

SIMULINK PRODUCT FAMILY Simulink Simulation and Model-Based Design

Simulink Report Generator Generate documentation for Simulink and Stateflow models

Fixed-Point Modeling Simulink Fixed Point Design and simulate fixed-point systems

Event-Based Modeling Stateflow

Design and simulate state machines and control logic

SimEvents Model and simulate discrete-event systems

Physical Modeling Simscape Model and simulate multidomain physical systems

SimMechanics Model and simulate mechanical systems

SimPowerSystems Model and simulate electrical power systems

SimDriveline Model and simulate mechanical driveline systems

SimHydraulics Model and simulate hydraulic systems

SimElectronics Model and simulate electronic and electromechanical systems

Simulation Graphics Simulink 3D Animation Animate and visualize Simulink models in three dimensions

Gauges Blockset Monitor signals with graphical instruments

Control System Design and Analysis Simulink Control Design Compute PID gains, linearize models, and design control systems

Aerospace Blockset Model and simulate aircraft, spacecraft, and propulsion systems

Simulink Design Optimization Estimate and optimize Simulink model parameters

Signal Processing and Communications Signal Processing Blockset

Design and simulate signal processing systems and devices

Communications Blockset Design and simulate the physical layer of communication systems and components

RF Blockset Design and simulate the behavior of RF systems and components in a wireless system

Video and Image Processing Blockset Design and simulate video and image processing systems

Code Generation Real-Time Workshop Generate C code from Simulink models and MATLAB code

Real-Time Workshop Embedded Coder Generate C and C++ code optimized for embedded systems

Stateflow Coder Generate C code from Stateflow charts

Simulink HDL Coder Generate HDL code from Simulink models and MATLAB code

Target Support Package Deploy generated code onto embedded processors, microcontrollers, and DSPs

DO Qualification Kit (for DO-178) Qualify Simulink and PolySpace verification tools to DO-178

IEC Certification Kit (for IEC 61508 and ISO 26262) Certify embedded systems developed using Simulink and PolySpace products to IEC 61508 and ISO 26262

Rapid Prototyping and HIL Simulation xPC Target Perform real-time rapid prototyping and hardware-in-theloop simulation using PC hardware xPC Target Embedded Option Deploy real-time applications on PC hardware

Real-Time Windows Target Run Simulink models on a PC in real time

Verification, Validation, and Test Simulink Verification and Validation Trace requirements, enforce modeling standards, and measure model coverage

Simulink Design Verifier Generate tests and prove model properties using formal methods

SystemTest Manage tests and analyze results for system verification and validation

Embedded IDE Link Build, optimize, and verify code using embedded software development environments

EDA Simulator Link Cosimulate and verify VHDL and Verilog using HDL simulators

Simulink application

CHAPTER - 2 MATHEMATICAL OPERATIONS

Simple Calculations (arithmetic)


Matlab uses standard arithmetic operators + - / * ^ to indicate addition, subsraction, divison, multiplication, and raised-to-the-power respectively. The arithmetic operators have the following precedence-levels: 1. Brakets first. In case they are nested, then the sequence is from inner-most to the outer-most 2. Raised to power next. 3. multiplication and division is next. If there are such competing operators, then the sequence is from left to right. 4. Addition and subtraction next. In this case also, f there are competing such operators, then the sequence is from left to right.

For example, >> 3^2 - (5 + 4)/2 + 6*3 ans = 22.5000 MATLAB prints the answer and assigns the value to a variable called ans. If you want to perform further calculations with the answer, you can use the variable ans rather than retype the answer. For example, >> ans^2 + sqrt(ans) ans = 510.9934 Observe that MATLAB assigns a new value to ans with each calculation. You can assign computed values to variables of your choosing. For example,
>> a= 5/3*(2^5-4*3)-25 a= 8.3333

>> b= ((3^3-35)/(73-85)+(34/4+5)) b= 14.1667 >> (a-b)^2/(b-a) ans =

5.8333
If you wish to remove this echo in matlab, use a semicolon at the end of each command. For example: >> a= 5/3*(2^5-4*3)-25; >> >> b= ((3^3-35)/(73-85)+(34/4+5)); >> This will come up in the work area of matlab

So, the variable a will be assigned to a value 5/3*(2^5-4*3)-25 and variable b will be assigned to a value ((3^3-35)/(73-85)+(34/4+5)) and no echo occurs . And now you can use variable a and b in the complicated calculations like; >> (a-b)^2/(b-a) ans = 5.8333 Or can be written as: >> a= 5/3*(2^5-4*3)-25; b= ((3^3-35)/(73-85)+(34/4+5));(a-b)^2/(b-a) ans = 5.8333

To clear the value of the variables a and b , type clear a; clear b .

>> a-b ??? Undefined function or variable 'a'.


>> b-a ??? Undefined function or variable 'b'. The variables of a and b are not in the memory of matlab now and when we deal with calculation on these variables, matlab gives a warning as indicated. According to the precedence of a and b the warning alters. If the first one is not in the memory, matlab does not interest in the others.

Arithmetic Operators + - * / \ ^ ' for Matrix and array arithmetic

+ Addition or unary plus. A+B adds A and B. A and B must have the same size, unless one is a scalar. A scalar can be added to a matrix of any size.
- Subtraction or unary minus. A-B subtracts B from A. A and B must have the same size, unless one is a scalar. A scalar can be subtracted from a matrix of any size. * Matrix multiplication. C = A*B is the linear algebraic product of the matrices A and B. More precisely,

For nonscalar A and B, the number of columns of A must equal the number of rows of B. A scalar can multiply a matrix of any size.

.*

Array multiplication. A.*B is the element-by-element product of the arrays A and B. A and B must have the same size, unless one of them is a scalar.

/
./ \

Slash or matrix right division. B/A is roughly the same as B*inv(A). More precisely, B/A = (A'\B')'.
Array right division. A./B is the matrix with elements A(i,j)/B(i,j). A and B must have the same size, unless one of them is a scalar. Backslash or matrix left division. If A is a square matrix, A\B is roughly the same as inv(A)*B, except it is computed in a different way. If A is an n-by-n matrix and B is a column vector with n components, or a matrix with several such columns, then X = A\B is the solution to the equation AX = B. A warning message is displayed if A is badly scaled or nearly singular.

If A is an m-by-n matrix with m ~= n and B is a column vector with m components, or a matrix with several such columns, then X = A\B is the solution in the least squares sense to the under- or overdetermined system of equations AX = B .\ Array left division. A.\B is the matrix with elements B(i,j)/A(i,j). A and B must have the same size, unless one of them is a scalar. ^ Matrix power. X^p is X to the power p, if p is a scalar. If p is an integer, the power is computed by repeated squaring. If the integer is negative, X is inverted first. For other values of p, the calculation involves eigenvalues and eigenvectors, such that if [V,D] = eig(X), then X^p = V*D.^p/V. If x is a scalar and P is a matrix, x^P is x raised to the matrix power P using eigenvalues and eigenvectors. X^P, where X and P are both matrices, is an error.

.^

Array power. A.^B is the matrix with elements A(i,j) to the B(i,j) power. A and B must have the same size, unless one of

them is a scalar.
' Matrix transpose. A' is the linear algebraic transpose of A. For complex matrices, this is the complex conjugate transpose.

.'

Array transpose. A.' is the array transpose of A. For complex


matrices, this does not involve conjugation.

Examples on arithmetic operators > X = 0:2:10 , X' , X.^2 X= 0 ans = 0 2 4 6 8 10

8 10

ans = 0 4 16 36 64 100

The period in this expression is very important; it says that the

numbers in X should be squared individually, or element-by-element.


Typing X^2 would tell Matlab to use matrix multiplication to multiply X by itself and would produce an error message in this case. >>X = 0:2:10 , X./3, X.\3 ans = 0 0.6667 1.3333 2.0000 2.6667 3.3333 ans = Inf 1.5000 0.7500 0.5000 0.3750 0.3000

NUMBERS AND STORAGE Matlab performs all calculations in double precision and can work with the following data types: numbers Integer Real Complex Inf Details Numbers without any fractional part and decimal point. For example : 645 Numbers with fractional part e.g. 3.1234 Numbers having real and imaginary parts e.g. 3+5i Matlab treats i as well as j to represent -1 nfinity e.g. The result of divided with zero.

NaN

Not a number e.g. 0/0

For display of the results, matlab uses format command to control the output Category Format short Format short e Format long e Format bank details 4 decimal places (3.2345) 4 decimal places with exponent (3.2345e+00) Normal with exponent (3.2345678934627e+00) 2 decimal places (3..23)

FUNCTIONS
FUNCTION abs sqrt sign STANDS FOR Absolute value Square root function Signum function

conj
imaj real angle cos

Conjugate of a complex number


maginary part of a complex number Real part of a complex number Phase angle of a complex number Cosine function

sin
tan exp log log10

Sine function
Tangent function Exponential function Natural function Logaritm base 10

FUNCTION cosh sinh tanh acos acosh asin asinh

STANDS FOR Hyperbolic cosine function Hyperbolic sine function Hyperbolic tangent function nverse cosine Inverse Hyperbolic cosine Inverse sine Inverse hyperbolic sine

atan
atanh atan2 round floor fix ceil rem

Inverse tangent
Inverse hyperbolic tangent Two argument form of inverse tan Round to nearest integer Round towards minus infinity Round towards zero Round towards plus infinity Reminder after division

Vectors and Matrices


The row vectors: The row vectors are entities enclosed in pair of square-brakets with numbers seperated either by spaces or by commas. For example, enter two

vectors Z and Y as:


>> Z = [2,4,6,8] Z= 2 4 6 8 >> Y = [4 -3 5 -2] Y= 4 -3 5 -2

Adding Two Row Matrices:

>> Z = [2 4 6 8] >> Y = [4 -3 5 -2]


>>X=Z+Y It creates new row matrix X= 6 1 11 6

The linear combination of Z and Y: >> C=4*Z+6*Y C= 32 -2 54 20

Combination of vectors to form another vector: W =[Z,Y] W= 2 4 6 8 4 -3 5 -2

Application of Build in functions and some command to row Matrix: sort(W) ans =

-3

-2

min(W) ans = -3

max(W) ans = 8

sum(W) ans = 24 sin(sum(W)) ans = -0.9056

mean(W) ans = 3

log(W) ans = Columns 1 through 3 0.6931 1.3863 1.7918

Columns 4 through 6
2.0794 1.3863 1.0986 + 3.1416i

Columns 7 through 8 1.6094 0.6931 + 3.1416i

Rand: Generates an array with elements randomly chosen from the uniform distribution over the interval [0, 1] Rand ans = 0.4326

Randn: Generates an array with elements randomly chosen from the normal distribution function with zero mean and standard deviation 1.
Randn ans = 0.1253

plot(Z,Y)

Column Vectors The column vectors in matlab are formed by using a set of numbers in a pair of square brackets and seperating them with semi-colon. Therefore, one can define two column vectors A and B and add them as below: >> A=[2;3;1],B=[4;6;5], C=A+B A= 2 3 1 B= 4 6 5 C= 6 9 6

The Notation: n order to form a vector as a sequence of numbers, one may use the colon

notation. According to which, a:b:c yields a sequence of numbers starting with


a, and possibly ending with c in steps of b.

Heres how to do it without typing each number: >> X = [1:9] X= 1 2 3 4 5 6 7 8 Or you may not use [ ] notation 9

>> X = 1:9
X= 1 2 3 4 5 6 7 8 9

In this example the increment is not given, in this case matlab


default value is 1 so matlab understands that the increment is one.

Example : >> X = 0:2:10 X= 0 2 4 6

8 10

In this example, the increment is specified as 2. Note that in some cases, the upper limit may not be attainable thing. For example; >> D= 1:0.3:3 D= 1.0000 1.3000 1.6000 1.9000 2.2000 2.5000 2.8000 Example; >> 1:-1:5 ans = Empty matrix: 1-by-0

>> 5:-1:1 ans = 5 4 3

Sections of a Vector:
Let us define a vector using the range notation: >> W=[1:3,7:9] W= 1 2 3 7

Now we would like to extract the middle of two elements of this vector. This can be done with the range notation again. As you can see, the middle two elements are 3:4 range. Therefore, the required part of vector can be obtained as:
>> W(3:4) ans =

For example; 6:-1:1 is the desending range and when used with part extraction of vector, it gives: >> W(6:-1:1) ans = 9 8 7 3 2 1 Thus by this way we sorted vector numbers from bigger to smaller values. >> H=1:2:19 H= 1 3 5 7 9 11 13 15 17 19 >> H(3:2:8) ans = 5 9 13

Example >> M=[3,2,7]; N =[6,8,9]; M+N , M-N , M*N

ans = 9 10 16
ans = -3 -6 -2 ??? Error using ==> mtimes Inner matrix dimensions must agree

As we can see, M+N and M-N are calculated but M*N can not be calculated. Because the summation and substraction can be performed when the marix dimensions are the same. For example, 3x3 matrix can be sum or substract by only 3x3 matrix. But in multiplication, the number of first vector column must be equal to the number of second vector row. For example, (2x3) by (3x1) this results 2x1 vector as shown below.

>> M=[3,2,7;2,3,4], N =[6;8;9], M*N M= 3 2 2 3 N= 6 8 9 ans = 97 72 7 4

If you dont want M an N be seen in the window , we can write by using

semicolon instead of comma:


>> M=[3,2,7;2,3,4]; N =[6;8;9];M*N ans = 97 72

2.5 Transpose We can convert a column vector into a row vector (and vice versa) by a process called transposing denoted by '. >> c = [ 1; 3; sqrt(5)],c c= 1.0000 3.0000 2.2361 ans = 1.0000 3.0000 2.2361

>> w= [3 -5 9], c = [ 1; 3; sqrt(5)],t = w + 2*c' w= 3 -5 9 c= 1.0000 3.0000 2.2361 t= 5.0000 1.0000 13.4721
>> T = 5*w'-2*c T= 13.0000 -31.0000 40.5279

If x is a complex vector, then x' gives the complex conjugate transpose of x: >> x = [1+3i, 2-2i], x x= 1.0000 + 3.0000i 2.0000 - 2.0000i ans = 1.0000 - 3.0000i 2.0000 + 2.0000i

Example :
>> A=[1,3,6;2,7,8;0,3,9] Then the output appears in the next line as shown below.

A= 1 2 0

3 6 7 8 3 9 Thus, a matrix is entered row by row, and each row is separated by the semicolon(;). Within each row, elements are separated by a space or a comma(,). Commands and variables used in Matlab are casesensitive. That is, lower case letters are distinguished from upper case letters. The size of the matrix is checked with >> size(A) ans = 3 3 >> A' ans = 1 2 0 3 7 3 6 8 9

Arrays and Matrices, Basic Information Length Max Length of vector or largest array dimension Largest elements in array

Min
Size Eye Zeros

Smallest elements in array


Array dimensions Identity matrix Create array of all zeros

Cross
Dot Sum Sort

Vector cross product


Vector dot product Sum of array elements Sort array elements in ascending or descending order

Det
Rank nv Eig

Matrix determinant
Rank of matrix Matrix inverse Eigenvalues and eigenvectors

Sqrtm
Expm Logm

Matrix square root


Matrix exponential Matrix logarithm

2.7 Working on Matrices 2.7.1 Dot product (dot) C = dot(A,B) C = dot(A,B,dim) C = dot(A,B) returns the scalar product of the vectors A and B.

A and B must be vectors of the same length. When A and B are both
column vectors, dot(A,B) is the same as A*B. For multidimensional arrays A and B, dot returns the scalar

product along the first non-singleton dimension of A and B. A and B


must have the same size. C = dot(A,B,dim) returns the scalar product of A and B in the dimension dim.

Examples The dot product of two vectors is calculated as shown: >> a = [1 2 3]; b = [4 5 6]; c = dot(a,b) c= 32 But if we write; >> a.*b ans =

4 10 18

2.7.2- Product of array elements(prod) B = prod(A) B = prod(A,dim) B = prod(A) returns the products along different dimensions of an array.

If A is a vector, prod(A) returns the product of the elements.


If A is a matrix, prod(A) treats the columns of A as vectors, returning a row vector of the products of each column.

If A is a multidimensional array, prod(A) treats the values along the


first non-singleton dimension as vectors, returning an array of row vectors. B = prod(A,dim) takes the products along the dimension of A specified by scalar dim.

Examples
The magic square of order 3 is M = magic(3) M= 8 1 6 3 5 7 4 9 2 The product of the elements in each column is

prod(M) =
96 45 84 The product of the elements in each row can be obtained by: prod(M,2) = 48 105 72

2.7.3 Vector cross product(cross) C = cross(A,B) C = cross(A,B,dim) C = cross(A,B) returns the cross product of the vectors A and B. That is, C = A x B. A and B must be 3-element vectors. If A and B are multidimensional arrays, cross returns the cross product of A and B along the first dimension of length 3. C = cross(A,B,dim) where A and B are multidimensional arrays, returns the cross product of A and B in dimension dim. A and B must have the same size, and both size(A,dim) and size(B,dim) must be 3.

Example The cross product of two vectors are calculated as shown: >> a = [1 2 3];

b = [4 5 6];

c = cross(a,b) c= -3 6 -3

c = cross(b,a)

2.7.4- Matrix determinant(det)

d = det(X)
d = det(X) returns the determinant of the square matrix X. If X contains only integer entries, the result d is also an integer. Algorithm: The determinant is computed from the triangular factors obtained by Gaussian elimination [L,U] = lu(A) s = det(L) % This is always +1 or -1

det(A) = s*prod(diag(U))

Examples The statement A = [1 2 3; 4 5 6; 7 8 9] produces A= 1 2 3 4 5 6 7 8 9 >> A = [1 2 3; 4 5 6; 7 8 9]; det(A) ans = 0 This happens to be a singular matrix, so d = det(A) produces d = 0. Changing A(3,3) with A(3,3) = 0 turns A into a nonsingular matrix. Now d = det(A) produces d = 27. The statement B = [1 7 -5; 4 -3 6; -1 8 9]; det(B) produces >> B = [1 7 -5; 4 -3 6; -1 8 9]; det(B) ans = -514

2.7.5 Rank of matrix(rank)

k = rank(A) k = rank(A,tol) The rank function provides an estimate of the number of linearly independent rows or columns of a full matrix. K = rank(A) returns the number of singular values of A that

are larger than the default tolerance, max(size(A))*eps(norm(A)).


K = rank(A,tol) returns the number of singular values of A that are larger than tol.

The rank algorithm is s = svd(A); tol = max(size(A))*eps(max(s)); r = sum(s > tol); >> A = [1 0 0 0 0 >> rank(A) ans = 2 1 0 2 -1 ];

2.7.6. Matrix inverse(inv)

Y = inv(X)
Y = inv(X) returns the inverse of the square matrix X. A warning message is printed if X is badly scaled or nearly singular.

In practice, it is seldom necessary to form the explicit inverse of a


matrix. A frequent misuse of inv arises when solving the system of linear equations Ax=b. One way to solve this is with x = inv(A)*b. A better way, from both an execution time and numerical accuracy standpoint, is to use the matrix division operator x = A\b. This produces the solution using Gaussian elimination, without forming the inverse.

>> A = [1 2 3; 4 5 6]; B=inv(A) ??? Error using inv

Matrix must be square.

>> A = [1 2 3; 4 5 6; 3 4 2]; B=inv(A) B= -1.5556 0.8889 -0.3333 1.1111 -0.7778 0.6667 0.1111 0.2222 -0.3333

2.7.7 Sum of array elements(sum) B = sum(A) B = sum(A,dim) B = sum(..., double) B = sum(..., dim,double) B = sum(..., native) B = sum(..., dim,native) B = sum(A) returns sums along different dimensions of an array.

If A is a vector, sum(A) returns the sum of the elements.


If A is a matrix, sum(A) treats the columns of A as vectors, returning a row vector of the sums of each column. If A is a multidimensional array, sum(A) treats the values along the first non-singleton dimension as vectors, returning an array of row vectors.

B = sum(A,dim) sums along the dimension of A specified by scalar dim. The dim input is an integer value from 1 to N, where N is the number of dimensions in A. Set dim to 1 to compute the sum of each column, 2 to sum rows, etc. B = sum(..., double) and B = sum(..., dim,double) performs additions in double-precision and return an answer of type double, even if A has data type single or an integer data type. This is the default for integer data types. B = sum(..., native) and B = sum(..., dim,native) performs additions in the native data type of A and return an answer of the same data type. This is the default for single and double. Remarks:

sum(diag(X)) is the trace of X.

Examples
The magic square of order 3 is M = magic(3)

M=
8 3 4 1 6 5 7 9 2 This is called a magic square because the sums of the elements in each column are the same. Sum(M) = 15 15 15

as are the sums of the elements in each row, obtained either by transposing or using thedim argument.

Transposing sum(M) =

15 15 15
Using the dim argument

sum(M,1) ans = 15 15 15

2.7.8- Length of vector or largest array dimension(length) numberOfElements = length(array) Number Of Elements = length(array) finds the number of elements along the largest dimension of an array. Array is an array of any matlab data type and any valid dimensions. numberOfElements is a whole number of the matlab double class. For non-empty arrays, number of elements is equivalent to max(size(array)). For empty arrays, number of elements is zero. Example Create a 1-by-8 array X and use length to find the number of elements in the second (largest) dimension: X = [5, 3.4, 72, 28/4, 3.61, 17 94 89]; length(X) ans = 8

2.7.9. Largest elements in array(max) C = max(A) C = max(A,B) C = max(A,[],dim) [C,I] = max(...) C = max(A) returns the largest elements along different dimensions of an array. If A is a vector, max(A) returns the largest element in A. If A is a matrix, max(A) treats the columns of A as vectors, returning a row vector containing the maximum element from each column. If A is a multidimensional array, max(A) treats the values along the first non-singleton dimension as vectors, returning the maximum value of each vector.

C = max(A,B) returns an array the same size as A and B with the largest elements taken from A or B. The dimensions of A and B must match, or they may be scalar. C = max(A,[],dim) returns the largest elements along the dimension of A specified by scalar dim. For example, max(A,[ ],1) produces the maximum values along the first dimension (the rows) of A. [C,I] = max(...) finds the indices of the maximum values of A, and

returns them in output vector I. If there are several identical maximum


values, the index of the first one found is returned.

2.7.10 Smallest elements in array(min) C = min(A) C = min(A,B) C = min(A,[],dim) [C,I] = min(...) C = min(A) returns the smallest elements along different dimensions of an array. If A is a vector, min(A) returns the smallest element in A. If A is a matrix, min(A) treats the columns of A as vectors, returning a row vector containing the minimum element from each column. If A is a multidimensional array, min operates along the first

nonsingleton dimension.

C = min(A,B) returns an array the same size as A and B with the smallest elements taken from A or B. The dimensions of A and B must match, or they may be scalar.

C = min(A,[],dim) returns the smallest elements along the


dimension of A specified by scalar dim. For example, min(A,[],1) produces the minimum values along the first dimension (the rows) of A.

[C,I] = min(...) finds the indices of the minimum values of A, and returns them in output vector I. If there are several identical minimum values, the index of the first one found is returned.

2.7.11- Average or mean value of array (mean) M = mean(A) M = mean(A,dim) M = mean(A) returns the mean values of the elements along different dimensions of an array. If A is a vector, mean(A) returns the mean value of A. If A is a matrix, mean(A) treats the columns of A as vectors, returning a row vector of mean values. If A is a multidimensional array, mean(A) treats the values along the first non-singleton dimension as vectors, returning an array of mean values. M = mean(A,dim) returns the mean values for elements along the dimension of A specified by scalar dim. For matrices, mean(A,2) is a column vector containing the mean value of each row.

Examples A = [1 2 3; 3 3 6; 4 6 8; 4 7 7]; mean(A) ans = 3.0000 4.5000 6.0000 mean(A,2) ans = 2.0000 4.0000 6.0000 6.0000

2.7.12 Median value of array(median) M = median(A) M = median(A,dim) M = median(A) returns the median values of the elements along different dimensions of an array. A should be of type single or double. If A is a vector, median(A) returns the median value of A. If A is a matrix, median(A) treats the columns of A as vectors, returning a row vector of median values.

If A is a multidimensional array, median(A) treats the values


along the first nonsingleton dimension as vectors, returning an array of median values.

M = median(A,dim) returns the median values for elements along the dimension of A specified by scalar dim.

Examples
A = [1 2 4 4; 3 4 6 6; 5 6 8 8; 5 6 8 8] A= 1 2 4 4 3 4 6 6 5 6 8 8 5 6 8 8 median(A) ans = 4 5 7 7 median(A,2) ans = 3 5 7 7

2.7.13- Identity matrix(eye) Y = eye(n) Y = eye(m,n) Y = eye([m n]) Y = eye(size(A)) Y = eye(m, n, classname) Y = eye(n) returns the n-by-n identity matrix. Y = eye(m,n) or Y = eye([m n]) returns an m-by-n matrix with 1's on the diagonal and 0's elsewhere. The size inputs m and n should be nonnegative integers. Negative integers are treated as 0. Y = eye(size(A)) returns an identity matrix the same size as A. Y = eye(m, n, classname) is an m-by-n matrix with 1's of class classname on the diagonal and zeros of class classname elsewhere. classname is a string specifying the data type of the output. classname can take the following values: 'double', 'single', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', or 'uint64'.

The identity matrix is not defined for higher-dimensional arrays. The assignment y = eye([2,3,4]) results in an error. Examples Return a 3-by-5 matrix of class int8:

>> x = eye(3,5,'int8') x= 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0

2.7.14 - Matrix square root(sqrtm) X = sqrtm(A) [X, resnorm] = sqrtm(A) [X, alpha, condest] = sqrtm(A) X = sqrtm(A) is the principal square root of the matrix A, i.e. X*X = A. X is the unique square root for which every eigenvalue has nonnegative real part. If A has any eigenvalues with negative real parts then a complex

result is produced. If A is singular then A may not have a square root. A


warning is printed if exact singularity is detected.

Examples

Example 1 A matrix representation of the fourth difference operator is X= 5 -4 1 0 0 -4 6 -4 1 0 1 -4 6 -4 1 0 1 -4 6 -4 0 0 1 -4 5 This matrix is symmetric and positive definite. Its unique positive definite square root, Y = sqrtm(X), is a representation of the second difference operator. Y= 2 -1 -0 -0 -0 -1 2 -1 0 -0 0 -1 2 -1 0 -0 0 -1 2 -1 -0 -0 -0 -1 2

Example 2 The matrix X= 7 10 15 22 has four square roots. Two of them are Y1 = 1.5667 1.7408 2.6112 4.1779 and Y2 = 1 2 3 4 The other two are -Y1 and -Y2. All four can be obtained from the eigenvalues and vectors of X.

2.7.15 - Matrix exponential (expm)

Y = expm(X) Y = expm(X) computes the matrix exponential of X. Although it is not computed this way, if X has a full set of eigenvectors V with corresponding eigenvalues D, then [V,D] = EIG(X) and EXPM(X) = V*diag(exp(diag(D)))/V Examples This example computes and compares the matrix exponential of A and the exponential of A.

A = [1 0 0

1 0 0

0 2 -1 ];

expm(A) ans = 2.7183 1.7183 1.0862 0 1.0000 1.2642 0 0 0.3679


exp(A) ans = 2.7183 1.0000 1.0000

2.7183 1.0000 1.0000

1.0000 7.3891 0.3679

Notice that the diagonal elements of the two results are equal. This would be true for any triangular matrix. But the off-diagonal elements, including those below the diagonal, are different

2.7.16 - Matrix logarithm (logm) L = logm(A) [L, exitflag] = logm(A) L = logm(A) is the principal matrix logarithm of A, the inverse of expm(A). L is the unique logarithm for which every eigenvalue has imaginary part lying strictly between - and . If A is singular or has any eigenvalues on the negative real axis, the principal logarithm is undefined.

In this case, logm computes a non-principal logarithm and returns a


warning message. [L, exitflag] = logm(A) returns a scalar exitflag that describes the exit

condition of logm:
If exitflag = 0, the algorithm was successfully completed.

If exitflag = 1, too many matrix square roots had to be computed. However, the computed value of L might still be accurate. This is different from R13 and earlier versions that returned an expensive and often inaccurate error estimate as the second output argument. The input A can have class double or single. Remarks: If A is real symmetric or complex Hermitian, then so is logm(A). Some matrices, like A = [0 1; 0 0], do not have any logarithms, real or complex, so logm cannot be expected to produce one. Limitations: For most matrices: logm(expm(A)) = A = expm(logm(A)) These identities may fail for some A. For example, if the computed eigenvalues of A include an exact zero, then logm(A) generates infinity. Or, if the elements of A are too large, expm(A) may overflow.

Examples Suppose A is the 3-by-3 matrix 1 1 0 0 0 2 0 0 -1 and Y = expm(A) is Y= 2.7183 1.7183 1.0862 0 1.0000 1.2642 0 0 0.3679 Then A = logm(Y) produces the original matrix A. Y= 1.0000 1.0000 0.0000 0 0 2.0000 0 0 -1.0000 But log(A) involves taking the logarithm of zero, and so produces ans = 0.0000 0 -35.5119 -Inf -Inf 0.6931 -Inf -Inf 0.0000 + 3.1416i

Excercises: 1. Enter the following numbers at the command prompt in scientific notation (answers are below): 1.234 105, 8.765 104, 10 15, 1012. (1.234e5, -8.765e-4, 1e-15, -1e12) 2. Set up any 3 3 matrix a. Write some command-line statements to perform the following operations on a: (a) interchange columns 2 and 3; (b) add a fourth column (of 0s); (c) insert a row of 1s as the new second row of a (i.e. move the current second and third rows down); (d) remove the second column. 3. Draw lines joining the following points: (0, 1), (4, 3), (2, 0) and (5,2) on a xy coordinate system. 4. The initial heat distribution over a steel plate is given by the function

u(x, y) = 80y2ex20.3y2 Plot the surface u over the grid defined by 2.1 x 2.1, 6 y 6, where the grid width is 0.15 in both directions. .

5. Draw a graph of the population of the USA from 1790 to 2000, using the (logistic) model P(t) = 19 72 73 000 1 + e0.03134(t1913.25) where t is the date in years. Actual data (in 1000s) for every decade from 1790 to 1950 are as follows: 3929, 5308, 7240, 9638, 12 866, 17 069, 23 192, 31 443, 38 558, 50 156, 62 948, 75 995, 91 972, 105 711, 122 775, 131 669, 150 697. Superimpose this data on the graph of P(t). Plot the data as discrete circles (i.e. do not join them with lines) 6. The Spiral of Archimedes may be represented in polar coordinates by the equation r = a, where a is some constant. (The shells of a class of animals called nummulites grow in this way.) Write some command-line statements to draw the spiral for some values of a.

7. The arrangement of seeds in a sunflower head (and other flowers, like daisies) follows a fixed mathematical pattern. The nth seed is at position r =n, A perfect sunflower? with angular coordinate dn/180 radians, where d is the constant angle of divergence (in degrees) between any two successive seeds, i.e. between the nth and (n+1)th seeds. A perfect sunflower head is generated by d=137.51. Write a program to plot the seeds; use a circle (o) for each seed. A remarkable feature of this model is that the angle d must be exact to get proper sunflowers. Experiment with some different values, e.g. 137.45 (spokes, from fairly far out), 137.65 (spokes all the way), 137.92 (Catherine wheels).

CHAPTER 3
SOLVING LINEAR EQUATIONS,

DIFFERANTIATION AND INTEGRATION

3.1 Algebra To perform symbolic computations, you must use syms to

declare the variables you plan to use to be symbolic variables.


Consider the following series of commands: >> syms x y (x - y)*(x - y)^2

ans =

(x - y)^3

>> expand(ans) ans = x^3 - 3*x^2*y + 3*x*y^2 - y^3 >> factor(ans) ans = (x - y)^3 The command expand told Matlab to multiply out the expression, and factor forced Matlab to restore it to factored form.

Matlab has a command called simplify, which you can sometimes use to
express a formula as simply as possible. For example, >> simplify((x^3 - y^3)/(x - y)) ans = x^2 + x*y + y^2 4.2 Symbolic Expressions, Variable Precision, and Exact Arithmetic you can also do exact arithmetic with symbolic expressions. Consider the following example:

>> cos(pi/2)
ans = 6.1232e-17

The answer is written in floating point format and means 6.1232 1017. However, we know that cos(/2) is really equal to 0. The inaccuracy is due to the fact that typing pi in Matlab gives an approximation to accurate to about 15 digits, not its exact value. To

compute an exact answer, instead of an approximate answer, we must


create an exact symbolic representation of /2 by typing sym(pi/2). Now lets take the cosine of the symbolic representation of /2: >> cos(sym('pi/2')) ans = 0 This is the expected answer.

The quotes around pi/2 in sym(pi/2) create a string consisting of the characters pi/2 and prevent MATLAB from evaluating pi/2 as a floating point number. The command sym converts the string to a symbolic expression. The commands sym and syms are closely related. In fact, syms x is equivalent to x = sym(x). The command syms has a lasting effect on its argument (it declares it to be symbolic from now on), while sym has only a temporary effect unless you assign the output to a variable, as in x = sym(x). Here is how to add 1/2 and 1/3 symbolically:

>> sym('1/2') + sym('1/3') ans =

5/6
In simple aritmetic solution; > 1/2+1/3 ans = 0.8333 Finally, you can also do variable-precision arithmetic with vpa. For example, to print 50 digits of 2, type >> vpa(sqrt(2), 50) ans = 1.4142135623730950488016887242096980785696718753769

You should be aware of using sym or vpa on an expression that Matlab must evaluate before applying variable-precision arithmetic. To illustrate, enter the expressions 345, vpa(345), and vpa(345). The first gives a floating point approximation to the answer, the second because Matlab only carries 16-digit precision in its

floating point evaluation of the exponentiation gives an answer


that is correct only in its first 16 digits, and the third gives the exact answer.

>> 3^45
ans = 2.9543e+021 >> vpa(3^45) ans = 2954312706550833610752.0 >> vpa('3^45') ans = 2954312706550833698643.0

3.2 Variables and Assignments In Matlab, you use the equal sign to assign values to a variable.

For instance,
>> x=7 x=

7
will give the variable x the value 7 from now on. Hence forth, whenever Matlab sees the letter x, it will substitute the value 7. For example, if y has been defined as a symbolic variable, then >> x^2 - 2*x*y + y ans = 49 - 13*y

To clear the value of the variable x, type clear x. You can make very general assignments for symbolic variables and then manipulate them. For example, >> clear x; syms x y >> z = x2 - 2*x*y + y z= x^2-2*x*y+y >> 5*y*z ans =

5*y*(x^2-2*x*y+y)

3.3 Interrupting Calculations If MATLAB is hung up in a calculation, or is just taking too long to perform

an operation, you can usually abort it by typing CTRL+C (that is,


hold down the key labeled CTRL, or CONTROL, and press C).

4.5 Solving Equations 4.5.1 linear Equations You can solve equations involving variables with solve or fzero. For example, to find the solutions of the quadratic equation x2 2x 4 = 0, type >> solve('x^2 - 2*x - 4 = 0') ans = 1 - 5^(1/2) 5^(1/2) + 1

Note that the equation to be solved is specified as a string; that is,

it is surrounded by single quotes. The answer consists of the exact


(symbolic) solutions 1 5. To get numerical solutions, type double(ans), or vpa(ans) to display more digits. >> double(ans) ans = -1.2361 3.2361 >> vpa(ans)

ans =
-1.2360679774997896964091736687313 3.2360679774997896964091736687313

The command solve can solve higher-degree polynomial equations, as well as many other types of equations. It can also solve equations involving more than one variable. If there are fewer equations than variables, you should specify (as strings) which variable(s) to solve for. For example, type solve(2*x -log(y) = 1, y) to solve 2x log y = 1 for y in terms of x. >> solve('2*x -log(y) = 1', 'y') ans = exp(2*x - 1) This means, y=e2x-1

You can specify more than one equation as well. For example, >> [x, y] = solve('x^2 - y = 2', 'y - 2*x = 5')

x=
2*2^(1/2) + 1 1 - 2*2^(1/2)

y= 4*2^(1/2) + 7 7 - 4*2^(1/2)

This system of equations has two solutions. Matlab reports the solution by giving the two x values and the two y values for those solutions. Thus the first solution consists of the first value of x together with the first value of y. You can extract these values by typing x(1) and y(1): >> x(1),y(1) ans =

2*2^(1/2) + 1

ans =

4*2^(1/2) + 7 The second solution can be extracted with x(2) and y(2).

Note that in the preceding solve command, we assigned the


output to the vector [x, y]. If you use solve on a system of equations without assigning the output to a vector, then Matlab does not automatically display the values of the solution: >> sol = solve('x^2 - y = 2', 'y - 2*x = 5')

sol =
x: [2x1 sym] y: [2x1 sym]

To see the vectors of x and y values of the solution, type sol.x and sol.y. To see the individual values, type sol.x(1), sol.y(1), etc. >> sol.x , sol.y

ans =
2*2^(1/2) + 1 1 - 2*2^(1/2)

ans =
4*2^(1/2) + 7 7 - 4*2^(1/2)

3.4.1.a. Suppressing Output Some Matlab commands produce output that is superfluous. For example, when you assign a value to a variable, Matlab echoes the value. You can suppress the output of a command by putting a semicolon after the command. Here is an example: >> syms x >> y = x + 7 y= x+7 >> z = x + 7; >> z z= x+7

Another object that you may want to suppress is Matlabs


label for theoutput of a command. The command disp is designed to achieve that; typing disp(x) will print the value of

the variable x without printing the label and the equal sign. So,
>> x = 7;

>> disp(x)
7 or >> disp(solve('x + tan(y) = 5', 'y')) atan(5 - x)

3.4.2 Functions and Expressions

In Matlab, an expression can belong to either the string or symbolic class of data. Consider the following example:
>> f = x3 - 1;

>> f(7) ans = 1 This result may be puzzling if you are expecting f to act like a function. Since f is a string, f(7) denotes the seventh character in f, which is 1 (the spaces count). Notice that like symbolic output, string output is not indented from the left margin. This is a clue that the answer above is a string (consisting of one character) and not a floating point number. Typing f(5) would yield a minus sign and f(-1) would produce an error message.

3.4.2.a. Substitution You can substitute numerical values directly into an expression with subs. So you can solve functions by giving numerical values.

For example, >> syms a x y ; a = x^2 + y^2; subs(a, x, 2) ans = y^2 + 4 >> subs(a, [x y], [3 4]) ans = 25

For example, let f be a function as: f(x)=4x3-5x2+7x-9 and we are asked to determine f(5)=? >> syms f x ; f=4*x^3-5*x^2+7*x-9 ; subs(f,x,3)

ans = 75 Here, subs(f,x,3) is used to substitute the value required to be solved. The first character shows the function name (f), the second one denotes variable name (x), and the third one will be the value, which is written instead of the variable.

Can be done with more variables as:

F(x,y,z)= 2x2+5log(y)-8z3 , what is f(2,3,4)

>> syms f x y z ; f=2*x^2+5*log(y)-8*z^3; subs(f,[x,y,z],[2,3,4])

ans =

-498.5069

Examples on solving equations


1. Solve (symbolically) the system of linear equations 3x + 4y + 5z = 2 2x 3y + 7z= 1 x 6y + z = 3 solution: >> [x, y, z] = solve('3*x + 4*y + 5*z = 2', '2*x - 3*y + 7*z = -1', 'x - 6*y + z = 3', 'x', 'y', 'z') x= 241/92 y= -21/92 z= -91/92

2.

Try to solve the system of linear equations(HW)

3x 9y + 8z = 2 2x 3y + 7z= 1 x 6y + z = 3 3. Factor the polynomial x4 y4.

Solution: >> syms x y; factor(x^4 - y^4) ans = (x - y)*(x + y)*(x^2 + y^2)

3.4.3 Doing Calculus with Matlab Matlab has commands for most of the computations of basic calculus in its Symbolic MathToolbox. This toolbox includes part of a separate program called Maple, which processes the symbolic calculations. 3.4.3.1 Differentiation You can use diff to differentiate symbolic expressions, and also to approximate the derivative of a function given numerically (say by an M-file): > syms x; diff(x^3) ans = 3*x^2

The syntax for second derivatives is diff(f(x), 2), and for

nthderivatives ,diff(f(x), n).


>> syms x ;diff(x^3, 2)

ans =
6*x The command diff can also compute partial derivatives of expressions involving several variables, as in diff(x2*y, y), >> syms y ; diff(x^2*y, y)

ans =
x^2

but to do multiple partials with respect to mixed variables you must use diff repeatedly, as in diff(diff(sin(x*y/z), x), y). (Remember to declare y and z symbolic.) >> syms x y z; diff(diff(sin(x*y/z), x), y) ans = cos((x*y)/z)/z - (x*y*sin((x*y)/z))/z^2

3.4.3.2 Integration Matlab can compute definite and indefinite integrals. Here is an

indefinite integral:
>> int ('x^2', 'x')

ans =
x^3/3 As with diff, you can declare x to be symbolic and dispense with the character string quotes. Note that Matlab does not include a constant of integration; the output is a single antiderivative of the integrand. Now here is a definite integral:

>> syms x; int(asin(x), 0, 1)

ans =
pi/2 1 >> int ('x^2', 'x',2) ans = 8/3 - x^3/3 >> int ('x^2', 'x',2,5) ans =

39

In definite integrals, first value in the paranthesis is the function, the second one is the initial condition and the last one is the final condition of the integral. So the values given after the function is the interval of the integral and they are seperated by coma. The following command computes the double integral

>> syms x y; int(int(x^2 + y^2, y, 0, sin(x)), 0, pi)

ans =
2*pi*(2*sin((pi^2/4)^(1/2))^2 - 1)*(pi^2/4)^(1/2) + (2*(pi^2/4)^(1/2)*(4*sin(2*(pi^2/4)^(1/2))*(pi^2/4)^(1/2) 4*sin((pi^2/4)^(1/2))^2))/pi + 4/9

>> syms x y; int(int('x^2 + y^2', 'y', 0, x), 0, 3) ans =

27

Solutions : a) >> syms x; diff(6*x^3 - 5*x^2 + 2*x - 3,x) ans = 18*x^2 - 10*x + 2 b) >> diff((2*x - 1)/(x^2 + 1), x) ans =

2/(x^2 + 1) - (2*x*(2*x - 1))/(x^2 + 1)^2 >> simplify(ans)


ans =

(2*(x - x^2 + 1))/(x^2 + 1)^2

c) >> diff(sin(3*x^2 + 2), x) ans = 6*x*cos(3*x^2 + 2) e) >> diff(sqrt(1 + x^4), x) ans = (2*x^3)/(x^4 + 1)^(1/2) g) >> diff(atan(x^2 + 1), x) ans = (2*x)/((x^2 + 1)^2 + 1)

d) >> diff(asin(2*x + 3), x)


ans = 2/(1 - (2*x + 3)^2)^(1/2) f) >> syms x r ; diff(x^r, x) ans = r*x^(r - 1)

Example on integration
See if Matlab can do the following integrals symbolically. For the indefinite integrals, check the results by differentiating.

Solution: a) >> syms x; int(cos(x), x, 0, pi/2) ans = 1 b) >> syms x;int(x*sin(x^2), x) ans = -cos(x^2)/2 To check the indefinite integral, we just differentiate. >> diff(-cos(x^2)/2, x) ans =

x*sin(x^2)

c) >> syms x;int(sin(3*x)*sqrt(1 - cos(3*x)), x) ans = (2*(1 - cos(3*x))^(3/2))/9 Check;

>> diff(ans,x)
ans = sin(3*x)*(1 - cos(3*x))^(1/2)

d) >> int(x^2*sqrt(x + 4), x) ans = -(2*(x + 4)^(3/2)*(168*x - 15*(x + 4)^2 + 112))/105

>> diff(ans, x)
ans = (2*(30*x - 48)*(x + 4)^(3/2))/105 - ((x + 4)^(1/2)*(168*x - 15*(x + 4)^2 + 112))/35 >> simplify(ans) ans =

x^2*(x + 4)^(1/2)

Вам также может понравиться