Appendix C: Introduction
to MATLAB® and Simulink®
C.1 INTRODUCTION
MATLAB® is a technical computing environment (program) designed for numerical computation
and visualization. It is a standard tool in many universities and research organizations for perform-
ing mathematical calculations. Originally written to provide access to matrix manipulation soft-
ware, MATLAB has developed into a powerful tool to simplify mathematical analysis.
In order to use MATLAB successfully, the student should understand how to enter and manip-
ulate variables, how to model control systems in MATLAB, and how to produce plots and graphs
depicting the performance specifications of control systems. This appendix is intended to guide
the student through the MATLAB functions that are useful in understanding and accomplish-
ing these tasks. Students are encouraged to use the documentation provided with MATLAB to
explore more advanced problems.
The examples shown here were developed originally for MATLAB version 6.1, Release 12.1, for
Windows 98. They have been verified using MATLAB Release 2012b (version 8.0) for Windows XP
and Windows 7. There may be variations in other versions or releases for other platforms. Many of
the commands shown here are in the Control Systems Toolbox, which is available as an add-on to
the basic MATLAB program. Companion files specific to this text are available at the text web page
on http://www.crcpress.com/product/isbn/9781466504264.
C.2 BASICS
MATLAB is a window-based workspace environment in which variables are entered and manipu-
lated. The MATLAB program is started by double clicking the MATLAB icon in the Windows
desktop. This opens a window similar to that shown in Figure C.1. Commands are entered in the
command window, which is the inner window as shown on the right side of Figure C.1 Two right
arrows (>>) is the command prompt, indicating that the program is ready for the next command.
Variables are created as they are entered and are stored in the workspace. Variable names must
begin with a letter. A variable to represent a = 1.7 may be entered as follows:
>> alpha=1.7;
Placing the variable name “alpha” to the left of the equal sign defines alpha as whatever is on the
right side of the equal sign.
MATLAB displays the variable upon entry unless a semicolon is placed at the end of the line,
that is,
>> beta=alpha*3.7 %Optional comment
beta =
6.2900
A percent sign provides a mean to include a comment. Everything to the right of a percent sign
is ignored by MATLAB. In MATLAB R2011b, a workspace window lists the variables that are
defined as shown on the right side of Figure C.1.
595
596 Appendix C: Introduction to MATLAB® and Simulink®
FIGURE C.1 MATLAB® window.
C.2.1 Matrices
Matrices are entered a row at a time as follows:
>> A= [11 12 13
21 22 23
31 32 33]
The carriage return is implied at the end of each line and is not explicitly shown in this text.
MATLAB displays the variables upon entry unless a semicolon is placed at the end of the line.
Semicolons are also used to simplify and conserve space. The same 3 × 3 matrix may be entered
as follows:
>> A=[11 12 13; 21 22 23; 31 32 33]; % Optional Comment
Matrices are indexed in (row, column) format. For example, a single element of a matrix can be
referenced as follows:
>> A(2,3)
This gives the result
ans =
23
C.2.2 Matrix Transpose
Matrices are transposed using a prime notation:
>> B = A′
Appendix C: Introduction to MATLAB® and Simulink® 597
Produces
B =
11 21 31
12 22 32
13 23 33
C.2.3 Solution of Simultaneous Equations
One common use of matrices is solving simultaneous equations. MATLAB provides a matrix divi-
sion function that is useful for solving simultaneous equations. If A is square, the result of X = A\B
is the solution to the linear system A*X = B.
For example, given the set of simultaneous equations,
A1 + A2 + A3 = 6
−2 A1 − 3 A2 + 5 A3 = 7
4 A1 + 9 A2 + 25 A3 = 97
The solution is determined as follows:
>> A=[1 1 1;−2 −3 5; 4 9 25]
A =
1 1 1
−2 −3 5
4 9 25
>> B=[6; 7; 97]
B =
6
7
97
>> X = A\B
X =
1.0000
2.0000
3.0000
And indeed, A1 = 1, A2 = 2, A3 = 3, satisfies the set of simultaneous equations.
C.2.4 Range of Values
A colon is used to denote a range of values, that is, a matrix consisting of the first two rows of A is
denoted A(1:2,:), which stands for A(rows 1–2, all columns). A colon notation also can be used
to generate a vector of elements equally spaced over the range. The format for defining a vector x
whose elements range from an initial value to a final value is
>> x=[0:2*pi]; %[Initial value:Final value]
The step size is assumed to be 1 unless an optional step size is specified between the initial and final
values. A vector, used to plot data, may be defined as follows:
>>x=[0:.25:2*pi] %[Initial value:Step size:Final value]
598 Appendix C: Introduction to MATLAB® and Simulink®
MATLAB generates the vector:
x =
Columns 1 through 7
0 0.2500 0.5000 0.7500 1.0000 1.2500 1.5000
Columns 8 through 14
1.7500 2.0000 2.2500 2.5000 2.7500 3.0000 3.2500
Columns 15 through 21
3.5000 3.7500 4.0000 4.2500 4.5000 4.7500 5.0000
Columns 22 through 2 6
5.2500 5.5000 5.7500 6.0000 6.2500
Numerous common mathematical functions are available, such as
>> y = sin (x)
which generate a vector corresponding to the sine of each element of the vector x. Some other trigo-
nometric functions available in MATLAB are listed in Table C.1.
The data are plotted with the command
>> plot (x, y)
This command opens a plot window as shown in Figure C.2. The window has menu buttons across
the top that allow the user to rescale, annotate, edit, save, and print the plot.
Multiple traces can be shown on one plot as illustrated by the following commands:
z=cos(x);
subplot(2,1,1),plot(x,y) % Plot of 2 rows, 1 column
% Select the first subplot
title(‘Multiple Plots’) % Set title above first plot
grid % Turn grid on in first plot
ylabel(‘sin(x)’) % Set Y axis label
subplot(2,1,2),plot(x,z) % Select second subplot
grid % Turn grid on in second plot
xlabel(‘x’) % Set X axis label
ylabel(‘cos(x)’) % Set Y axis label
These commands generate the plot shown in Figure C.3.
TABLE C.1
MATLAB® Trigonometric Functions
sin Sine sec Secant
sinh Hyperbolic sine sech Hyperbolic secant
asin Inverse sine asec Inverse secant
asinh Inverse hyperbolic sine asech Inverse hyperbolic secant
cos Cosine csc Cosecant
cosh Hyperbolic cosine csch Hyperbolic cosecant
acos Inverse cosine acsc Inverse cosecant
acosh Inverse hyperbolic cosine acsch Inverse hyperbolic cosecant
tan Tangent cot Cotangent
tanh Hyperbolic tangent coth Hyperbolic cotangent
atan Inverse tangent acot Inverse cotangent
atan2 Four quadrant inverse tangent acoth Inverse hyperbolic cotangent
atanh Inverse hyperbolic tangent
Appendix C: Introduction to MATLAB® and Simulink® 599
FIGURE C.2 MATLAB® plot window.
FIGURE C.3 Multiple plots in one window: sine plot (top figure); cosine plot (bottom figure).
600 Appendix C: Introduction to MATLAB® and Simulink®
Note that the titles and labels can be set from the command line or within the plot window using
the buttons across the top of the window. A number of line styles and colors may be specified as
described by the command:
>> help plot options
Typing “help” at the prompt will provide an outline of the help available in the command win-
dow. More extensive help features are accessed through the help menu button near the top of the
MATLAB window.
C.2.5 Scripts (M-Files) and MAT-Files
MATLAB allows the user to define scripts containing several commands in files. Scripts (histori-
cally called M-Files) are stored in the current directory as “filename.m” and are executed from the
command line by typing the file name without the .m extension. Scripts may be created and edited
from the MATLAB window by using the “New script” or “Open file” buttons on the toolbar
Workspace variables also may be saved by typing “save filename”. This creates a MAT-File
in the current directory named “filename.mat”. The variables are loaded back into the workspace
by typing “load filename”.
C.3 DEFINING SYSTEMS
The majority of this text involves working with dynamic systems defined in the s-plane by trans-
fer functions. Polynomials in the s-plane are represented by a vector of coefficients of decreasing
power of s. For example, the polynomial s3 + 2s2 + 5 is represented by the vector [1 2 0 5], which is
a list of the coefficients of 1s3 + 2s2 + 0s1 + 5s0. All coefficients including the zero must be included
in the vector. Polynomials are multiplied by convolution of the representative vectors. Hence, the
polynomial
poly = s(s + 3)(s + 10) = s 3 + 13s 2 + 30s (C.1)
is formed as follows:
>> poly = conv ([l 0],conv([l 3], [1 10]))
poly =
1 13 30 0
The roots of the polynomial are calculated using the “roots” command:
>> roots (poly)
ans =
0
−10
−3
C.3.1 Transfer Function Model
A transfer function is a ratio of polynomials in s; hence, the transfer function
num s+5 s+5
= = 3 (C.2)
den s(s + 3)(s + 10) s + 13s 2 + 30s
Appendix C: Introduction to MATLAB® and Simulink® 601
is formed as follows:
>> num=[1 5];
>> den=conv([l 0]conv([l 3],[1 10]))
den =
1 13 30 0
The “TF” command is used to generate a linear time-invariant (LTI) transfer function system model
object, “sys”, from the numerator and denominator polynomials. This transfer function system
model object is subsequently used for analysis as shown in Section C.4:
>> sys = tf (num, den)
Transfer function:
s + 5
------------------
sˆ3 + 13 sˆ2 + 30 s
C.3.2 State-Space Model
State-space models are entered as matrices. In Section 5.13, a direct current (dc) servomotor is mod-
eled by Equation 5.135. Augmenting the system with θμ = ω yields the third-order state-space equation:
θ µ 0 1 0
θµ 0
− Bm Kt
x = Ax + Bu = ω m = 0 ωm + 0 ea (C.3)
im Jm Jm
im 1
0 −Kb − Rm
Lm
Lm Lm
θµ
y = Cx + Du = θµ = 1 0 0 ωm + [0]ea (C.4)
im
A very small 12 V dc servomotor has the characteristics provided later, which are converted to SI
units (see Appendix D) to develop the A and B matrices. The units of the variables are the following:
θ is in radians, ω is in rad/s, i is in amperes, and e is in volts:
oz-in.
Bm = 0.013 oz.-in. K t = 1.223
A
mV
Lm = 0.75 mH K b = 0.905
rpm
J = 0.085 × 10 −4 oz.-in.-s2 Rm = 24 Ω
0 1 0
A = 0 −1530 144,000 (C.5)
0 −11.5 −32,000
602 Appendix C: Introduction to MATLAB® and Simulink®
0
B= 0 (C.6)
1330
The following commands are used to enter the state-space model to generate a linear time-
invariant (LTI) system model object, sys2. This state-space model object may be used for
analysis like the transfer function system model object. These commands have been saved in
an m-file named “dcservo.m”, which is available at the text web page, http://www.crcpress.com/
product/isbn/9781466504264, and can be executed by typing “dcservo” at the command
prompt:
A=[0 1 0 % Define the A matrix
0 −1530 144000
0 −11.5 −32000];
B=[0 ; 0 ; 1330]; % Define the B matrix
C=[1 0 0]; % Define the C matrix
D=[0]; % Define the D matrix
sys2=ss(A,B,C,D) % Generate state space model
which produces the state and output equations:
a =
x1 x2 x3
x1 0 1 0
x2 0 −1530 1.44e+005
x3 0 −11.5 −3.2e+004
b =
u1
x1 0
x2 0
x3 1330
c =
x1 x2 x3
y1 1 0 0
d =
u1
y1 0
Continuous-time state-space model.
C.4 ANALYSIS
C.4.1 Root Locus
The LTI system model object is used for analysis. The root locus for a unity feedback system is
presented in Chapter 10. The root locus is plotted in MATLAB using the “rlocus” command:
>> rlocus(sys) % Plots a root locus for sys
or
>> rlocus(sys,K) % Plots a root locus with
% user-specified vector
% of gains K
Appendix C: Introduction to MATLAB® and Simulink® 603
FIGURE C.4 Root locus SISOTOOL window.
A more advanced interface for root-locus analysis and design is the “SISOTOOL” interface. The
“SISOTOOL” is a graphical user interface that facilitates compensator design and is started with
the command:
>> sisotool(‘rlocus’,sys) % Start root-locus design tool
This command opens a new window, plots the root locus as shown in Figure C.4, and allows the
user to specify a gain or add compensator components by placing poles and zeros on the plot.
Design constraints such as desired damping ratio or peak overshoot can be set within the tool and
appear as bounds on the plot. The closed-loop poles are shown as little squares on the locus. They
can be moved with the mouse to adjust the loop gain. Figure C.4 shows the closed-loop poles for
a gain of 15 that places the dominant poles for a damping ratio of ζ = 0.707. The Analysis menu
provides an option to plot a closed-loop step response as shown in Figure C.5. The closed-loop
transfer function is exported to the workspace with the File menu. For this example, the closed-
loop transfer function is
>> T_r2y
Zero/pole/gain from input “r” to output “y”:
15.0461 (s+5)
-------------------------------
(s+8.882) (sˆ2 + 4.118s + 8.47)
604 Appendix C: Introduction to MATLAB® and Simulink®
FIGURE C.5 Step response.
C.4.2 Sampled-Data Systems
MATLAB also works with sampled-data systems as described in Chapters 18 and 19. The MATLAB
commands to enter the sampled-data transfer function
z +1
G( z) =
z 2 − 1.5z + 0.5
with a sample time of T = 0.05 s are
>> Tsamp = 0.05;
>> Gofz=tf([1 1],[1 −1.5 0.5],Tsamp)
The SISOTOOL also works with discrete systems. Design is accomplished in the z domain as
shown in Figure C.6.
C.4.3 Frequency Response
Frequency response is presented in Chapters 11 and 12. Frequency response plots are generated for
LTI system models using the command
>> bode(sys)
which generates a Bode diagram as shown in Figure C.7 for Equation C.2. Another example is
shown in Section 12.9. Nichols and Nyquist plots are generated with the commands:
>> nichols(sys)
or
>> nyquist(sys)
Appendix C: Introduction to MATLAB® and Simulink® 605
FIGURE C.6 Digital root locus SISOTOOL window.
Bode diagram
50
0
Magnitude (dB)
–50
–100
–150
–90
Phase (deg)
–135
–180
10–1 100 101 102 103
Frequency (rad/s)
FIGURE C.7 Bode diagram of an example transfer function.
606 Appendix C: Introduction to MATLAB® and Simulink®
The “SISOTOOL” described earlier also provides options for designing on a Bode or Nichols chart.
The command
>> sisotool(‘bode’,sys) % Start bode plot design tool
opens the “SISOTOOL” with the Bode plots as shown in Figure C.8. The command
>> sisotool(‘nichols’,sys)% Nichols chart design tool
opens the “SISOTOOL” with the Nichols chart as shown in Figure C.9. With either view, the user
can adjust gain or add compensator poles and zeros and immediately see the resulting loop charac-
teristics. The Nichols chart shown in Figure C.9 includes a grid and depicts the plot of Lm G vs. φG,
which can be raised to lie tangent to the M-contour design constraint shown.
C.5 SIMULATION
Control systems are commonly evaluated by simulating the response to a step and an impulse
inputs. The “step”and “impu1se” commands generate plots of the step and impulse response,
respectively. When invoked with arguments to the left of the equal sign as shown,
>> [y,t]=step(sys)
or
>> [y,t]=impulse(sys)
the output vector “y” and time vector “t” that are generated automatically for the plot are defined
in the workspace. These vectors are available then for use elsewhere.
It is often desirable to specify the input as a function of time to generate simulations that are
more complex than the step and impulse inputs. This is done by defining an input vector “u” and
the corresponding time vector “t”. These vectors are used as inputs to the “lsim” command that
simulates the response of a linear system as follows:
t=[0:.1:10]; %Define a simulation time
% vector
u=[ones(1,51) zeros(1,50)];%Define vector
% representing a pulse input
[y,t]=lsim(sys,u,t); %Simulate the response
plot(t,[y u]) %Plot the response
This example also illustrates the ones and zeros commands. A vector or matrix whose ele-
ments are all ones or zeros is defined with these commands, using arguments that are the size of
the vector or matrix desired. A related function is “eye(rows,columns)” that defines an identity
matrix or a nonsquare matrix with ones on the principal diagonal and zeros elsewhere:
>> eye(3) ans = 1 0 0
0 1 0
0 0 1
>> eye(3,5) ans = 1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
Appendix C: Introduction to MATLAB® and Simulink® 607
FIGURE C.8 Bode diagram SISOTOOL window.
FIGURE C.9 Nichols chart diagram SISOTOOL window with grid and bounds.
608 Appendix C: Introduction to MATLAB® and Simulink®
FIGURE C.10 Simulink® block diagram.
C.5.1 Simulink®
For simulations of more advanced system models, including nonlinear models, it is useful to run
Simulink®. Simulink is a graphical simulation tool that is started from the MATLAB command
window by typing “simulink” at the prompt. This opens a window with the Simulink block
library and provides an option for creating a new Simulink model. Blocks are selected and placed
on the model workspace to create a system block diagram as shown in Figure C.10. Simulink is
not discussed further since none of the problems within this text require anything as advanced as
Simulink.
C.6 IMPLEMENTATION OF RESULTS
Compensators are typically designed as continuous-time transfer functions. They may be imple-
mented with analog components, but it is more common to implement them in a digital control
system. MATLAB provides commands for transforming analog designs into the discrete domain.
To implement the lead filter Gc = (s + 3)/(s + 30) in a digital system with a sampling rate of 40 Hz,
the “c2d” function is used:
>> num=[1 3];
>> den=[1 30];
>> ts=l/40;
>> sys=tf(num,den)
Transfer function:
s + 3
− − − −
s + 30
>> sysd=c2d(sys,ts,‘zoh’)
Transfer function:
z − 0.9472
− − − −
z − 0.4724
Sampling time: 0.025
Appendix C: Introduction to MATLAB® and Simulink® 609
The discrete transfer function is used as described in Chapter 18. The “c2d” function provides
several transformation methods including the zero-order hold method shown here and the Tustin
transformation. In order to see enough digits of the function for useful purposes, it is necessary to
extract the information from the LTI model object within MATLAB. This is done by addressing
num, or numerator property, and den, or denominator property of the sysd object. Setting the
display format to “long” provides the required digits:
>> format long
>> sysd.num{1}
ans =
1.000000000000000 −0.947236655274101
>> roots(sysd.den{1})
ans =
0.472366552741015
There are numerous properties of numerous objects to explore. This appendix has provided most of
the detail needed to accomplish the homework problems in the text. The practicing engineer will
undoubtedly gain significant experience with MATLAB and learn much more. See the MATLAB
documentation and help files for the most useful and accurate information readily available.