Uploaded by xixav11443

FeedlabCh1

advertisement
Chapter 1
MATLAB® Preliminaries
1.1
INTRODUCTION
MATLAB® (Matrix Laboratory) is a high-level technical computing environment
developed by The Mathworks, Inc. for mathematical, scientific, and engineering
applications. It is design to perform complex, high-performance numerical analysis and
computation. This software integrates computation, visualization, and programming in an
easy-to-use environment where problems and solutions are expressed in familiar
mathematical notations. Powerful applications such as modeling, data analysis,
simulation, exploration, and visualization can be done with this tool. For these reasons,
MATLAB® has been commonly used in the analysis and design of feedback control
systems.
1.2
MATLAB® FAMILIARIZATION
When you start MATLAB®, the MATLAB® desktop appears, containing tools (graphical
user interfaces) for managing files, variables, and applications associated with MATLAB®.
The first time MATLAB® starts, the desktop appears as shown in Fig. 1.1. The following
important entities in the MATLAB® user interface are explained in detail.
Command Window
This is where you input commands like entering values in variables, or running scripts
(m-files). M-files are scripts that simply execute a series of MATLAB® statements, or they
can be functions that also accept arguments and produce outputs. The prompt >> is an
indicator where you will input values, basic expressions and scripts.
Command History
Lines you enter in the Command Window are logged in the Command History window. In
the Command History, you can view previously used functions, and copy then execute
those selected lines. The text %-- 11:18 AM 4/04/04 --% indicates the
Timestamp in which the command was executed, while the succeeding texts indicate the
commands performed on that particular time.
4
Fig. 1.1 The MATLAB® 7.0 environment.
Fig. 1.2 The Workspace Browser.
5
Workspace Browser
The MATLAB® Workspace Browser (see Fig. 1.2) consists of the set of variables (named
arrays) built up during a MATLAB® session and stored in memory. You add variables to
the workspace by using these functions, running m-files, and loading saved workspaces.
To view the workspace and information about each variable, use the Workspace Browser,
or use the functions who and whos.
Start Menu
The Start Menu consists of various MATLAB® Toolboxes and Blocksets. These toolboxes
and blocksets are used depending on a specific application, and contain various predefined functions and demos. The Control System Toolbox is used in this text.
1.3
MATLAB® FUNDAMENTALS: FUNCTIONS, EXPRESSIONS, AND
COMMANDS
Once you are familiar with the MATLAB® environment, it is time to enter basic
expressions. In the command window, all commands are straightforward; just type the
expressions such as entering values in a variable or running an m-file.
Expressions and Variables
Expressions typed without a variable name are evaluated by MATLAB® and the result is
stored and displayed by a variable called ans. The result of an expression can be assigned
to a variable name. Variable names consist of a letter, followed by any number of letters,
digits, or underscores. MATLAB® uses only the first 31 characters of a variable name and
MATLAB® is case sensitive. MATLAB® is so straightforward that you may enter also
mathematical expressions and formulas as you enter the variables. Notice that MATLAB®
display the result with 5 significant digits (default format: format short). The commands
format short e, format long, and format long e display 5 digits floating
point, 15 digits fixed point, and 15 digits floating point, respectively.
The first example shows a ‘no typed variable’ expressions, answer is automatically stored
in ans. The first expression involves direct value in a variable, while the second one
shows a direct mathematical expression using the function cos. Further explanations on
Math functions are explained in Elementary Mathematics Functions.
Listing 1.1
>> 13
ans =
13
6
>> cos(3.1416/3)
ans =
0.49999787927255
The second example shows an expression with values stored in variables a and b.
Listing 1.2
>> a= 234.56778
a =
2.3457e+002
>> b=3.1416*(cos(3.1416/6))+2
b =
4.7207e+000
In displaying answers and expressions, the % indicates that any typed expression is
converted into a comment while typing a semicolon, ;, after a mathematical expression,
omits the MATLAB® response or does not display the result. An example is shown in
basic display manipulation. The first expression does not display the value of a1 but it is
still in the workspace while the second expression is converted into a comment.
Listing 1.3
>> a1=3.5445/64;
>> % a1=3.5445/64
Using the command fprintf you can directly manipulate the format of the output of an
expression or function. This command displays the result with a desired format on the
screen or to specified filename. The %8.4f, indicates that the output value is a float
number that has 4 decimal values and has 8 characters in length, if length of characters is
less than 8 (7 in the example) the 8th would be a space. All expressions inside the single
quote sign are the ones to be displayed. The \n indicates that the next output to be
displayed (if there’s any) would be on the next line. The expression to be evaluated is
typed after the comma “,” sign.
Listing 1.4
>> fprintf('Area of a circle is %8.4f Square meters\n',
3.1416*3^2)
Area of a circle is
28.2744 Square meters
7
MATLAB® has several predefined variables and are listed in Table 1.1. You may try the
following variables in the Command Window to check their functionality. There are also
several commands that perform specific functions. These commands are listed in Table
1.2. It is recommended to try them for you to see how it works.
Table 1.1 Special variables and constants.
ans
computer
eps
i or j
inf
NaN
pi
realmax
realmin
Most recent answer
Computer type
Floating point relative accuracy
Imaginary unit
Infinity
Not-a-number
3.14159265358…… or ( S )
Largest floating point number
Smallest floating point number
Table 1.2 MATLAB® special commands.
clc
clear variable
diary
exit
help command
home
load
save
who
whos variable
Clears all input and output from the
Command Window display, giving you a
"clean
screen."
Clear the contents and the variable itself
in the workspace. Without the variable,
it clears the whole workspace
Causes a copy of all subsequent
command window input and most of the
resulting command window output to be
appended to the named file. If no file is
specified, the file 'diary' is used.
Exits MATLAB
Ask help on a particular command
Same as clc.
Read the contents of the MAT-file
saved.
Saves the workspace to a binary file
called a MAT-file, which has a .mat
extension.
Displays variables in workspace
Displays the number of elements in a
variable, if no variable is indicated, it
displays the values of each variable.
8
A sequence of characters in single quotes is called a character string or text variable.
Characters can be augmented or combined by using a vector “[‘first character’,’second
character’]” An example is shown below.
Listing 1.5
>> c='Manila'
c =
Manila
>> cs=[c,',Philippines']
cs =
Manila,Philippines
1.4
MATLAB® COMMANDS AND MATRIX FUNCTIONS
MATLAB® treats the single value element, like in the first and second example earlier on
Expressions and Variables as a single element matrix. From the word ‘MATLAB’ which
means Matrix Laboratory, it explains why values are treated as matrices. Matrices are
entered into MATLAB® by listing the elements of the matrix and enclosing them within a
pair of brackets, “[ ].” Elements of a single row are separated by commas or blanks,
and rows are separated by semicolons or carriage return.
Entering Vectors and Matrices
A single row matrix A
>4
32 31 5@ is entered in MATLAB® in two ways, either using
spaces or using commas.
Listing 1.6
>> A=[4 32 31 5]
A =
4
32
31
5
>> A=[4,32,31,5]
A =
4
32
31
5
9
ª3º
A single column matrix B «« 4 »» is entered in MATLAB® by using semicolons or carriage
«¬ 5 »¼
returns (in this example, using semicolons).
Listing 1.7
>> B=[3;4;5]
B =
3
4
5
Combining the single column and single row matrix instructions, you can create an m x n
ª1 2 º
matrix. If you want to create matrix C «
» , it is entered in MATLAB® by using spaces
¬3 4 ¼
or commas with semicolons or carriage returns, as shown below.
Listing 1.8
>> C=[1 2;3 4]
C =
1
3
2
4
The entire row or column can be addressed using colon “;”. For example, if you want to
get the first row of matrix C, follow the example below. The number 1 denotes ‘first’ and
its location tells whether it is a column or row. If the number is placed on the first
position, then it denotes that the output is an entire row and if it is placed in the second
position, it denotes an entire column. In our example, the number 1 is placed on the first
position; therefore its output is the first row. Try to interchange the colons and numbers
to see the corresponding change on the output.
Listing 1.9
>> frow=C(1,:)
frow =
1
2
>>
10
You can also address a single element in a given matrix, we know that a matrix element
can be addressed in an expression (i,j), where i is the row and j is the column of the
element. Same thing is done here in MATLAB. For example, to get the 1st row, 2nd
column element of matrix C, which is 2, see the example below.
Listing 1.10
>> f12=C(1,2)
f12 =
2
Table 1.3 Element-by-element math operations.
+
.*
./
.\
.^
.’
Addition
Subtraction
Element-by-element multiplication.
Element-by-element division.
Element-by-element left division.
Element-by-element power
Unconjugated array transpose
Matrix / Vector Basic Operations
Arithmetic operations on arrays are done element-by-element. This means that addition
and subtraction are the same for arrays and matrices, but that multiplicative and division
operations are different. Basic operations such as addition and subtraction on matrices
with the same dimensions can be done. If they are conformable, two matrices can be
multiplied and divided. For element-by-element multiplication and division or array
operations, MATLAB® uses a dot, or decimal point, as part of the notation for
multiplication and division. Element by element operations are listed in Table 1.3. Given
two matrices C and D, multiplication can be done by typing >>C*D, element by element
multiplication can be done by typing >>C.*D, >>C\D is equivalent to C-1D, and
>>C/D is equivalent to CD-1.
The inverse of a matrix, denoted by C-1 can be done by using the command >>inv(C).
An example is shown below.
11
Listing 1.11
>> C=[1 2;3 4]
C =
1
3
2
4
>> D=[5 6;7 8]
D =
5
7
6
8
>> C*D
ans =
19
43
22
50
>> C\D
ans =
-3.0000
4.0000
-4.0000
5.0000
>> inv(C)*D
ans =
-3.0000
4.0000
-4.0000
5.0000
>> C.*D
ans =
5
21
12
32
12
Transpose and Conjugate Transpose
An n vector is a row vector or a column array of n numbers. In MATLAB®, elements
enclosed by brackets and separated by semicolon generate a column vector. The
conjugate transpose of a row vector is a column vector, and vice versa. This can be done
in MATLAB® using the symbol “’” (apostrophe). An example is shown below, the
transpose of matrix D is E. If the matrix is real, the conjugate transpose is simply a
transpose.
Listing 1.12
>> E=D'
E =
5
6
7
8
Special Matrices and Matrix Manipulations
Special matrices can be generated by using the functions given in Table 1.4.
Table 1.4 Elementary matrices.
eye
meshgrid
ones
zeros
rand
randn
Identity matrix
x and y arrays for 3-D plots
Ones matrix
Zeros matrix
Uniformly distributed random numbers
Normally distributed random numbers
Information on a particular matrix can be extracted. This can aid in certain calculations
and operations. Try these commands and see how it works. See Table 1.5 for details.
Table 1.5 Basic information of a matrix.
disp
isempty
isequal
isnumeric
issparse
length
ndims
numel
size
Display array
True for empty matrix
True if arrays are identical
True for numeric arrays
True for sparse matrix
Length of vector
Number of dimensions
Number of elements
Size of matrix
13
Table 1.6 Commands for manipulating matrices.
diag
fliplr
flipud
reshape
rot90
tril
triu
:
Create or extract diagonal
Flip matrix in the left/right direction
Flip matrix in the up/down direction
change size
Rotate matrix 90 degrees
Extract lower triangular part
Extract upper triangular part
Index into matrix, rearrange matrix
Table 1.7 Some operations on matrices.
det
norm
trace
inv
eig
poly
exp
logm
sqrtm
Determinant
Matrix vector norm
Sum of diagonal elements
Matrix inverse
Eigenvalues and eigenvectors
Characteristic polynomial
Matrix exponential
Matrix logarithm
Matrix square root
Manipulation and creation of matrices can be done using the following MATLAB®
functions. See Tables 6 and 7. Try the following commands and see how it works.
Generating Sequences
Vectors can be generated by just specifying the first, last and the increment desired for
each element. For example, if you want to create a row vector with a first element of ‘1’
and a last element of ‘9’ and an increment of ‘1’, just use the syntax in the example
below. The default increment is ‘1’ so even if you omit the second parameter ‘1’,
>>F=(1:9), you still can get the same result. You may try to experiment and change
the increment, and see what happens.
Listing 1.13
>> F=(1:1:9)
F =
1
2
3
4
5
>> F=(1:9)
14
6
7
8
9
F =
1
2
3
4
5
6
7
8
9
Complex Numbers
We encounter some problems that include operations and manipulation of complex
numbers. Cases like getting the roots of a polynomial or solutions on partial fraction
expansion that involves complex roots are common. In MATLAB®, imaginary numbers
are represented using i or j. Mathematical operations are straightforward, similar to
operations in real numbers. As an example, let us perform basic operations of two
complex numbers.
Given: (25 j 65) and (30 j80) (addition and division)
Listing 1.14
>> (25+65j)+(30+80j)
%Addition
ans =
5.5000e+001 +1.4500e+002i
>> (25+65j)/(30+80j)
%Division
ans =
0.8151 - 0.0068i
We can also extract some parameters from complex numbers like phase angle and
magnitude, real part and imaginary part. As an example, we need to get the magnitude
and phase angle of the complex number 25 – j65. We have to convert the angle in degrees
so we multiplied S /180 to the answer of angle (always in radians).
Listing 1.15
>> abs(25-65i)
ans =
69.6419
>> angle(25-65i)*(180/pi)
ans =
15
-68.9625
>> real(25-65i)
ans
25
>> imag(25-65i)
ans
-65
Matrix Exponential
expm(A) is the matrix exponential of an n u n matrix A. That is,
expm( A ) I A A 2 A3
"
2! 3!
Note that a transcendental function is interpreted as a matrix function if an “m” is
appended to the function name, as in expm(A) or sqrtm(A).
Eigenvalues
The eigenvalues of a matrix A is found by using the function >>eig(A), which returns
the eigenvalues in a column vector. If A is real and symmetric, the eigenvalues will be
real. But if A is not symmetric, the eigenvalues are frequently complex in nature.
Elementary Mathematics Functions and Operators in MATLAB®
Elementary math functions and operators in MATLAB® are very easy to use since
they are basic and straightforward in nature. Basic operations like addition, subtraction,
multiplication, division can be represented by “ + , - , * , /” respectively. If you want to
raise a number to a certain exponent, just simply insert ^ after the number and before the
exponent. For example, if you want to evaluate 26, just type >>2^6. For matrices or
arrays, operations are different (for exponents, multiplication and division) as stated
earlier.
Some MATLAB® basic math functions automatically operate element by element
on an array. Functions that operate element by element are given in Table 1.8.
16
Table 1.8 Elementary math functions.
abs
acos
acosh
angle
asin
asinh
atan
atanh
conj
cos
exp
cosh
floor
fix
imag
log
log10
real
rem
round
sign
sinh
sqrt
tan
tanh
Absolute value
Inverse cosine
Inverse hyperbolic cosine
Phase angle
Inverse sine
Inverse hyperbolic sine
Inverse tangent
Inverse hyperbolic tangent
complex conjugate
Cosine
Exponential
Hyperbolic cosine
Round towards infinity
Round towards zero
Complex Imaginary part
Natural logarithm
Common logarithm
Complex real part
remainder after division
Round towards nearest integer
Signum function
Hyperbolic sine
Square root
Tangent
Hyperbolic tangent
Logical Operators
MATLAB® relational operators and logical operators also work on an element-byelement basis. Relational operators compare two scalars and produce a 1 if the operation
is true and a 0 if it is false. For example, if you enter >>t=17>55, MATLAB® will
respond with t =0. When used with two matrices, relational operators compare
corresponding matrix elements. For example, >>L = D <= X will check every element
of D against the corresponding element of X. If the element of D is less than or equal to
the corresponding element of X, the corresponding element of L will be 1. Otherwise, the
corresponding element of L will be zero. The logical operators & for logical AND, | for
logical OR, and ~ for logical NOT all return 1 for logical TRUE and 0 for logical
FALSE. An example is shown below.
Listing 1.16
>> H=[1 3 5 7 9];
>> I=[0 2 3 4 5];
>> J=[2 2 6 3 4];
17
>> lgcal1=H<I
lgcal1 =
0
0
0
0
0
1
1
1
1
1
>> lgcal2=H>I
lgcal2 =
1
1
>> lgcal3=(H>I)&(H>=J)
lgcal3 =
0
1.5
1
0
CREATING SCRIPTS AND FUNCTIONS (m-files)
Files that contain code in the MATLAB® language are called m-files. You create m-files
using a text editor, then use them as you would any other MATLAB® function or
command.
There are two kinds of m-files:
1. Scripts, which do not accept input arguments or return output arguments. They
operate on data in the workspace.
2. Functions, which can accept input arguments and return output arguments.
Internal variables are local to the function.
Creating Script Files
If you're a new MATLAB® programmer, just create the m-files that you want to try out in
the current directory. As you develop more of your own m-files, you will want to
organize them into other directories and personal toolboxes that you can add to
MATLAB® search path. If you duplicate function names, MATLAB® executes the one that
occurs first in the search path. Each script file should have a name that ends in “.m” The
commands in the script file are executed in the MATLAB® environment by simply
entering the name of the script file without the extension “.m.”
An m-file can be created by clicking >FILE>NEW>M-FILE and then a window will
appear. You may type your script or code in the m-file window. See Fig. 1.3.
18
Fig. 1.3 MATLAB® m-file editor.
Creating Functions
Function files are m-files that are very similar to script files. The first major difference is
that the first line of a function file begins with the word function, followed by a statement
identifying the name of the function and the input and output argument in the form:
function [output arguments] = function_name(input
arguments)
Control Flow
In your functions or scripts, it is common that you include control flow commands.
MATLAB® control flow is given in Table 1.9. The control flow commands for, while, and
if are statements similar to those used in many computer languages to produce
conditional statements or loops. Every for, while, and if statements must be matched
with an end statement. The break command can be used to terminate the execution of a
loop permanently. The if statement can be used in conjunction with the nargin,
19
nargout, and error functions to perform error checking of a function. Inside a
function file, nargin and nargout are equal to the number of input and output
arguments, respectively, that were used in function call. The function
error(‘message’) returns control to the keyboard and displays message. For more
information regarding the commands, please type >> help <command>.
Table 1.9 Control flow commands in MATLAB®.
break
else
elseif
and
error
for
if
return
while
1.6
Terminate execution of loop
used with if
used with if
Terminate the loop for, while, and if
statement
Display message and abort function
Repeat statement a specified number
of times
conditionally executed statements
return to invoking function
Repeat statements an indefinite
number of times
GENERATING PLOTS
MATLAB® can create high-resolution, publication-quality 2-D, 3-D, linear, log, semilog,
polar, bar chart and contour plots on plotters, dot-matrix printers, and laser printers. Some
of the 2-D graph types are plot, loglog, semilogx, semilogy, polar, and bar.
The command grid adds a grid to the graph, and the command title(‘text’),
xlabel(‘text’), ylabel(‘text’), and text(‘text’) can be used for
labeling and placing text on the graph. MATLAB® provides automatic scaling. The
function axis([xmin, xmax, ymin, ymax])enforces manual scaling.
As an example, let us plot a sinusoidal function, let y 2sin x , where x is the abscissa
(an angle) and y is the ordinate. Take note that angles are in radians. The listing is shown
below.
Listing 1.17
>> x=(0:0.002:2*pi);
>> y=2*sin(x);
>> plot(x,y); title('Sinusoidal waveform');
20
The output waveform is shown in Fig. 1.4.
Fig. 1.4 Plot of the function y = 2sinx.
1.7
OTHER MATLAB® FUNCTIONS AND COMMANDS FOR CONTROL SYSTEMS
ENGINEERING APPLICATIONS
The functions to be presented are basic and are commonly used in control systems
applications. These functions are not used directly for solving control system problems
but rather application of these commands will greatly help in solving them.
Polynomials
Polynomials can be represented as row vectors containing the coefficients. As an
example, the polynomial s 3 32s 2 32 can be represented as
Listing 1.18
>>x=[1 32 0 32]
x =
1
32
0
32
>>
The first element of the vector is the coefficient of the highest exponent while the last is
the coefficient of the lowest exponent. A ‘0’ is included because there is no s on the
polynomial. Polynomials can also be represented in a factor form of its roots such as,
21
P
s s 2 s 4 s 5 , which can be written using the function poly(), as shown
below.
Listing 1.19
>> x=poly([0 –2 4 –5])
x =
1
3
-18
-40
0
For a given characteristic polynomial, its roots can be obtained by using the function
roots().
Listing 1.20
>> roots([1 3 -18 -40 0])
ans =
0
4.0000
-5.0000
-2.0000
Two polynomials can also be multiplied and divided using the conv() and deconv()
functions.
>> x = [1 2 1];
>> y = [2 5];
>> m = conv(x,y)
m =
2
9
12
5
>> n = deconv(x,y)
n =
0.5000
-0.2500
Other important functions used in control engineering analysis and design are shown in
Table 1.10.
22
Table 1.10 Other basic functions for control engineering applications.
ilaplace
Generates the inverse-Laplace transform of a polynomial in the
s domain. (Requires Symbolic Math Toolbox)
laplace
Generates the Laplace transform of a polynomial in the time
domain. (Requires Symbolic Math Toolbox)
polyval
Polynomial evaluation.
residue
Partial fraction expansion.
1.8
MATLAB® EXERCISES
1. Generate a 1u 3 matrix whose entries are the coefficients of the polynomial
2 s 2 3s 1 .
N s
2. Generate a 1u 4 matrix whose entries are the coefficients of the polynomial
D s
s 3 6 s 2 11s 6 .
3. Determine the product N(s)D(s).
4. Assume a rational function H s
N s
, determine the partial fraction expansion of
D s
H(s).
5. Determine the poles and zeros of H(s). (Determine the roots of the numerator and
denominator polynomials.)
6. What is the value of H(s) if s = 2?
7. Generate the following matrices:
ª1 0 2 º
« 2 1 3 »
¬
¼
ª1 2 0 º
C ««0 3 0 »»
«¬0 0 2 »¼
A
B
ª 2 1 º
« 1 0»
¬
¼
D I3
If possible, determine the following:
a. AB
b. BA
e. Show that I 3C CI 3
d. AT A C
f. Eigenvalues of C
c. AT A
C.
23
1 (0.9) 2 cos t for 5 cycles.
8. Generate a plot of the function f t
9. Solve the system of linear equations
x 2 y 3z 2w 2
2 y 6w 1
2x z w 0
y 6z 1
10. Determine the rank of the coefficient matrix developed in No. 9 using the function rank.
11. Augment the constant matrix in No. 9 to the coefficient matrix also in No. 9. Determine
the Reduced Row Echelon Form of this augmented matrix by using the function rref.
What is the significance of this result?
12. Generate the vector x
>0
0 0 1 1 2 2 0 0 0@ without typing the entries
manually, and by using the functions ones and zeros only.
13. Determine the size of the matrix generated in No. 9 using the function size.
14. Determine the length of the matrix generated in No. 9 using the function length.
15. What is the difference between size and length?
24
Download