Post on 24-Aug-2014
transcript
1
Matlab
* Getting Started
* Plotting
* Number formatting
* File Management
* Symbolic calc
* Laplace transform
* State space
* Transfer function
* LTI & Root Locus
* Bode and Nyquist
* Side Notes
Simulink
* Simulink Basics
* Examples
Other Tutorials
> Ansys
> Pro/Mechanica
More...
> About this site
> Other sites
>
M
E
N
U
>
Introduction
MATLAB (Matrix Laboratory), a product of Mathworks, is a scientific software package designed to
provide integrated numeric computation and graphics visualization in high-level programming
language. MATLAB program consists of standard and specialized toolboxes allowing users to take
advantage of the matrix algorithm based on LINPACK1 and EISPACK2 projects. MATLAB offers
interactive features allowing the users great flexibility in the manipulation of data and in the form of
matrix arrays for computation and visualization. MATLAB inputs can be entered at the "command
line" or from "mfiles", which contains a programming-like set of instructions to be executed by
MATLAB. In the aspect of programming, MATLAB works differently from FORTRAN, C, or Basic, e.g.
no dimensioning required for matrix arrays and no object code file generated. MATLAB offers some
standard toolboxes and many optional toolboxes (at extra cost, of course!) such as financial toolbox
and statistics toolbox. Users may create their own toolboxes consisted of "mfiles" written for specific
applications. The original version of MATLAB was written in FORTRAN but later was rewritten in C.
You are encouraged to use MATLAB's on-line help files for functions and commands associated with
available toolboxes. MATLAB consists of a collection of toolboxes. These toolboxes contain library
files called M-Files, which are also functions or command names, executable from the Command
window.
Conventions Used in This Tutorial
Bold face: signifies a command or string of commands to be entered exactly as shown, a
display by Matlab echo, or a Matlab reserved word, e.g., function name, command, etc. It also
represents a keyboard command, e.g. CTRL+Q, or menu selection sequence when used with
">" sign.
Italic: when used with a command, it signifies an input to be specifed by the user. For example,
eig(matrix name) means a user-defined matrix (variable) to be entered in place of matrix
name.
Getting Started
To start Matlab in an Unix or Linux shell, enter matlab at system prompt.
To start Matlab in Windows environment, select the executable file located at:
> All Programs > Matlab > R2008a > Matlab R2008a
Alternately you may double-click on Matlab icon located on the desktop.
2
Once Matlab's initializing process is completed, a Matlab desktop environment will appear providing a
set of subwindows, a.k.a browsers. In this desktop environment you may define variables, manage
files and objects, execute programs, and view command history.
A typical Matlab desktop is shown below.
Workspace window displays the defined variables. You may also list all defined variables in a Matlab
session by issuing the command who in Command Window. The "traditional" Command window is
where the user normally defines variables and enters Matlab pre-defined functions. You may close,
restore, and resize any of these windows.
Defining Variables...
One of the easy ways to learn MATLAB is to understand how MATLAB handles matrices. Think in
terms of arrays and vectors when you work with MATLAB. For example, an array of data A = 1, 0, 9,
11, 5 is a 1x5 matrix, and a scalar number 9 is an 1x1 matrix. To store the array A in MATLAB, at
the command prompt >> (in Command window), enter:
MATLAB will display or echo your input:
To suppress the echo, add a ";" at the end of the input line.
To verify the size of the input array or matrix, use the command "size" as shown below:
,
which verifies the dimension of matrix A as 1x5 (one row and five columns).
In MATLAB, rows are separated by ";" and columns are separated by ",". For example, a 3x5 matrix
B with the following elements:
first row: 1, 0, 9, 4, 3
second row: 0, 8, 4, 2, 7
third row: 14, 90, 0, 43, 25
would be entered in MATLAB as follow:
3
Note that you may use a space in place of the comma in separating the column entries.
You may add, subtract, multiply, and divide matrices with simple operation in MATLAB. Please keep
in mind of the rules concerning matrix operations such as the computability issue, e.g., you may not
multiply a 2x3 matrix by a 4x2 matrix - the dimensions must agree.
You may extract a certain group or element from an existing matrix. Say you wish to create a new
array C from the second row of matrix B. Specify the row number and ":" for all columns in that row
as shown below:
Similarly, You may also form a matrix from the element of an existing matrix:
Here, a square matrix D has been created from the specified elements of matrix B.
You may also delete rows and columns from a matrix using a pair of square brackets. For example,
to delete the third column of matrix B, you simply enter
and MATLAB will return:
Note that the column 3 is excluded.
Alternately, you may define these variables (matrices) by clicking on the New Variable icon in
Workspace browser as shown below.
Once a variable name is entered, you may double click on the icon associated with the variable name
(in Workspace browser) to bring up the Array Editor. From the Array Editor, you may enter the
values as you would in a typical spreadsheet program like Excel.
4
You may create a new variable from selected elements of the existing array by highlighting the group
of elements you wish to use, then right-click with the cursor pointing in the selected area to bring up
the context menu. Select the Create Variable from Selection choice. Matlab will assign an
"unnamed" label to your new varible. To modify this, right-click the unnamed variable and select
Rename from the pop-up menu.
Data from the Array Editor browser could be exchanged with OpenOffice Calc spreadsheet program
via the clipboard. (OpenOffice works fine for me in both Windows and Linux environments. I don't
use Excel but I believe the file I/O interface with Excel is supported by Matlab 7 and R2006a).
Working with Arrays...
MATLAB treats arithmetic operations on arrays in an element-by-element manner. This operation is
accomplished by including a dot or a period before the arithmetic operator such as multiplication,
division, etc. The table below gives a list of such operators with examples of how these operators are
being used.
For examples in the table below, the following matrices are used:
Operation Description Example (MATLAB actual inputs and outputs)
+ Addition
- Substraction
5
* Multiplication
.*
Element-by-element
multiplication.
Note that this is different from
multiplication of two matrices.
Note that this is not the same as C = A*B
/
Right matrix division.
Dividing matrix B into matrix A
\
Left matrix division.
Dividing A into B. This is
equivalent to inv(A)*B. Note
that X = C is the solution to
A*X=B
./
Element-by-element division
note that D(2,1) is undefined due
to the zero at B(2,1)
.\
Element-by-element left
division.Note that left division in
this particular example means
elements of B divided by the
corresponding elements of A.
6
.^ Element-by-element power
Transposing a matrix in MATLAB involves a simple prime notation ( ' ) after the defined matrix as
shown below:
Example:
Sorting columns and rows follow the syntax: B=sort(A,dim), where dim is the dimension of the
matrix with the value 1 for column; 2 for row. Matrix A is the variable specified by the user.
Example:
Sorting columns:
Note that without dim being specified, the default value is 1. The default setting is ascending order.
The variable name of the sorted matrix can be omitted if no needed.
Sorting column in descending order:
Sorting row in descending order
The inverse of matrix A can be obtained with the command:
7
Eigenvalues and Eigenvectors can easily be obtained with the command [V,E]=eig(matrix
name):
where matrix V consists of Eigenvectors . The corresponding Eigenvalues are shown in matrix E.
Eigen values alone can be obtained without the notation "[V,E]":
Command Input Assistance Feature
Not sure how a command is spelled? Too lazy to type the complete command? Well, Matlab 7
programmers have added a new feature to answer these questions. Now you may type only the first
few letters of the command and use the TAB key to see what commands are available or to let Matlab complete the command typing for you. For example, if you wish to enter the command
nyqchart. You may simply type nyq then press the TAB key. A list of commands with spelling close
to what you enter will appear in a pop-up menu.
If the highlighted command is what you want, then another gentle stroke on the TAB key will
complete the command input for you.
Notes on Format
Matlab handles floating-point numbers in either single precsion or double precision (defaut setting)
format. While double precision numbers use 64 bits, single precision numbers use 32 bits, based on
IEEE Standard 754. You may convert a double precision number to a single precision number using
the command single(number).
MATLAB provides mathematical expression just like most other programming languages. These
expressions are variables, numbers, operators (+, -, *, /, etc.), and functions. To 'accommodate' EE
folks either i or j can be used to describe the imaginary number (square root of minus one). There
8
are standard (built-in) functions in MATLAB like sin, cos, inv, exp, sqrt, etc. Users may also write
user-defined functions to perform calculation like a subroutine function in C or FORTRAN.
You may control the displayed string by using the commands
format type
format ('type')
Available options for type are:
short e (scientific notation, five-digit floating point)
long e (5 digit for single precision and 15 for double precision)
short g (five digits)
long g (7 digits for single precision and 15 for double precision)
format bank (two digit decimal)
format rat (rational)
format hex (hexadecimal)
format loose (line feed added)
format compact (line feed suppressed).
Refer to Matlab's help file (help format) for more info. Unfortunately, Matlab's number display
control is not set up in the same way as in most calculators, e.g. fixing the display digits trailing the
decimal. However, the user may display a number with two digits trailing the decimal by using bank format. The following examples demonstrate how Matlab format command displays numbers.
Examples:
>> w=pi/2
w =
1.5708
short g (5-digit number) is Matlab's default format.
>> format long g
>> w
w =
1.5707963267949
15-digit display indicates double-precision setting (default)
To display single-precision result, use the command single(variable) as illustrated below:
>> single(w)
ans =
1.570796
Note that ω is now truncated to a 7-digit number.
To display ω in scientific long format, use
>> format long e
Matlab display:
w =
1.570796326794897e+000
Short scientific format can be specified with
>> format short e
Matlab's answer:
w =
1.5708e+000
To check with Matlab if the results are the same for long g of 2*w and double(2*w), we could ask
Matlab with the following command:
>> double(pi)==2*w
Matlab's answer:
ans =
1
which confirms that the two quantities indeed are the same! (1 for yes and 0 for no).
9
Equivalently, you may ask the question in a different way:
>> double(pi)~=2*w
ans =
0
It means "no, the two are not unequal!".
Bank format reduces or truncates the number to 2 digit after the decimal (dollars and cents).
>> format bank
>> w
Matlab's answer:
w =
1.57
Quitting Matlab
To quit Matlab, simply enter exit at Matlab command prompt >> or CTRL+Q (Windows). If your
Matlab process is "frozen" (crashed) in Windows (XP,2000), you may kill the process from Windows
Task Manager (CTRL+ALT+DEL) by selecting Matlab process and click on End Process button. In
UNIX or LINUX environment, Matlab rarely crashes. In case you need to kill a Matlab session, find
the process ID (PID) number and issue the command kill -9 [process ID].
______________ 1LINPACK is a collection of Fortran subroutines that analyze and solve linear equations and linear least-squares problems. The package solves linear systems whose matrices are general, banded,
symmetric indefinite, symmetric positive definite, triangular, and tridiagonal square. In addition, the
package computes the QR and singular value decompositions of rectangular matrices and applies
them to least-squares problems. LINPACK uses column-oriented algorithms to increase efficiency by
preserving locality of reference. [source: NETLIB]
2EISPACK is a collection of Fortran subroutines that compute the eigenvalues and eigenvectors of
nine classes of matrices: complex general, complex Hermitian, real general, real symmetric, real
symmetric banded, real symmetric tridiagonal, special real tridiagonal, generalized real, and
generalized real symmetric matices. In addition, two routines are included that use singular value
decomposition to solve certain least-squares problems [source: NETLIB]
10
Plotting and Graphics
Matlab offers fairly decent scientific visualization and graphics capabilities. In the current version,
Matlab features both 2-D and 3-D graphics options. Some basic plotting and graphic features are
presented and discussed in this tutorial through a series of examples.
Example 1:
We wish to plot the function:
for the range of t from 0 to 5 with an increment of .1.
In Matlab Command window, enter the following lines:
Please note that the array representing the function y must have the same dimension as that of t
array. Array division "./" and array exponential ".^" are used to create the y array as a function of
t.Note that Matlab will treat all entries after the "%" sign as comment line. The command "gtext" is
used to insert a user-defined text string at a chosen cursor position on the graph. The graphic
window displaying the plot is shown below:
___________________
Example 2:
Two or more plots can be shown on the same graph as shown in this example. In this example, an
additional function "y2" is to be shown with function y plotted in Example 1 on the same graph. Note
that the "legend" function is used to label the plots. The entries in Matlab command window are as
follows:
The resulting plot is shown below:
11
Note that markers are used in the "plot" function in Example 2 for the purpose of identification. The
table below lists all markers offered in Matlab.
Designated
colour
Used in "plot"
command
Designated
linestyle
Used in "plot"
command
yellow y point .
red r circle o
green g x-mark x
blue b plus +
black k star *
white w solid - (minus sign)
magenta m dotted :
cyan c dashdotted -.
dashed -- (two minus signs)
______________________
Example 3:
You may show multiple plot in an array format. This can be achieved with the "subplot" command.
You may arrange multiple plot in any array you wish, e.g., a 2 x 2 plot array would yield two plots on
the top row and two plots on the bottom row. The functions used in Examples 1 and 2 above can be
shown in an array format by the following inputs:
which, will produce these graphs in one plot:
12
_________________
Example 4:
Matlab offers some neat 3-D plotting functions such as plot3 and mesh. In this example, a 3-D plot
using mesh command is illustrated. To generate a 3-D plot using mesh command, you first need to
establish the domains of the "x-" and "y-", in which the function is evaluated with the command
meshgrid. In this example, function: y=3sin(y) * cos(x) is plotted in the x-domain between -pi and
pi with an increment of pi/50. Note that meshgrid function is used to transform the domain for
plotting using the mesh command. The following commands illustrate the use of aforementioned
plotting functions.
The resulting plot is shown below:
13
__________________
Example 5:
A 3-D plot is shown in the following example, where two functions sin(4t) cos(4t) are visualized as
parameter t increases from 0 to 5 at an increment of 0.01.
A different view can be achieved with the function view
14
Example 6:
Note: Some features mentioned in this example are available only in Matlab 7.
In this example, we will curve fit a set of raw data using two different methods of regression:
polynomial regression and linear-in-parameters regression.
Polynomial regression is modeled by
(1)
and linear-in-parameters regression is modeled by
(2)
Assume we are given a raw data set obtained from an experiment presented in array format as
follows:
time=[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15], measured in seconds.
volts=[0 21.7 15.9 14.2 10.8 6.8 5.7 4.5 4.3 3.7 3.5 2.8 3.1 2.6 3.3 2.5]
We will compute the unknown coefficients a_o, a_1, and a_2 and plot the fitted curves against the
raw data using the two regression methods mentioned above.
First, let's open a Matlab editor to create an M-file and name it curvefit. Make sure that the file is
saved in a directory that has been included in Matlab defined path.
To bring up the editor in Matlab 7, click on the New M-file icon as shown:
You may also bring up the editor from File > New > M-File.
In the editor window, select Enable Cell Mode from Cell menu.
The curvefit.m file should contain the following lines:
% Regression and curve fitting example %% Raw data set t = [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]'; y = [0 21.7 15.9 14.2 10.8 6.8 5.7 4.5 4.3 3.7 3.5 2.8 3.1 2.6 3.3 2.5]'; plot(t,y,'o r'),grid %plot raw data points %% Polynomial regression X = [ones(size(t)) t t.^2];
a = X\y %solving for unknown coefficients T = (0:.5:16)'; Y = [ones(size(T)) T T.^2]*a;
plot(T,Y,'-',t,y,'o'), grid on title('Polynomial Regression') xlabel('time, sec') ylabel('Magnitude, volts')
15
%% Linear-in-parameters regression X = [ones(size(t)) exp(-t) t.*exp(-t)]; a = X\y
T = (0:.2:16)'; Y = [ones(size(T)) exp(-T) T.*exp(-T)]*a; plot(T,Y,'-',t,y,'o'), grid on
title('Linear-in-Paramenters Regression') xlabel('time, sec') ylabel('Magnitude, volts')
Note that %% is used to signify a cell, where a group of commands is executed in step process. This
is among the new features offered in Matlab 7. I will demonstrate this feature in the following steps.
As you type in the lines (as shown in blue box above) with cell mode enabled, you will notice that the yellow background is on automatically. Each time you enter "%%", a new cell is created.
Once you finish entering all the lines, save the file and move the cursor the the first cell. Then click
on the first icon of the cell evaluation group (Evaluate cell icon) as shown below.
A plot of raw data should popup. To take advantage of
the docking feature in Matab 7, click on the docking
arrow located at the upper right corner of the figure
window.
Note that the you may "undock" the figure at any time
by clicking on the undock arrow icon.
This docking feature is particularly useful when you
want to see both Matlab's results in the Command
window and the content of the figure in one compact
group.
A typical desktop environment with docked figure of plotted raw data (first cell evaluated) is shown
below:
Next, click on the second cell icon (Evaluate cell and advance icon). You will notice the yellow
highlighted group is now shifted down to the second cell. Matlab effectively evaluated the first cell
16
again and make the cell below the next active cell. To evaluate the second cell and make the third
cell active, click on this icon again.
A plot of polynomial regression is now obtained.
The unknown coefficients of Eq. (1) as obtained from Matlab Command window are:
a_o = 13.1395
a_1= -1.0932
a_2= 0.0213
You can see that the polynomial approximation we used did not yield a very good curve fitting. We
may try to increase the order of the polynomial or use a different approximation.
In this example we'll try the linear-in-parameters regression as defined in the third cell.
Click on the first icon (Evaluate Cell icon). This effectively evaluates the third cell containing
instructions for linear-in-parameters regression.
The unknown coefficients of Eq. (2) as obtained from Matlab Command window are:
a_o= 3.9215
a_1= -4.1214
a_2= 53.4127
This approximation has been shown to be better than polynomial regression for the given set of raw data.
Combined plot
Sometime you may want to show all plots in one figure like one shown below.
17
The plot above was generated from the existing M-file listed above with only a few minor
modifications. The command hold on was added preceding to the first plot command (in the first
cell).
Version 7 offers quite a few new user-friendly plotting tools such as text annotations, data cursor,
and legend insert tools, etc. Data cursor tool is useful when you wish to know the coordinates of a
particular point on the plot.
Data cursor can be activated from Tools > Data cursor menu or by clicking on icon then lefit-
click on the desired location on the existing curve. You may delete the current data tip by simply
selecting it then press the Delete key.
Background colour can be changed from View > Property Editor.
You are encouraged to explore more useful plotting features offered in v.7. Have fun!
18
FILE MANAGEMENT
Working Directory
Working directory is the workspace where your Matlab files are saved to by default. The user may
specify this workspace on local machine or a file server on the network. At UP, you may also save
your files on your Unix machine by setting the appropriate path in Matlab setting. The current
location of the working directory is displayed on the tool bar area of your Matlab main window (make
sure the Current Directory option under Desktop menu is checked). A typical display of current
directory is shown below.
You may change the location the current directory by clicking on the "..." icon (next to the pulldown
menu). Alternately, you may also rightclick on Matlab icon (or shortcut) and select Properties from
context menu then change/edit the path in the Target box.
Importing an Existing File to Matlab
There are several ways to import a file (usually data file) to Matlab. Depending on the file size, the
method of file import can be chosen among those discussed below to fit your needs.
� Enter data explicitly in Matlab command window. This method is practical only for a small list
of data.
� Create an M-file containing your data in explicit format. This is similar to Method 1 above
except that with this method you may edit the content of the data file. Upon the completion of data file editing, you may call this M-file in the Matab session.
� Create an M-file to handle the import of an existing file by using the load command. This is
particularly useful when you have a large file or a repeated files to be processed using Matlab.
Example 1 belows illustrates the use of this method.
� Use of fopen, fread, and other Matlab's low-level I/O functions to import or extract exisiting
external files. This method is useful when data are imported from application with established
file formats. File permission settings are allowed in this file import method.
� Create a file in MAT-file format from a program such as FORTRAN or C and read this MAT-file
into Matlab using the load command.
� Use of MEX-file to read the data.
Example 1:
In this example, we'll use Matlab to read in and plot a waveform that was saved in ASCII format in
an one-column format. The first two data points are time domain information. We want to plot the
amplitude of the waveform vs. time. The program written in Matlab with source code shown in the
yellow-highlighted block below will prompt you to enter a file name with extention ".dat". Comments
are made along each line (text that follows % sign) to help explaining the process. You may use an
editor of your choice to create the M-file. Once completed, you may enter the name of the file you've
named for this program at the Matlab command prompt ">>" to execute the program. Note the use
of eval and load function to import an ASCII file from the current directory.
Example M-file "pltone.m":
% Plotting an imported file. Example 1
% April 1993.Rev. Jan 2004. T Nguyen.
%
filename = input('Enter name of file: ','s');
eval(['load ' filename '.dat'])
dataset=eval(filename);
dataset=dataset'; % transposing the input array
p1=dataset(1,:); % first point of imported data set
p2=dataset(2,:); % second point
19
D=length(dataset); % full length of the import array
DD=D-2; % length of array minus first 2 data points
Dset=dataset(3:fulllength,:); % array including only recorded amplitude
p3=(DD-1)*p2 + p1; % final point in the time domain
t1=(p1:p2:p3); % creating the time array
plot(t1,Dset)
xlabel('time,sec')
ylabel('amplitude, mV')
grid
%
%plotname=input('name of a plot file:?' ,'s');
%eval(['print -dps ' plotname]);end;
%
%end of program
Exporting Matlab data
There are several methods to export your work in Matlab to another format for use in other
applications. Like in the importing methods, depending on the size of the exported information, you
may choose from the following methods for exporting your Matlab results:
� For small size of results generated from Matlab such as computed matrices, you may use the
diary command to generate a diary file. You may use a text editor to further manipulate this
diary file.
� Use the save command with -ascii option to created a file (user-specified filename) in ASCII
format.
� Use the fopen, fwrite, and other low-level I/O functions to write your computed results to a file in a user-defined format. Type help fopen or help fwrite in Matlab command window for
more information.
� Use of MEX-file to write data.
� Use save command to write out data as MAT-file in user-defined format then use a
programming language of your choice, e.g., FORTRAN or C, to extract information from MAT-
file.
MEX-files
With Matlab, you can create interface files called MEX-files. These files can be written in C or FOTRAN
language as subroutines to be called from Matlab as if they were built-in functions. MEX-files are
often used:
� to improve the calculation performance in cases where Matlab doesn't run fast enough
� to avoid re-writing large pre-existing codes in another language such as C or FORTRAN
� to facilitate data exchange and interface via A/D or D/A cards installed on a data acquisition
hardware
For Windows environment, a MEX-file is designated by an extension "dll"; for Mac the extension is
"mex"; for Sun-4 the extension is "mex4". The use of MEX-files are explained in the External
Interface Guide, a Mathwork's publication.
20
SYMBOLIC CALCULATION
Based on Maple kernel, symbolic Math Toolbox performs calculation symbolically in Matlab
environment. The following examples introduce some basic operations available in Basic Symbolic
Math toolbox version 2.1.3.
Example 1: Simplifying an expression.
Simplify
- In Matlab command window, we will first need to define alpha as a symbolic expression.
>> alpha = sym('alpha')
alternately, you may also enter:
>> syms alpha
The commands "sym" and "syms" are Matlab's reserved words. When "syms" is used by itself at
the command prompt, all defined symbolic values will be listed.
- Next, we will enter the expression of z.
>> z = sin(alpha)^2 + cos(alpha)^2;
Note that ";" is used to suppress echo.
>> simplify(z)
Matlab will yield "1", as expected:
ans =
1
You may also specify the format of the output in symbolic calculation by adding the option as shown
in the example below.
>> syms rho
>> rho=0.25
>> sym(rho,'r')
Matlab returns:
ans =
1/4
'r' stands for rational form. Similarly, you may use 'e', 'd' format. Please refer to Matlab's help files or
click here for more info on format.
Example 2: Derivative.
We wish to take the derivative of function f(x):
:
Matlab command entries:
>> syms x
>> f=x^3-cos(x);
>> g=diff(f)
Matlab returns:
g =
3*x^2+sin(x)
Note that the command "diff" was used to obtain the derivative of function f.
Since function f has only one independent variable, the diff command performed the calculation
based on x. If there are more than one independent variable in a function, you should include the
"intended" variable in the following format:
diff(f, x)
where x is the "intended" variable. For example,
We wish to obtain the derivative of the following function
21
Matlab command entries:
>> syms x y
>> f=x^2+(y+5)^3;
>> diff(f,y)
Matlab returns:
ans =
3*(y+5)^2
Note that in this case, the command diff(f,y) is equivalent to
Example 3: Integral
To integrate function f(x,y) as shown in Example 2, we will use the command "int" as shown below.
>> int(f,x)
Matlab returns:
ans =
1/3*x^3+(y+5)^3*x
The syntax of the integral command can be viewed by typing >> help int in Matlab command
window.
If we wish to perform the following definite integral:
Matlab command entry:
>> int(f,y,0,10)
Matlab returns:
ans =
12500+10*x^2
Example 4: Finding roots.
Consider the following polynomial:
Suppose we wish to find the roots of this polynomial. In Matlab Command window:
>> syms x
>> f=2*x^2 + 4*x -8;
>> solve(f,x)
Matlab returns:
ans =
5^(1/2)-1
-1-5^(1/2)
Alternately, you may use the following lines in Matlab to perform the same calculation:
>> f=[2 4 -8];
>> roots(f)
Matlab returns:
ans =
-3.2361
1.2361
22
Note that the results from both approaches are the same.
Example 5: Matrix Symbolic Calculation
This example demonstrates how Matlab handles matrix calculation symbolically.
First we need to define the symbolic variables:
>> syms a b c d e f g h
Matrix A is then defined as:
>> A=[a b; c d]
Matlab's echo:
A =
[ a, b]
[ c, d]
Next, matrix B is defined as:
>> B=[e f;g h]
Matlab's echo:
B =
[ e, f]
[ g, h]
The addition of these two matrices yields:
>> C=A+B
C =
[ a+e, b+f]
[ c+g, d+h]
and the product of A and B is:
>> D=A*B
D =
[ a*e+b*g, a*f+b*h]
[ c*e+d*g, c*f+d*h]
If we wish to evaluate a specific matrix numerically, we simply assign the numeric values to the
appropriate variable then use the command eval as demonstrate below.
>> a=1;b=2;c=3;d=4;e=5;f=6;e=7;f=8;g=9;h=0;
>> eval(A)
ans =
1 2
3 4
>> eval(B)
ans =
7 8
9 0
>> eval(C)
ans =
8 10
12 4
The inverse of A can be expressed symbolically:
>> D=inv(A)
D =
23
[ d/(a*d-b*c), -b/(a*d-b*c)]
[ -c/(a*d-b*c), a/(a*d-b*c)]
Numerically, D is expressed by
>> Dn=eval(inv(A))
Dn =
-2.0000 1.0000
1.5000 -0.5000
As a verification, we may evaluate D directly:
>> De=eval(D)
De =
-2.0000 1.0000
1.5000 -0.5000
You may also try
>> Df=inv(eval(A))
to verify if you get the same result.
24
1. Laplace Transform
Laplace transform of a function f(t) is defined as
where
Laplace transform of a function f(t) can be obtained with Matlab's function laplace.
Syntax: L =laplace(f)
The usage is demonstrated in the following examples.
Example 1.
Find the Laplace transform of
Matlab performs Laplace transform symbolically. Thus, you need to first define the variable t as a "symbol".
>> syms t
Next, enter the function f(t):
>> f=5*exp(-2*t);
Finally, enter the following command:
>> L=laplace(f)
Matlab yields the following answer:
L =
5/(s+2)
You may want to carry out the transformation by hand (or using Laplace transform table) to verify
this result.
Example 2.
Find the Laplace transform of:
In Matlab Command Window:
>> laplace(12*diff(sym('y(t)'),2))
Note that the function y(t) is defined as symbol with the imbeded command "sym". The number 2
means we wish to take the second derivative of the function y(t).
Matlab result:
ans =
12*s*(s*laplace(y(t),t,s)-y(0))-12*D(y)(0)
where y(0) is the initial condition.
Example 3.
Find the inverse Laplace transform of
In Matlab Command window:
>> ilaplace(1/s-2/(s+4)+1/(s+5))
Matlab result:
ans =
1-2*exp(-4*t)+exp(-5*t)
or
25
which is the solution of the differential equation
As an exercise, you should carryout the Laplace transform of the above differential equation with
initial condition y(0) = 0 to arrive to the expression of Y(s) as shown above.
2. State-Space
As defined in class, the state of a system is a set of variables such that the knowledge of these
variables and the input functions will, with the equations describing the dynamics, provide the future
state and output of the system. The state of the system is described by the set of the first-order
differential equations written in terms of state variables (x1, x2, x3, ..., xn). These first-order
differential equations can be written in a general form that can be represented in matrix notation:
where u is a vector of the inputs, x is the element state vector, and y is a vector containing outputs.
Example 4.
Consider an RLC series circuit as shown in the figure below:
Using Kirchhoff's voltage law, we obtain a differential equation that can be reduced to a set of first-
order system:
in matrix form:
Assuming we can measure Vc, then the output relationship can be described by
We will analyze this problem with a step input.
In MATLAB you can create an "M-file" including the model parameters. To create an M-file, go to FILE
menu and select NEW > M-file. An editor window will pop up. Enter the 12 lines as shown below.
26
Save the file to directory where you can specify the path from the MATLAB command window. Once
saved, this M-file can be loaded (executed) by simply go to the appropriate directory and call the M-
file by its name. For example, if the above M-file was saved as "rlc.m" ( the extension .m is
appended by MATLAB automatically), in MATLAB, simply enter "rlc" at the command prompt to execute the program and enter the requested value accordingly.
NOTE: Make sure not to save your M-file with a name that is the same as a Matlab reserved word or
function name.
The out put of the step response is shown below:
Grids can be shown on the plot with the "grid" command either in your M-file script or at the
command line.
3. Converting State-Space to Transfer Function.
You may find it useful to obtain a transfer function of the system from the state-space
representation. This can be achieved by using the MATLAB's function "ss2tf". In the example above,
the matrices A, B, C, D were computed according to the user-defined parameters. We will use the
computed values from Example 4 above to demonstrate the use of the "ss2tf" command. A
screenshot of the conversion with the computed values of A, B, C, and D matrices are shown below
27
Vector DEN contains the coefficients of the denominator in descending powers of s. The numerator
coefficients are returned in matrix NUM with as many rows as there are outputs y. Thus the above
answer from MATLAB can be written as:
28
Contents:
LTI Viewer
Root Locus
LTI Viewer
LTI (Linear Time Invariant) interface is where the user may obtain information about a system
response by clicking on the chosen system represented by a transfer function. LTI Viewer allows the
user to obtain time and frequency information of LTI transfer functions that can be used to create
plots of step and impulse responses, Bode, Nyquist, Nichols, and pole-zero plots. With a right click on
the mouse, the information such as peak time and settling time can be obtained.
In this tutorial, I will walk you through some examples where you will learn how the LTI viewer can
be used in the design of the system. In the following examples, we'll consider the following transfer
functions:
STEP 1- MATLAB INPUT:
You may choose to enter the TF's in either MATLAB Command window or MATLAB Editor window. A
typical input in the editor is show below. Comments are preceded by "%".
% GUI Example 1 T1=tf(10,[1 4 10]);
T2=tf(200,conv([1 10],[1 4 24])); % note the use of convolution function
T3=tf(60,conv([1 3],[1 1.5 24]));
ltiview % call the LTI Viewer
If you use the editor option, once complete the entry of command lines above, save the file. In this
example the file has been saved as "guiex1.m". Make sure you specify the correct path in MATLAB so
that your saved mfile can be executed from MATLAB Command window.
STEP 2 - Switch over the MATLAB command and type in the file name you've just saved. In this
example, at the command prompt, type in:
>> guiex1
and press the RETURN (or ENTER) key. A LTI Viewer window will appear.
29
STEP 3 - Import the deifned TFs. Click on FILE menu on the LTI Viewer window and select IMPORT.
An LTI Browser window will pop up. hold down the SHIFT key while selecting T1, T2, and T3 transfer
functions.
Click on the OK button. The step response of the three imported TFs will be displayed in the LTI
Viewer window as shown below.
30
Now, move the cursor inside the graph area and right click. A context menu will pop-up. Move the
cursor to Characteristics to and select Peak Response (sub-menu).
LTI Viewer will display the locations on the plots where the peaks occur. You may also obtain the
exact value corresponding to these peak by simply move the cursor over the peak of interest.
You are encouraged to experiment with different options in these submenus to obtain information on
other parameters of step input response. You may also change to different type of response by
selecting the Systems menu.
You may also use the LEFT CLICK on a particular point on the plot to see the amplitude at that
specific point and its corresponding time.
To print to a figure, select Print to Figure from FILE menu. In the 'figure' window, you can change the label and title of the plot and other plot features by double click on the item you wish to modify.
Note that alternately, you may use the step command in MATLAB to obtain the same response to
step input. For example, let's take the second transfer function T2. The step response to this TF can
be obtain with the following commands:
>> [y2,t2]=step(T2)
assuming that T2 has been entered previously. The step command as described above will produce
two arrays containing the magnitude and time values of the step response for T2. You may use the plot command to graphically show the response. If step command is used without the array forming
31
in the left handside of the entry above, a plot of the step command will result from the step
command:
>> step(T2)
ROOT LOCUS
Root locus design using MATLAB's Graphical User Interface is activated with the command:
>> rltool
A Single Input Single Output (SISO) Design window will appear. In this window you may define the
design parameters in various arrangements of feedback structure, which consists of four main
components: compensator (C), pre-filter (F), plant (G), and sensor (H).
In this version of Matlab, there are several design tools available to add poles and zero directly on
the plot (graphic window). A typical SISO Design window is shown below.
Use this button to select
for dragging
: add compensator pole
: add compensator zero
: Add a complex pole
: Add a complex zero
:erase compensator pole
or zero
Next, we want to import a pre-defined open-loop TFs. We will use this TF to analyze closed-loop
characteristics. All LTI objects in the MATLAB can be exported to Root Locus Design (RLD) GUI.
From top menu in SISO Design window: FILE> Import model. Alternately, you may use the
keystroke ALT F, i (ALT key then the "i" key) to import the TFs. A new window will pop up like one
shown below.
32
The available TFs in workspace will show up in SISO Models box. In G (plant) box under System
Data group, enter T2.
Alternately, you may also issue the command
>> rltool(T2)
Click on the OK button to obtain the root locus plot. Right click on the graphics window and select
Grid to display the grids.
You may now enter design parameters such as natural frequencies, settling time, damping ratio, etc.
by right click on the graph (plot) area and select:
Design Constraints > New...
33
For the purpose of demonstration, let's select the natural frequency ω > 7.5 r/s. In the Constraint
pull-down menu, select Natural frequency then enter 7.5 in the Constraint parameters box.
Make sure at least is selected from the pull-down menu preceeding the numeric value.
SISO Design window will display a yellow region to reflect your new design specification.
You are encouraged to experiment with different design parameters and add (or remove) poles and
zeros to exam the system's stability and the system's sensitivity to a range of design parameters.
34
BODE and NYQUIST PLOTS
As you have learned in class how to construct a Bode diagrams using the asymptote approximation
technique. Here you will learn how to use MATLAB to obtain Bode plots with a better accuracy around
the break frequencies (corner frequencies). It is recommended that you read through the MATLAB's
help file on Bode and Nyquist plottings with the commands:
>> help Nyquist
>> help Bode
To show how a typical Bode magnitude and phase plots are constructed, let's consider an example
where the transfer function is
If the desired frequency range is 0.1 to 1000 radians/sec, a vector w is generated with the
command
>> w = logspace(-1,3,100)
where 100 is number of points.
The Bode plots can then be obtained with the following commands:
>> num=[1 2];
>> den=poly([-5 -20 -50]);
>> [mag,phase,w]=bode(num,den)
Note that the [mag,phase,w] group is used only if you want MATLAB to generate matrices of
magnitude, phase, and frequency range for further analysis. You may obtain a graphical
representation of the Bode plot with the command "bode(num,den,w)" only. The results are shown below.
Nyquist plot for an open loop transfer function:
can be obtained from MATLAB wth the following command:
>> nyquist(num,den)
The result is shown below.
35
Note that the Nyquist plot above does not intesect with the real axis at -1. What can you say about
the system's stability? Try to adjust the gain K to 5 (num=5) to see if the system is still stable.
36
SIDE NOTES
� Classical and modern control theories
� Control actions
� Matlab handles
CLASSICAL AND MODERN CONTROL THEORIES.
Some differences between classical and modern control theories are highlighted below.
Classical Theory Modern Theory
Transfer function (TF) I/O based principally on TF. Used only to obtain
corresponding D.E.
Differential equations
(D.E.)
Linearized when encountered.
Constraints req'd. for useful I/O
relationship.
Direct use of D.E.
Input Impulse, step, sinusoidal. Initial
conditions must obtained. Indifferent to type of input.
Controllers Limited to linear controller. Non-linear controller (optimal)
can be obtained.
Design process Synthesis Trial-and-error
Modeled systems limited to SISO SISO/MIMO capability
____________
CONTROL ACTIONS
We have discussed at great length on the subject of control actions in class. Here, some highlights of
the three main controllers, namely proportional, integral, and derivative controllers are re-visited.
The block diagram of a typical control system is presented in Figure 1.
Figure 1.
Proportional Control Action
This type of control action involves a proportional constant, namely Kp, which is defined as
, (1)
where U(s) is the output signal and E(s) is the error signal, measured in frequency domain.
You may think of Kp as a volume control knob on your car radio. It is essentially an adjustable
amplifier that helps reducing the effects of disturbances. This relatively simple type of controller is
also useful in reducing the system sensitivity to changes in the plant's parameter. However, if the
proportional gain is set too high, system instability (closed-loop) and signal distortion may result.
Proportional control action is generally not useful for controlling steady state errors. This
shortcoming of proportional control action gives rise to the need of another type of control action:
the integral control action.
37
Integral Control Action
The relationship of the integral control action with the output and error signals, in frequency domain,
is defined as
. (2)
where KI is the integral gain, U(s) is output, and E(s) relates to the error signal. In the time domain,
the rate of change of the output is proportional to the error signal by the constant KI. This means
when the error changes, the rate at which the output signal change depends on the constant KI. If
error is zero, the output signal remains unchanged (slope = 0). This control action is also known as
the reset control.
Derivative Control Action
In this control action, the magnitude of the output of the controller U(s) is proportional to the rate of
change of error signal E(s) by the constant KD. This action is described by Eq (3).
. (3)
In a linear system, derivative controller measures the instantaneous slope of the error signal,
predicts or anticipates the large overshoot, and makes proper adjustment before the overshoot
actually happens. Because of this inherent characteristic, derivative controller is classified as
anticipatory type of controller. Noted that if the steady-state error of a system is unchanged in the
time domain, the derivative control has no effect since the time derivative is zero in this case.
Because derivative control action only works in transient mode, it should never be used alone!
Proportional-plus-Integral Control Action (PI)
Combining Eq (1) and Eq (2), we have
. (4)
Rearranging (4) we obtain
.
(5)
where TI = KP/KI is known as the integral time or reset rate (times per minute), the rate at which KP
is repeated (duplicated). Note that KP affects both proportional and integral parts of the controller.
For a system of type 1 (see lecture notes) with a ramp input, KP controls the ramp-error constant and
consequently affects the magnitude of the non-zero steady-state error. However, as demonstrated in
lab, if you crank up KP too high in a type 1 system, the system could become very unstable (remember the roaring noise?). For a type 0 system, the value of KI affects the ramp-error constant
while KP affects phase margin, gain margin, resonant peak, and bandwidth. In general, a PI control
action can improve steady-state error, but at the expense of stability. In addition, if the location of
the zero of the controller is correctly placed, you can also improve the damping as well. In the design
of a PI controller, it's good to keep the zero close to the origin and far away from the most significant
poles, while keeping KP and KI small. When properly designed, a PI controller can improve damping
but extend rise time. In frequency domain, it can reduce bandwidth and improve gain and phase
margins as well as resonant peak.
Proportional-plus-Derivative Control Action (PD)
The combination of proportional and derivative control actions forms
. (6)
where TD = KD/KP is called the derivative time, during which interval the proportional control action
takes effect.
38
The anticipatory characteristic of derivative control action is found in PD control action. This means,
in transient mode, PD can anticipate the direction of the error in making adjustments before
excessive overshoot occurs. During the stead-state mode, PD has an effect on the stead-state error
only when the error changes with respect to time. In the design of a PD controller, we want to place
the controller's corner frequency ω = 1/TP so that the phase margin is improved with the new gain-
crossover frequency. The effects of a PD controller in frequency domain include the increase of
bandwidth and an accentuation of high-frequency noise, as PD controller acts like a high-pass filter.
In the time domain, PD improves damping while reduces maximum overshoot, rise time, and settling
time. PD is generally not ideal for lightly damped systems.
Proportional-plus-Intergal-plus-Derivative Control Action (PID)
As the name suggests, this type of controller represents the combined action of Eq. (5) and Eq. (6)
or
.
(7)
This type of controller contains the inherent characteristics of PD and PI controllers. With PI
controller acts like a low-pass filter (phase-lag controller) and PD acts like a high-pass filter (phase-
lead controller), PID controller functions as a bandpass filter. The phase-lag part of the controller is
used to boost the damping of the system while the phase-lead part is used to reduce the rise time.
The general effects of a properly designed controller are summarized below:
PI controller Effects of
increasing KI1
PD controller Effects of
increasing KD1
Max. overshoot reduced increased reduced decreased2
Damping improved - improved -
Rise time increased decreased reduced decreased
Settling time increased increased reduced decreased2
Steady-state error improved - reduced -
Phase margin improved decreased improved increased2
Gain margin improved - improved -
Resonant peak improved increased improved decreased2
Bandwidth decreased increased increased increased
filter low-pass - high-pass -
1- the observed effects based on unit-step response of a third-order system with KP held constant.
2- If KDis set too high, max overshoot and settling time may increase significantly. In the frequency domain, the excessive gain
of KD can cause the phase margin to decrease and resonant peak to increase.
___________
MATLAB HANDLES
Handle is Matlab's way of identifying an object. You may assign a handle to a Matlab function for
subsequent changes of properties or execution of the function. A function handle is assigned with the
use of the "@" sign.
Example:
We will use the handle name "banana" as an identifier in the plotting of a natural log function.
Actual Matlab input Comments
>> x=(0.1:0.1:10); setting an array
>> banana = @log; function_handle 'banana' is defined
>> juice=plot(x,banana(x)) handle 'juice' is defined
39
>> set(findobj(juice,'type','line',...
'color','blue'),'color',...
'yellow','linewidth',2)
Find the specified properties of handle 'juice'
(the plot) and change its properties such as
colour and line width.
*Note: the three dots ("...") used in the command lines above are continuation designator telling
Matlab that the lines are to be interpreted one string of command.
_________
RECOMMENDED READINGS
Hale F., Introduction to Control System Analysis and Design, 2nd. ed., Prentice-Hall,1988.
Kou B. C., Automatic Control Systems, 7th. ed. John Wiley & Son, 1995.
Ogata K., Modern Control Engineering, 2nd., Prentice Hall, 1990.
Phelan R. M., Automatic Control System, Cornell University Press, 1977.
Raven F. H., Automatic Control Engineering, 3rd ed., McGraw-Hill, 1978.
40
SIMULINK
Introduction
Simulink (Simulation and Link) is an extension of MATLAB by Mathworks Inc. It works with
MATLAB to offer modeling, simulating, and analyzing of dynamical systems under a graphical user
interface (GUI) environment. The construction of a model is simplified with click-and-drag mouse
operations. Simulink includes a comprehensive block library of toolboxes for both linear and
nonlinear analyses. Models are hierarchical, which allow using both top-down and bottom-up
approaches. As Simulink is an integral part of MATLAB, it is easy to switch back and forth during the
analysis process and thus, the user may take full advantage of features offered in both
environments. This tutorial presents the basic features of Simulink and is focused on control
systems as it has been written for students in my control systems course.
This tutorial has been written for Simulink v.5 and v.6.
Getting Started
To start a Simulink session, you'd need to bring up Matlab program first.
From Matlab command window, enter:
>> simulink
Alternately, you may click on the Simulink icon located on the toolbar as shown:
Simulink's library browser window like one shown below will pop up presenting the block set for
model construction.
To see the content of the blockset, click on the "+" sign at the beginning of each toolbox.
To start a model click on the NEW FILE ICON as shown in the screenshot above. Alternately, you
may use keystrokes CTRL+N.
A new window will appear on the screen. You will be constructing your model in this window. Also in
this window the constructed model is simulated. A screenshot of a typical working (model) window is
shown below:
41
To become familiarized with the structure and the environment of Simulink, you are encouraged to
explore the toolboxes and scan their contents. You may not know what they are all about at first, but
perhaps you could catch on the organisation of these toolboxes according to their categories. For
instance, you may see that the Control System toolbox consists of the Linear Time Invariant (LTI)
system library and the MATLAB functions can be found under Function and Tables of the Simulink
main toolbox. A good way to learn Simulink (or any computer program in general) is to practice and
explore. Making mistakes is part of the learning curve. So, fear not you should be!
A simple model is used here to introduce some basic features of Simulink. Please follow the steps
below to construct a simple model.
STEP 1: CREATING BLOCKS.
From BLOCK SET CATEGORIES section of the SIMULINK LIBRARY BROWSER window, click on the "+"
sign next to the Simulink group to expand the tree and select (click on) Sources.
A set of blocks will appear in the BLOCKSET group. Click on the Sine Wave block and drag it to the
workspace window (also known as model window).
Now you have established a source of your model.
42
NOTE: It is advisable that you save your model at some point early on so that if your PC crashes you
wouldn't loose too much time reconstructing your model. This is among the reasons why I prefer
Linux or Unix!
I am going to save this model under the filename: "simexample1". To save a model, you may click
on the floppy diskette icon . or from FILE menu, select Save or using keystrokes CTRL+S. All
Simulink model file will have an extension ".mdl". Simulink recognises file with .mdl extension as a simulation model (similar to how MATLAB recognises files with the extension .m as an MFile).
Continue to build your model by adding more components (or blocks) to your model window. We'll
continue to add a Scope from Sinks library, an Integrator block from Continuous library, and a
Mux block from Signal Routing library.
NOTE: If you wish to locate a block knowing its name, you may enter the name in the SEARCH
WINDOW (at Find prompt) and Simulink will bring up the specified block.
To move the blocks around, simply click on it and drag it to a desired location.
Once you've dragged over all necessary blocks, the workspace window should consist of the following
components:
You may remove (delete) a block by simply clicking on it once to turn on the "select mode" (with
four corner boxes) and use the DEL key or keys combination CTRL-X.
STEP 2: MAKING CONNECTIONS
To establish connections between the blocks, move the cursor to the output port represented by ">"
sign on the block. Once placed at a port, the cursor will turn into a cross "+" enabling you to make
connection between blocks.
To make a connection: left-click while holding down the control key (on your keyboard) and drag
from source port to a destination port.
The connected model is shown below.
A sine signal is generated by the Sine Wave block (a source) and is displayed by the scope. The
integrated sine signal is sent to scope for display along with the original signal from the source via
the Mux, whose function is to mutiplex signals in form of scalar, vector, or matrix into a bus.
STEP 3: RUNNING SIMULATION
You now may run the simulation of the simple system above by clicking on the play button .
Alternately, you may use keystrokes CTRL+T, or choose Start submenu (under Simulation menu).
Double click on the Scope block to display of the scope.
43
To view/edit the parameters, simply double click on the block of interest.
Handling of Blocks and Lines
The table below describes the actions and the corresponding keystrokes or mouse operations
(Windows versions).
Actions Keystokes or Mouse
Actions
Copying a block from a library Drag the block to the
model window with the left
button on the mouse OR
use select the COPY and
PASTE from EDIT menu.
Duplicating blocks in a model Hold down the CTRL key
and select the block with
the left mouse drag the
block to a new location.
Display block's parameters Double click on the block
Flip a block CTRL-F
Rotate a block (clockwise 90 deg @ each keystroke) CTRL-R
Changing blocks' names Click on block's label and
position the cursor to
desired place.
Disconnecting a block hold down the SHIFT key
and drag the block to a
new location
Drawing a diagonal line hold down the SHIFT key
while dragging the mouse
with the left button
Dividing a line move the cursor to the line
to where you want to
create the vertex and use
the left button on the
mouse to drag the line
while holding down the
SHIFT key
44
Annotations
To add an annotation to your model, place the cursor at an unoccupied area in your model window
and double click (left button). A small rectangular area will appear with a cursor prompting for your
input.
To delete an annotation, hold down the SHIFT key while selecting the annotation, then press the
DELETE or BACKSPACE key. You may also change font type and colour from FORMAT menu. Make
sure that the block is selected before making the change.
______________________________________________________
45
SIMULINK EXAMPLES
Example 1. Simulation of an Equation.
In this example we will use Simulink to model an equation. Let's consider
(1)
where the displacement x is a function of time t, frequency w, phase angle phi, and amplitue A. In
this example the values for these parameters are set as follows: frequency=5
rad/sec;phase=pi/2;A=2.
where the displacement x is a function of time t, frequency w, phase angle phi, and amplitue A. In
this example the values for these parameters are set as follows: frequency=5
rad/sec;phase=pi/2;A=2.
1. From Simulink's library drag the following blocks to the Model Window
Blocks to be dragged to the
model window
Where located in Simulink library browser
Ramp Sources
Constant Sources
Gain Math Operation
Sum Math Operation
Product Math Operation
Trigonometry Function Math Operation
Scope Sinks
Mux Signal Routing
2. The next step is to connect these blocks as shown in Figure E1-1.
Figure E1-1
Double click on the blocks and enter the appropriate values as prompted by the pop-up dialog windows. Note that the cosine function can be selected from the pull-down menu in the pop-up
window. In the arrangement shown above, the input signal (a ramp function) is to be displayed along
with the output (displacement) via the use of the mux tool as demonstrated earlier in this tutorial. To
view the plots, double click on the scope.
3. Make sure all blocks are connected correctly then run the simulation (CTRL+T). You may need to
select the Autoscale button on the scope display window to obtain a better display of the plots.
You may find the sinusoidal plots to be a bit "jaggy". You may want to improve the resolution of the
displayed plot by redefining the Max Step Side value ("auto" is set a default value) in Simulation
Parameters window (with keystrokes CTRL+E in the model window). Just for fun, you may want to
experiement with different choice of solver. ODE45 is a default choice. You are encouraged to learn
more about the solver methods by checking out the help files in Matlab command window. For
instance, help ODE45 for parameters in non-stiff differential equations.
46
This example has demonstrated the use Simulink with built-in mathematical functions and other
supporting toolboxes to simulate an equation. The same output/result can also be obtained with the
following set of instructions entered in Matlab command window:
>> t=(0:.01:10);A=2;phi=pi/2;omega=5;
>> xt=A*cos(omega*t+phi);
>> plot(t,xt);grid
______________________________________
Example 2. Mass-Spring-Dashpot System Simulation
Figure E2-1
Consider a mass-spring-dashpot system as shown in Figure E2-1. The
mathematical model for this system is described by
(2)
where m is the equivalent mass of the system, c is the damping ratio, k is the
spring stiffness, and f(t) is the forcing function in the x-direction.
In this example I will illustrate how to use Simulink to simulate the response of
this system to unit step input.
STEP 1 In Simulink, create a new model window (CTRL+N) and drag the following blocks from
the Simulink library window:
Blocks to be dragged to the
model window
Where located in Simulink library browser
Step Sources
Gain Math Operation
Sum Math Operation
Integrator Continuous
Scope Sinks
To Workspace Sinks
STEP 2 By re-arranging Eqn 2 to yield an expression for the acceleration term, Eqn (2)
becomes
(3)
Based on Eqn 3, we connect the blocks in the diagram as shown in Figure E2-2. Use
CTRL+F and CTRL+R to flip and rotate the blocks as necessary (select the block first
then execute the key sequence). Note that you can use CTRL+right mouse button to
create branches of the connecting lines. Don't worry about the parameter values and
the signs for these blocks at this point as we'll take care of this in STEP 3. Just get
them connected first.
47
Figure E2-2
STEP 3 Enter the values of the parameters for each block. In this example, we will set m =
2.0; c=0.7; k=1. You are encouraged to try different values and observe the system's
response to step input.
To show that you may obtain different form of output, I included another block (in
addition to the scope block) called "simout". This block can be found in the Sinks group
from the Simulink Library browser. The output from this block is used in Matlab workspace. To illustrate how this block works, I will select a name for the output called
"simout" as the variable name in the block's parameter setting (double click on the
"simput" block to bring up the parameter dialog window). In additon, I will need a time
array from the simulation. This can be specifed as a parameter in the Simulation
Parameter window (CTRL+E) under the Workspace I/O tab as shown in Figure E2-3.
Figure E2-3
STEP 4 Run the simulation by clicking on the button (alternately you may use keyboard
command CTRL+T ). The screenshot of the output from the Scope block is show in
Figure E2-3.
48
Figure E2-3
That's it! You have successfully modeled and simulated a second-order under-damped
dynamic system. To exam different responses, feel free to change different values for
m, c, and k in the gain blocks.
To see how you can use the output from the "simout" block (by the way, you may
name the block whatever you wish), go to Matlab Command window and type
>> who
You should receive an echo from Matlab listing the following variables: "simout" and
"time" (and perhaps others variables in the current workspace memory).
Now, you may create a plot of the system response identical to that shown in the
Scope output. The command for creating this plot is:
>>plot(time,simout);grid
Note that the outout format used in the example above is matrix type. The output sent
to workspace can be used for further analysis and storage in ascii format. Output to
workspace allows more options in plot presentation and further data analysis as the arrays are in ascii format.
Example 3. Using the same system presented in Example 2, we will simulate the response using
transfer function approach.
STEP 1 In a new Simulink model window, drag the following blocks from the Simulink library
window: Step (from Sources), Transfer Function (from Continous),Scope (from Sinks),
and Save File to Workspace (from Sinks).
STEP 2 Arrange the blocks as shown in Figure E3-1 below.
Figure E3-1
NOTE: Block's background colour: Right click on the block and select the colour from
Background Color menu.
49
STEP 3 Entering blocks' parameters values.
We'll use the same values for m, c, and k as in Example 2. Double click on the transfer
function to bring up the parameter diaglog window and enter the values for the
coefficients in the denominator as shown in Figure E3-2.
Note that the Transfer function block has a defaut form of first order in the
denominator (s+1). You may specify different order for the numerator and the
denominator by entering the coefficients associated with the polynomials.
Figure E3-2
Click OK to close the dialog.Double click on the Save Output To A File block to open the
dialog window as shown in Figure E3-3. In the Filename box specify the path and the
name of the file you wish to save. The saved file will be in .MAT format (yes, it's in
binary format! So don't try to read it). You will be able to load this file to Matlab
workspace later on. Make sure to remember where you save the file to. In this
example, I'll put the file in my D drive under "temp" directory and name the file
"example3out.mat". You may choose other convenient location on your computer.
In the Variable name box, enter a name of your choice. Here I name the variable
"simout".
Leave other parameters in defaut settings unless you wish to obtain more plot points
by changing the Sample Time setting.
Figure E3-3
STEP 4 Run the simulation by clicking on the button (alternately you may use keyboard command CTRL+T ). The screenshot of the output from the Scope block is show in
Figure E3-4.
50
Figure E3-4
Now by comparing Figure E2-3 and Figure E3-4 you will see that the reponses are
identical. No surprise here since these figures effectively represent the same system,
only the latter involves fewer number of blocks!
LOADING MAT FILE
Use the load command to "import" the save *.mat file generated from the simulation.
Note: In this example, I set the path to the directory where the file "example3out.mat"
is saved. If you do not set the path in Matlab, you have to specify the full path in the
load command, e.g., >>load D:/temp/example3out.mat.
In Matlab command window, enter the followings:
>> load example3out
You may want to verify the loading by asking Matlab to list all of the variables in the
current workspace:
>> who
If the loading is successful, you should see the variable you specified earlier listed the
current workspace. In this example, Matlab echos:
Your variables are:
simout
"simout" is a 2 x m matrix, where m is number of columns reflecting the number of
data points generated from the simulation. The first row contains the time array.
To generate a plot of the step input response from the simulation, simply use the plot
command on "simout" matrix. For this example, the following command produces the
plot shown in Figure E3-5.
>> plot(simout(1,:),simout(2,:));grid
51
Figure E3-5
In summary, the simulations of a second-order continuous system modeled by
Equation 2 have been shown using two different approaches. Different file output options from Simulink were also demonstrated.
Example 4.
In this example, we'll consider the same system as described in Example 3. But instead of using step
input, we'll excite the second-order system with impulse load. In addition, we will simulate the
response using a state-space model.
NOTES ON IMPULSE FUNCTION
Impulse function is useful in the simulatoin of impact or sudden loads such as the striking of a the tip
of the pole against a ball in a pool game. Unit impulse function at a desired instant a is defined by
(4)
Equation 4 is also known as Dirac delta function.
To simulate unit impulse in Simulink, we'll use a two-block step function set as shown below.
SOME NOTES ON STATE-SPACE APPROACH
The concept of the state of the system is utilized extensively in the time-domain analysis and design
of control systems. The state variables (along with the input functions) used in equations describing
the dynamics of a system provide the future state of the system. Mathematically, the state of the
system is described by a set of first-order differential equation in terms of state variables.
For our example, we will express the natural state variables,e.g., position and velocity, of the system
in terms of the following variables:
(5)
where x1 represents the position and x2 represents the velocity of the system. With the new state
variables defined in Eq. 5, Eq. 3 becomes
(6)
In a matrix form:
(7)
Equation 7 may be expressed in a more compact form:
52
(8)
where A is known as the system matrix and B as the input matrix.
The output equation is expressed by
(9)
where
(10)
and
(11)
C is called the output matrix and D is called the direct transmittance matrix.
MATLAB AND SIMULINK APPLICATION
In this problem we will first ask Matlab to convert the transfer function as shown in Figure E3-1 using
the following command:
>> [A,B,C,D]=tf2ss(1,[2,0.7,1])
NOTE: You are encouraged to read the help file on tf2ss function (>> help tf2ss).
Matlab's answers:
Now, let's get back to SIMULINK window and construct the necessary blocks as shown below. Note
that the additional blocks (Transfer Fcn and its "scope") shown in light blue are provided for
comparison with the the output from state-space block.
53
As demonstrated in previous examples, you may change the parameters in the state-space block or
any other block by double clicking on it to bring up a parameter editing window.
For state space model, enter the following parameters:
A: [-0.35 -0.5;1 0]
B: [1;0]
C: [0 0.5] D: 0
Once the entries are completed, click OK button to close the panel and continue on making
necessary entries for other blocks.
For the impulse simulation:
In this example, let's consider an unit impulse at 0.2 second with pulse duration of 0.01 second and
a magnitude of 40. To simulate this impulse, we'll enter in the first block (Step start) the following
parameters (double click on the block to bring up the parameter windows):
Step time: 0.2
Initial value: 0
Final value: 40
For the second block (Step end):
Step time: 0.21
Initial value: 0 Final value: 40
This will produce the following impulse:
NOTES: The choice of pulse duration should be made carefully. A duration that is too short may lead
to computational error. An excessively long duration could misrepresent the dynamics of the
modeled system.
To run the simulation use keystrokes: CTRL+T or click on the button.
To change the simulation parameters and make adjustment to simulation duration, press CTRL+E or
choose Simulation parameters... from Simulation menu.
Enter 30 for Stop time.
54
The screenshot below shows the impulse response of the system described by Eq. 2 with m = 2; k =
1; c=0.7
For the fun of it, you may want to make adjustments to damping ratio and/or spring stiffness
paramaters and run the simulation again to see how these changes would affect the response to the
impulse input.
_________________________________
References and further readings:
1.Ogata, K., Modern Control Engineering, 3rd. Ed., Prentice Hall, NJ, 1997
2.Dorf, R., Bishop, R., Modern Control Systems, 8th Ed., Addison-Wesley, CA, 1998
3.Mathworks' documentations on Simulink