Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Feedlab CH 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

4

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.
5
Fig. 1.1 The MATLAB 7.0 environment.
Fig. 1.2 The Workspace Browser.
6
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 pre-
defined 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
7
>> 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 theres 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
8
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 Most recent answer
computer Computer type
eps Floating point relative accuracy
i or j Imaginary unit
inf Infinity
NaN Not-a-number
pi 3.14159265358 or (t )
realmax Largest floating point number
realmin Smallest floating point number
Table 1.2 MATLAB special commands.
clc Clears all input and output from the
Command Window display, giving you a
"clean
screen."
clear variable Clear the contents and the variable itself
in the workspace. Without the variable,
it clears the whole workspace
diary 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.
exit Exits MATLAB
help command Ask help on a particular command
home
Same as clc.
load Read the contents of the MAT-file
saved.
save Saves the workspace to a binary file
called a MAT-file, which has a .mat
extension.
who Displays variables in workspace
whos variable Displays the number of elements in a
variable, if no variable is indicated, it
displays the values of each variable.
9
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
| |
4 32 31 5 A = 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
10
A single column matrix
3
4
5
B
(
(
=
(
(

is entered in MATLAB by using semicolons or carriage
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
matrix. If you want to create matrix
1 2
3 4
C
(
=
(

, it is entered in MATLAB by using spaces
or commas with semicolons or carriage returns, as shown below.
Listing 1.8
>> C=[1 2;3 4]
C =
1 2
3 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
>>
11
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 1
st
row, 2
nd
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
-1
D, 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.
12
Listing 1.11
>> C=[1 2;3 4]
C =
1 2
3 4
>> D=[5 6;7 8]
D =
5 6
7 8
>> C*D
ans =
19 22
43 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 12
21 32
13
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 7
6 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 Identity matrix
meshgrid x and y arrays for 3-D plots
ones Ones matrix
zeros Zeros matrix
rand Uniformly distributed random numbers
randn 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 Display array
isempty True for empty matrix
isequal True if arrays are identical
isnumeric True for numeric arrays
issparse True for sparse matrix
length Length of vector
ndims Number of dimensions
numel Number of elements
size Size of matrix
14
Table 1.6 Commands for manipulating matrices.
diag Create or extract diagonal
fliplr Flip matrix in the left/right direction
flipud Flip matrix in the up/down direction
reshape change size
rot90 Rotate matrix 90 degrees
tril Extract lower triangular part
triu Extract upper triangular part
: Index into matrix, rearrange matrix
Table 1.7 Some operations on matrices.
det Determinant
norm Matrix vector norm
trace Sum of diagonal elements
inv Matrix inverse
eig Eigenvalues and eigenvectors
poly Characteristic polynomial
exp Matrix exponential
logm Matrix logarithm
sqrtm 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 6 7 8 9
>> F=(1:9)
15
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 65) j + and (30 80) j + (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 /180 t to the answer of angle (always in radians).
Listing 1.15
>> abs(25-65i)
ans =
69.6419
>> angle(25-65i)*(180/pi)
ans =
16
-68.9625
>> real(25-65i)
ans
25
>> imag(25-65i)
ans
-65
Matrix Exponential
expm(A) is the matrix exponential of an n n matrix A. That is,
2 3
expm( )
2! 3!
= + + + +
A A
A I A "
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 2
6
, 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.
17
Table 1.8 Elementary math functions.
abs Absolute value
acos Inverse cosine
acosh Inverse hyperbolic cosine
angle Phase angle
asin Inverse sine
asinh Inverse hyperbolic sine
atan Inverse tangent
atanh Inverse hyperbolic tangent
conj complex conjugate
cos Cosine
exp Exponential
cosh Hyperbolic cosine
floor Round towards infinity
fix Round towards zero
imag Complex Imaginary part
log Natural logarithm
log10 Common logarithm
real Complex real part
rem remainder after division
round Round towards nearest integer
sign Signum function
sinh Hyperbolic sine
sqrt Square root
tan Tangent
tanh Hyperbolic tangent
Logical Operators
MATLAB relational operators and logical operators also work on an element-by-
element 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];
18
>> lgcal1=H<I
lgcal1 =
0 0 0 0 0
>> lgcal2=H>I
lgcal2 =
1 1 1 1 1
>> lgcal3=(H>I)&(H>=J)
lgcal3 =
0 1 0 1 1
1.5 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.
19
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,
20
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 Terminate execution of loop
else used with if
elseif used with if
and Terminate the loop for, while, and if
statement
error Display message and abort function
for Repeat statement a specified number
of times
if conditionally executed statements
return return to invoking function
while Repeat statements an indefinite
number of times
1.6 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 2sin y 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');
21
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
3 2
32 32 s s + + 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,
22
( )( )( ) 2 4 5 P s s s s = + + , 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.
23
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 1 3 matrix whose entries are the coefficients of the polynomial
( )
2
2 3 1 N s s s = + .
2. Generate a 1 4 matrix whose entries are the coefficients of the polynomial
( )
3 2
6 11 6 D s s s s = + + .
3. Determine the product N(s)D(s).
4. Assume a rational function ( )
( )
( )
N s
H s
D s
= , determine the partial fraction expansion of
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
(
=
(


A
2 1
1 0
(
=
(

B
1 2 0
0 3 0
0 0 2
(
(
=
(
(

C
3
= D I
If possible, determine the following:
a. AB b. BA c.
T
A A d.
T
+ A A C
e. Show that
3 3
= = I C CI C. f. Eigenvalues of C
24
8. Generate a plot of the function ( ) ( )
2
1 (0.9) cos f t t = for 5 cycles.
9. Solve the system of linear equations
2 3 2 2 x y z w + + =
2 6 1 y w + =
2 0 x z w + =
6 1 y z =
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
| |
0 0 0 1 1 2 2 0 0 0 x = 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?

You might also like