Professional Documents
Culture Documents
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
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
Communications Toolbox Design and analyze algorithms for the physical layer of communication systems
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
Image Processing Image Processing Toolbox Perform image processing, analysis, and algorithm development
Image Acquisition Toolbox Acquire images and video from industry-standard hardware
Computational Biology Bioinformatics Toolbox Read, analyze, and visualize genomic, proteomic, and microarray data
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
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
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 Report Generator Generate documentation for Simulink and Stateflow models
Fixed-Point Modeling Simulink Fixed Point Design and simulate fixed-point systems
Simulation Graphics Simulink 3D Animation Animate and visualize Simulink models in three dimensions
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
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
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
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
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
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
+ 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.
.'
8 10
ans = 0 4 16 36 64 100
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
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
sin
tan exp log log10
Sine function
Tangent function Exponential function Natural function Logaritm base 10
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
Application of Build in functions and some command to row Matrix: sort(W) ans =
-3
-2
min(W) ans = -3
max(W) ans = 8
mean(W) ans = 3
Columns 4 through 6
2.0794 1.3863 1.0986 + 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
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
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
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
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.
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
Cross
Dot Sum Sort
Det
Rank nv Eig
Matrix determinant
Rank of matrix Matrix inverse Eigenvalues and eigenvectors
Sqrtm
Expm Logm
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
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.
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)
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
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
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 ];
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.
>> 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.
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:
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
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,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.
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
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.
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 ];
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.
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,
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
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:
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
>> 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
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
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).
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
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)
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.
ans =
-498.5069
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
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:
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
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
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 =
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)
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)
>> diff(ans,x)
ans = sin(3*x)*(1 - cos(3*x))^(1/2)
>> 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)