MATLAB Notes..
MATLAB Notes..
In Out
&Blocksets Simulink Block Library
Toolboxes Demos
Copyright (c) 199097 by The MathWorks, Inc.
MATLAB استخدام
Starting & Ending MATLAB )1بدء البرنامج وإنهائه
لبدء استخدام البرنامج انقر علي أيقونة MATLABللخروج من البرنامج انقر
علي أيقونة Exitفي قائمة الملفات.
The Command Window )2استخدام نافذة الوامر
نافذة الوامر هي النافذة الرئيسية التي من خللها يتم التصال بالمترجم
Interpreterوتجرى فيها جميع العمليات الحسابية .يظهر المترجم العلمة
(>>) كدليل على جاهز يته لتقبل الوامر .
)3كتابة اسطر الوامر Command Line Editing
↑ .Recall previous line استدعاء السطر السابق ← ctrl Move left one word تحرك إلي اليسار كلمة
واحد
↓ Recall next line استدعاء السطر قبل home Move to beginning of line تحرك إلي بداية السطر
السابق
← .Move back one character تحرك إلي الخلف حرف end Move to end of line تحرك إلي نهاية السطر
واحد
→ .Move forward one character تحرك إلي المام حرف esc clear line لحذف السطر
واحد
→ ctrl Move right one word تحرك إلي اليمين كلمة del delete character at cursor لحذف حرف عند
واحد المشيرة
.Matrix manipulation
.reshape - Change size .flipdim - Flip matrix along specified dimension
.diag - Diagonal matrices and diagonals of matrix .rot90 - Rotate matrix 90 degrees
.tril - Extract lower triangular part .find - Find indices of nonzero elements
.triu - Extract upper triangular part .end - Last index
.fliplr - Flip matrix in left/right direction .sub2ind - Linear index from multiple subscripts
.flipud - Flip matrix in up/down direction .ind2sub - Multiple subscripts from linear index
.Complex
.abs - Absolute value .real - Complex real part
.angle - Phase angle .unwrap - Unwrap phase angle
.conj - Complex conjugate .isreal - True for real array
.imag - Complex imaginary part .Cplxpair -Sort numbers into complex conjugate pairs
.ceil - Round towards plus infinity
.Rounding and remainder .round - Round towards nearest integer
.fix - Round towards zero .)mod - Modulus )signed remainder after division
.floor - Round towards minus infinity .rem - Remainder after division
.sign - Signum
.Linear equations.
."and / - Linear equation solution; use "help slash \ .cholinc - Incomplete Cholesky factorization
.inv - Matrix inverse .lu - LU factorization
COND - CONDITION NUMBER WITH .luinc - Incomplete LU factorization
.RESPECT TO INVERSION .qr - Orthogonal-triangular decomposition
.condest - 1-norm condition number estimate .nnls - Non-negative least-squares
.chol - Cholesky factorization .pinv - Pseudoinverse
.lscov - Least squares with known covariance
.Matrix functions
.expm - Matrix exponential .sqrtm - Matrix square root
.logm - Matrix logarithm .funm - Evaluate general matrix function
Factorization utilities
.qrdelete - Delete column from QR factorization .cdf2rdf -Complex diagonal form to real block diagonal form
.qrinsert - Insert column in QR factorization .balance -Diagonal scaling to improve eigenvalue accuracy
RSF2CSF -REAL BLOCK DIAGONAL FORM TO .planerot - Given's plane rotation
.COMPLEX DIAGONAL FORM
.Polynomials
.roots - Find polynomial roots .)residue - Partial-fraction expansion )residues
.poly - Convert roots to polynomial .polyfit - Fit polynomial to data
.polyval - Evaluate polynomial .polyder - Differentiate polynomial
POLYVALM - EVALUATE POLYNOMIAL .conv - Multiply polynomials
.WITH MATRIX ARGUMENT .deconv - Divide polynomials
.Plotting
.ezplot - Easy to use function plotter. fplot - Plot function
.Graph annotation
.legend - Graph legend .ylabel - Y-axis label
.title - Graph title .text - Text annotation
.xlabel - X-axis label .gtext - Place text with mouse
.Color control
.colormap - Color look-up table .hidden - Mesh hidden line removal mode
.caxis - Pseudocolor axis scaling .brighten - Brighten or darken color map
.shading - Color shading mode
.Lighting
.surfl - 3-D shaded surface with lighting .specular - Specular reflectance
.lighting - Lighting mode .diffuse - Diffuse reflectance
.material - Material reflectance mode .surfnorm - Surface normals
.Specialized graphs
.Specialized 2-D graphs
=X
7 2 9
10 7 4
8 12 5
=Y
8 1 6
3 5 7
4 9 2
w=v+s
=w
9 7 6
Vector Products and Transpose ضرب المصفوفات ومقلوبها
A row vector and a column vector of the same length can be multiplied in
either order. The result is either a scalar, the inner product, or a matrix, the
.outer product
x = v*u
=x
2
X = u*v
=X
3— 0 6
1— 0 2
4— 0 8
Matrix transposition مقلوب المصفوفة
'X = B
=X
438
951
276
'x = v
=x
2
0
1—
For a complex vector or matrix, z, the quantity z' denotes the complex
conjugate transpose. The unconjugated complex transpose is denoted by z.',
in analogy with the other array operations. So if
[z = [1+2i 3+4i
then z' is
2i—1
4i—3
while z.' is
1+2i
3+4i
For complex vectors, the two scalar products x'*y and y'*x are complex
conjugates of each other and the scalar product x'*x of a complex vector
with
.itself is real
X = A*B
=X
15 15 15
26 38 26
39 70 41
Y = B*A
=Y
47 28 15
60 34 15
43 28 15
A matrix can be multiplied on the right by a column vector and on the left by
.a row vector
x = A*u
=x
8
17
30
y = v*B
=y
10 7— 12
اذا كانت yكمية متجهة فان المر )plot)yينتج عنه رسم بياني ل yكدالة في
الزمن اما المر )plot)x,yفينتج عنه الرسم البياني yو xمثل ليجاد الرسم
البياني للدالة )y = sin)tمن 0الى π 2نجري العملية التالية:
;t = 0:pi/100:2*pi
;)y = sin)t
)plot)t,y
)'plot)x,y,'color_style_marker
:لختيار اللون نختار الحرف التالية
.'y', 'r', 'g', 'b', 'w', and 'k')اسود-ابيض-ازرق- اخضر, احمر,( اصفر
) .– : – – –( :لختيار نوع الخط نختار الرموز التالية
مثال
)'+:plot)x,y,'y
;)X,Y] = meshgrid)–8:.5:8]
;R = sqrt)X.^2 + Y.^2( + eps
;Z = sin)R(./R
)mesh)X,Y,Z
In this example, R is the distance from origin, which is at the center of the
.matrix
.Adding eps avoids the indeterminate 0/0 at the origin
Printing Graphics
The Print option on the File menu and the print command both print
.MATLAB figures
MORE ABOUT MATRICES AND ARRAYS
This sections shows you more about working with matrices and arrays,
focusing on
Linear Algebra
Informally, the terms matrix and array are often used interchangeably. More
precisely, a matrix is a two-dimensional numeric array that represents a
linear transformation. The mathematical operations defined on matrices are
the subject of linear algebra. Dürer’s magic square
=A
13 2 3 16
8 11 10 5
12 7 6 9
1 14 15 4
provides several examples that give a taste of MATLAB matrix operations.
You’ve already seen the matrix transpose, A'. Adding a matrix to its
.transpose produces a symmetric matrix
'A + A
= ans
17 11 8 32
23 17 20 8
26 14 17 11
2 26 23 17
The multiplication symbol, *, denotes the matrix multiplication involving
inner products between rows and columns. Multiplying a matrix by its
.transpose also produces a symmetric matrix
A'*A
= ans
360 206 212 378
206 368 370 212
212 370 368 206
378 212 206 360
PARTIAL-FRACTION EXPANSION WITH MATLAB
MATLAB has a command to obtain the partial-fraction expansion of
B(s)/A(s). Consider the transfer function
where some of ai and bj may be zero. In MATLAB row vectors num and den
specify the coefficients of the numerator and denominator of the transfer
,function. That is
)r,p,k] = residue)num,den]
B) s( r )1( r )2( r ) n(
= + + .... + + k )s(
A) s( s − p )1( s − p )2( s − p ) n(
B) s( a1 a2 an
= + + .... +
A) s( s + p1 s + p2 s + pn
we note that p)1( = -p1, p)2( = -p2 ,....... p(n) = -pn; r)1(= a1, r(2) = a2,….. r(n)
= an
B ) s( 2 s 3 + 5s 2 + 3s + 6
=
A) s( s 3 + 6 s 2 + 11s + 6
num = [2 5 3 61
[den = [1 6 11 6
)r;p,k] = residue)num,den]
:The command gives the following result
)r,p,k] = residue)nurn,den]
r= -6.0000
4.0000-
3.0000
p= -3.0000
2.0000-
1.0000-
= 2k
Note that the residues are returned in column vector r, the pole locations in(
).column vector p, and the direct term in row vector k
)num1den] = residue)r;p,k]
where r, p and k are as given in the previous MATLAB output, converts the
:partial-fraction expansion back to the polynomial ratio B(s)/A(s), as follows
)num,den] = residue)r,p,k]
= num
6.0000 3.0000 5.0000 2.0000
= den
6.0000 11.0000 6.0000 1.0000
Note that if p)j( = p)j + 1( =…..= p)j + m - 1( [that is,pj = pj+1 =…= pj+m-1], the
pole p)j( is a pole of multiplicity m. In such a case, the expansion includes
terms of the form
… B)s( = s 2 +2s + 3 = s2 + 2s + 3
A)s( )s + 1(3 s3 + 3s2 + 3s + 1
[num = [0 1 2 3
[den = [1 3 3 1
The command
)r,p,k] = residue)num,den]
.gives the result shown below
;[num = [0 1 2 3
;[den = [1 3 3 1
)r,p,k] = residue)num,den]
=r
1.0000
0.0000
2.0000
=p
1.0000-
1.0000-
1.0000-
=k
[]
And it is the MATLAB representation of the following partial-fraction
:(expansion of B(s)/A(s
B) s( 1 0 2
= + +
A) s ( s + 1 ) s + 1( 2
) s + 1(3
C ) s( 25
= 2
R) s( s + 4s + 25
)1(
This system is represented as two arrays each containing the coefficients of
the polynomials in decreasing powers of s as follows
num = [0 0 251
[den = [1 4 25
Note that zeros are padded where necessary. If num and den )the numerator
and denominator of the closed-loop transfer function( are known, commands
such as
)step)num,den,t step)num,den(,
will generate plots of unit-step responses. )t in the step command is the user-
specified time.( For a control system defined in a state-space form, where
state matrix A, control matrix B, output matrix C, and direct transmission
matrix D of state-space equations are known, the command
)step)A,B,C,D
will generate plots of unit-step responses. The time vector is automatically
determined when t is not explicitly included in the step commands Note that
when step commands have left-hand arguments such as
)y,x,t] = step)nun,den,t]
)y,x,tl = step)A,B,C,D,iu]
)Iy,x,tj = slep)A,B,C,D,iu,t
no plot is shown on the screen. Hence it is necessary to use a plot command
to see the response curves. The matrices y and x contain the output and state
response of the system, respectively, evaluated at the computation time
points t. )y has as many columns as outputs and one row for each element in
t. x has as many columns as states and one row for each element in t.( Note
in Equation )2( that the scalar U is an index into the inputs of the system and
specifies which input is to be used for the response. and t is the user-
specified time. If the system involves multiple inputs and multiple output the
step command, such as given by Equation )4-39(, produces a series of step
response plots, one for each input and output combination of
x =Ax+Bu
y = Cx + Du
;[num= [0 0 25
;[den = [1 4 25
)step)num,den
grid
)')title )'Unit-step Response of G)s(=25/)s^2+4s+25
x1' 0 1 x1 0
'= x + 1u
x
2 − 1 − 1 2
x
y = [1 0] 1 + [ 0]u
x2
;[A = [0 1;-1 -1
;B = [0;1l
;[C= [1 0
;[D = [0
;)impulse)A,B,C,D
;grid
)'title)'Unit-Impulse Response
:Example : Obtain the unit-impulse response of the following system
C )s( 1
= G )s( = 2
R) s( s + 0.2 s + 1
;[num= [0 0 1
;[den = [1 0.2 1
)impulse)num,den
grid
)')title )'Unit- impulse Response of G)s(=1/)s^2+0.2s+1
Example:Consider the impulse response of the standard second-order
system defined by
C ) s( ω n2
= G )s( = 2
R) s( s + 2ξω n s + ω n
ωn2 ω n2 s 1
C ) s( = 2 = 2
s + 2ξω n s + ω n s + 2ξω n s + ω n s
s 1
C ) s( =
s 2 + 2ξs + 1 s
Consider five different values of zeta: ξ = 0.1, 0.3, 0.5, 0.7, and 1.0. Obtain
.the unit-impulse response curves for each zeta with MATLAB
Solution. A MATLAB program for plotting the five unit-impulse response
curves in one diagram is
;[Num=[0 1 0
;[den=[1 0.2 1
;t=0:0.1:10
;)step)num,den1,t
)'text)2.2,0.88,'zeta=0.1
hold
;[den2= [1 0.6 1]; den3= [1 1 1]; den4= [1 1.4 1]; den5= [1 2 1
;)step)num,den2,t
)'text)1.33,0.72.'0.3
;)step)num,den3,t
)'text)1.15,0.58.'0.5
;)step)num,den4,t
)'text)1.1,0.46.'0.7
;)step)num,den5,t
)'text)0.8,0.28.'1.0
grid
)'[title)Impulse-responseCurves for G)s(=1/[s^2+2)zeta(s+1
hold
From the unit-impulse response curves for different values of zeta, we may
conclude that if the impulse response c(r) does not change sign the system is
either critically damped or overdamped, in which case the corresponding
step response does not overshoot, but increases or decreases monotonically
.and approaches a constant value
:Case l
C )s( 1
= G)s( = 2 :)J=1, b=0.5, Kp=1 )system 1
D) s( s + 0 .5 s + 1
:Case 2
C ) s( 1
= G ) s( = 2 :)J = 1, b = 0.5, Kp = 4 )system 2
D) s( s + 0.5s + 4
[num1 = [0 0 1
[den1= [1 0. 5 1
For system 2
[num2 = [0 0 1
[den2 = [1 0.5 4
;[num 1 = [0 0 1
;[den1 = [1 0.5 1
;[num2 [0 0 1
;[den2 [1 0.5 4
;t = 0:0.1:20
;)y1,x1,t] = step)num l, den l, t]
;)y2,x2,t] = step)num 2,den2,t]
)plot)t,yl,t,y2
grid
'
)'text)1 1,0.75,'System 1'(, text )11.2,0.1 6, System 2
)''title)'Step Responses of Two Systems
)'xlabel)'t Sec
t
)'ylalbel) outputs yl and y2
Plotting root loci with MATLAB. In plotting root loci with MATLAB we
deal
K ) s + z1 () s + z 2 (....) s + z m (
1+ =0
) s + p1 () s + p 2 (.....) s + p n (
num
1+ K =0
den
Note that both vectors num and den must be written in descending powers of
s A MATLAB command commonly used for plotting root loci is
)rlocus)num,den
Using this command, the root-locus plot is drawn on the screen. The gain
vector K is automatically determined. The command rlocus works for both
continuous- and discrete-time systems. For the systems defined in state
space, rlocus)A, B,C, D( plots the root locus of the system with the gain
vector automatically determined. Note that commands
rlocus)num,den,K( and rlocus)A,B,C,D,K( use the user-supplied gain vector
K. )The vector Kcontains all the gain values for which the closed-loop poles
are to be computed.( If invoked with left-hand arguments
)r,K] = rlocus)num,den]
)r,K] = rlocus)num,den,K]
)r,KI = rlocus)A,B,C,D]
)r,Kl = rlocus)A,B,C,D,K]
the screen will show the matrix r and gain vector K. )r has length K rows and
length den - 1 columns containing the complex root locations. Each row of
the matrix corresponds to a gain from vector K.( The plot command plot)r,' '(
plots the root loci. If it is desired to plot the root loci with marks '0'' or 'x', it
:is necessary to use the following command
)r = rlocus)num,den
)'pIot)r,'x or pIot)r,'o'(
EXAMPLE Consider the control system shown below. To plot the root-
locus
Define
[a = s)s +4( = s2 + 4s : a = [1 4 0
[b= s+6 : b= [1 6
2
[c = s + 1.4s + 1 : c= [1 1.4 1
;[a = [1 4 0
;[b = [1 6
;[c = [1 1.4 1
)d = conv)a,b
=d
0 24 10 1
)e = conv)c,d
=e
0 24.0000 43.6000 39.0000 11.4000 1.0000
To find the open-loop zeros of the given transfer function, we may use the
:following roots command
[p = [1 2 4
)r = roots)p
=r
1.7321I + 1.0000-
1.7321I - 1.0000-
)q = roots)c
=q
0.7141i + 0.7000-
0.7141i - 0.7000-
: EXAMPLE
Consider the system shown below, where the open-loop transfer function
G(s)H(s) is
K ) s + 0.2(
G ) s ( H ) s( =
s 2 ) s + 3.6(
;[num = [0 0 1 0.2
;[den = [1 3.6 0 0
)rlocus)num,den
)v= [-4 2 -4 4]; axis)v
grid
)'[)title)~Root-Locus Plot of G)s( = K)s + 0.2(/[s^2)s + 3.6
The resulting root-locus plot is
EXAMPLE
.Consider the system shown
Plot root loci with a square aspect ratio so that a line with slope 1 is a true
.450 line
To set the plot region on the screen to be square, enter the command
axis)'square'(. With this command, a line with slope 1 is at a true 45º, not
skewed by the irregular shape of the screen. MATLAB Program which
. produces a root-locus plot in a square region is
;[num = [0 0 0 1 1
;[3 12 -16 0 den = [1
{rlocus)num,den
)61; axis)v(;axis)'square1 6 -6 v = [-6
grid
)'[)title)'Root-Locus Plot of G)s( = K)s + 1 (/[s)s - 1 ()s^2 + 4s + 1 6
. The resulting plot is
: EXAMPLE
Consider the system whose open-loop transfer function G)s(H)s( is
K K
G ) s ( H ) s( = =
s ) s + 0.5() s + 0.6 s + 10(
2
s + 1.1s + 10.3s 2 + 5s (
4 3
MATLAB Program
;[num=[0 0 0 0 1
;[den = [1 1.1 10.3 5 0
)rlocus)n urn , den
grid
)'[)title)'
Root-Locus Plot of G)s( = K/[s{s + 0.5()s^2 + 0.6s + 10
.the root-locus plot
MATLAB Program
;num = [0 0 1 0.41
;[den = [1 3.6 0 0
;{rlocus)num,den
)V = [-5 1 -3 3]; axis)v
grid
))'[)title)' Root-Locus Plot of C)s( = K)s + O.4)/[s^2(s + 3.6
The command bode computes magnitudes and phase angles of the frequency
response of continuous-time, linear, time-invariant systems. When the
command bode )without left-hand arguments( is entered in the computer,
MATLAB produces a Bode plot on the screen. When invoked with left-band
arguments, [mag,phase,w] = bode)num,den,w( bode returns the frequency
response of the system in matrices mag, phase and w- No plot is drawn on
the screen-The matrices mag and phase contain magnitudes and phase angles
of the frequency response of the system evaluated at user specified
frequency points. The phase angle is returned in degrees. The magnitude can
be converted to decibels with the statement magdB = 20*Iogl0)mag( To
specify the frequency range, use the command Iogspace)d1 ,d2( or Iogspace
)d1 ,d2,n(. logspace)dl ,d2( generates a vector of 50 points logarithmically
equally spaced between decades 10d1 and 10d2. That is, to generate 50 points
.)between 0.1 rad/sec and100 rad/sec, enter the command w = logspace)-1,2
logspace)d1 ,d2,n( generates n points logarithmically equally spaced
between decades 10d1 and 10d2 For example, to generate100 points between 1
rad/sec and 1000 rad/sec, enter the following command: w =
Iogspace)0,3,100( To incorporate these frequency points when plotting Bode
diagrams, use the command bode)num,den,w( or bode)A,B,C,D,iu,w(.These
.commands use the user-specified frequency vector w
:Example1
25
G)s( =
s + 4 s + 25
2
Plot a Bode diagram for this transfer function. When the system is defined in
the form
use the command bode)num,den( to draw the Bode diagram. [when the
numerator and denominator contain the polynomial coefficients in
descending powers of s, bode)num,den( draws the Bode diagram.]
.MATLAB Program to plot the Bode diagram for this system is
)num [0 0 25
,[den [1 4 25
)bode)num,den
[subplot[2 1 1
)')title)' Bode Diagram of G)s(=25/)s^2+4s+25
9) s 2 + 0.2 s + 1(
G)s( =
s) s 2 + 1.2 s + 9(
.MATLAB Program
[num = [0 9 1.8 9
;[den =[1 1.2 9 0
)bode)num,den
;)subpIot)2,1,1
) )'[)title)'Bode Diagram of G)s( = 9)s^2 + 0.2s+1(/[s)s^2+1.2s + 9
X' = Ax + Bu
y = Cx + Du
where
)x = state vector )n-vector
)y = output vector )m-vector
)u = control vector )r-vector
)A = state matrix (n x n matrix
)B = control matrix (n x r matrix
)C = output matrix (m x n matrix
)D = direct transmission matrix (m x r matrix
A Bode diagram for this system may be obtained by entering the command
)bode)A,B,C,D( or bode)A,B,C,D,iu
The command bode)A,B,C,D( produces a series of Bode plots, one for each
input of the system, with the frequency range automatically determined.
)More points are used when the response is changing rapidly.( The command
bode)A, B,C,D,iu( where iu is the ith input of the system, produces the Bode
diagrams from the input iu to all the outputs )y1, y2,---, ym) of the system,
with frequency range automatically determined. )The scalar iu is an index
into the inputs of the system and specifies which input is to be used for
plotting Bode diagrams(. If the control vector u has three inputs such that
u1
u = u 2
u 3
then iu must be set to either 1,2, or 3. If the system has only one input u,then
:either of the following commands may be used
)bode)A,B,C,D( or bode)A,B,C,D,1
x1' 0 1 x1 0
'= + u
x 2 − 25 − 4 x 2 25
x
y = [1 0] 1
x2
This system has one input u and one output y. Then the MATLAB Program
:is
;[A = [0 1; -25 -4
;[B = [0;25
;[C = [1 0
;[D = [0
)Bode)A,B,C,D
;)Subplot)2,1,1
)'Title)'Bode Diagram