Usingcontrol Matlab
Usingcontrol Matlab
Usingcontrol Matlab
User's Guide
R2018a
How to Contact MathWorks
Phone: 508-647-7000
v
Using Model Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-23
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-24
Model Creation
2
Transfer Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
Transfer Function Representations . . . . . . . . . . . . . . . . . 2-3
Commands for Creating Transfer Functions . . . . . . . . . . 2-4
Create Transfer Function Using Numerator and
Denominator Coefficients . . . . . . . . . . . . . . . . . . . . . . 2-4
Create Transfer Function Model Using Zeros, Poles, and
Gain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5
vi Contents
Other Model Types in Discrete Time Representations . . 2-23
vii
Frequency Response Data (FRD) Model with Time
Delay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-69
viii Contents
Use Model Arrays to Create Linear Parameter-Varying
Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-114
Approximate Nonlinear Systems using LPV Models . . . 2-115
Applications of Linear Parameter-Varying Models . . . . 2-116
Data Manipulation
3
Store and Retrieve Model Data . . . . . . . . . . . . . . . . . . . . . . 3-2
Model Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2
Specify Model Properties at Model Creation . . . . . . . . . . 3-2
Examine and Change Properties of an Existing Model . . . 3-3
ix
Configure Display Format of Transfer Function in
Factorized Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-18
Model Interconnections
4
Why Interconnect Models? . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
x Contents
Model Transformation
5
Conversion Between Model Types . . . . . . . . . . . . . . . . . . . 5-2
Explicit Conversion Between Model Types . . . . . . . . . . . 5-2
Automatic Conversion Between Model Types . . . . . . . . . 5-2
Recommended Working Representation . . . . . . . . . . . . . 5-3
xi
Model Simplification
6
Model Reduction Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
When to Reduce Model Order . . . . . . . . . . . . . . . . . . . . . 6-2
Choosing a Model Reduction Method . . . . . . . . . . . . . . . 6-4
xii Contents
Linear Analysis
xiii
Frequency Domain Analysis
8
Frequency-Domain Responses . . . . . . . . . . . . . . . . . . . . . . 8-2
Sensitivity Analysis
9
Model Array with Single Parameter Variation . . . . . . . . . . 9-2
xiv Contents
Passivity and Conic Sectors
10
About Passivity and Passivity Indices . . . . . . . . . . . . . . . 10-2
Control Design
xv
Classical Control Design
12
Choosing a Control Design Approach . . . . . . . . . . . . . . . 12-2
xvi Contents
Edit Compensator Dynamics . . . . . . . . . . . . . . . . . . . . . . 12-93
Compensator Editor . . . . . . . . . . . . . . . . . . . . . . . . . . 12-93
Graphical Compensator Editing . . . . . . . . . . . . . . . . . 12-96
Poles and Zeros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-97
Lead and Lag Networks . . . . . . . . . . . . . . . . . . . . . . . 12-97
Notch Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-98
xvii
State-Space Control Design
13
Extended and Unscented Kalman Filter Algorithms for
Online State Estimation . . . . . . . . . . . . . . . . . . . . . . . . 13-2
Extended Kalman Filter Algorithm . . . . . . . . . . . . . . . . 13-2
Unscented Kalman Filter Algorithm . . . . . . . . . . . . . . . 13-5
xviii Contents
Choosing an Automated Tuning Approach . . . . . . . . . . . 14-5
xix
Quick Loop Tuning of Feedback Loops in Control System
Tuner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-48
xx Contents
Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-84
Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-85
xxi
Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-114
Sensitivity Evaluation . . . . . . . . . . . . . . . . . . . . . . . . 14-115
Sensitivity Bound . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-116
Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-116
Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-117
xxii Contents
Desired Loop Shape . . . . . . . . . . . . . . . . . . . . . . . . . 14-144
Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-144
Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-146
xxiii
Controller Poles Goal . . . . . . . . . . . . . . . . . . . . . . . . . . 14-176
Purpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-176
Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-176
Constrain Dynamics of Tuned Block . . . . . . . . . . . . . 14-177
Keep Poles Inside the Following Region . . . . . . . . . . 14-177
Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-178
xxiv Contents
Speed Up Tuning with Parallel Computing Toolbox
Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-225
Loop-Shaping Design
15
Structure of Control System for Tuning With
looptune . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-2
Gain-Scheduled Controllers
16
Gain Scheduling Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-2
Gain Scheduling in Simulink . . . . . . . . . . . . . . . . . . . . . 16-2
Tune Gain Schedules . . . . . . . . . . . . . . . . . . . . . . . . . . 16-3
xxv
Tune Gain Schedules in Simulink . . . . . . . . . . . . . . . . . 16-15
Workflow for Tuning Gain Schedules . . . . . . . . . . . . . 16-15
xxvi Contents
Control System Tuning Examples
17
Tuning Multiloop Control Systems . . . . . . . . . . . . . . . . . . 17-3
xxvii
Multiloop Control of a Helicopter . . . . . . . . . . . . . . . . 17-216
Customization
Preliminaries
18
Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-2
xxviii Contents
Setting Toolbox Preferences
19
Toolbox Preferences Editor . . . . . . . . . . . . . . . . . . . . . . . . 19-2
Overview of the Toolbox Preferences Editor . . . . . . . . . 19-2
Opening the Toolbox Preferences Editor . . . . . . . . . . . . 19-2
Units Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-3
Style Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-5
Options Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-6
Control System Designer Pane . . . . . . . . . . . . . . . . . . . 19-7
xxix
Customizing Response Plots Using Plot Tools . . . . . . . 21-24
Properties You Can Customize Using Plot Tools . . . . . . 21-24
Opening and Working with Plot Tools . . . . . . . . . . . . . 21-24
Example of Changing Line Color Using Plot Tools . . . . 21-25
xxx Contents
Reliable Computations
23
Scaling State-Space Models . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-2
Why Scaling Is Important . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-2
When to Scale Your Model . . . . . . . . . . . . . . . . . . . . . . . . . . 23-2
Manually Scale Your Model . . . . . . . . . . . . . . . . . . . . . . . . . . 23-3
xxxi
Linear System Modeling
33
1
Other model attributes stored as model data include time units, names for the model
inputs or outputs, and time delays. For more information about setting and retrieving
model attributes, see “Model Attributes”.
1-2
See Also
Note All model objects are MATLAB® objects, but working with them does not require a
background in object-oriented programming. To learn more about objects and object
syntax, see “Role of Classes in MATLAB” (MATLAB).
See Also
More About
• “Control System Modeling with Model Objects” on page 1-4
• “Types of Model Objects” on page 1-7
1-3
1 Linear System Model Objects
For example, the following control system contains a prefilter F, a plant G, and a
controller C, arranged in a single-loop configuration. The model also includes a
representation of sensor dynamics, S.
You can represent each of the components as a model object. You do not need to use the
same type of model object for each component. For example, represent the plant G as a
zero-pole-gain (zpk) model with a double pole at s = -1; C as a PID controller, and F and
S as transfer functions:
G = zpk([],[-1,-1],1);
C = pid(2,1.3,0.3,0.5);
S = tf(5,[1 4]);
F = tf(1,[1 1]);
You can then combine these elements build models that represent your control system or
the control system as a whole. For example, create the open-loop response SGC:
open_loop = S*G*C;
To build a model of the unfiltered closed-loop response, use the feedback command:
T = feedback(G*C,S);
To model the entire closed-loop system response from r to y, combine T with the filter
transfer function:
Try = T*F;
1-4
Control System Modeling with Model Objects
The results open_loop, T, and Try are also linear model objects. You can operate on
them with Control System Toolbox™ control design and analysis commands. For example,
plot the step response of the entire system:
stepplot(Try)
When you combine Numeric LTI models, the resulting Numeric LTI model represents the
aggregate system. The resulting model does not retain the original data from the
combined components. For example, T does not separately keep track of the dynamics of
the components G, C, and S that are combined to create T.
1-5
1 Linear System Model Objects
See Also
feedback
Related Examples
• “Numeric Model of SISO Feedback Loop” on page 4-6
• “Multi-Loop Control System” on page 4-10
• “MIMO Control System” on page 4-19
More About
• “Types of Model Objects” on page 1-7
1-6
Types of Model Objects
1-7
1 Linear System Model Objects
The diagram illustrates the following two overlapping broad classifications of model
object types:
1-8
See Also
• Dynamic System Models vs. Static Models — In general, Dynamic System Models
represent systems that have internal dynamics, while Static Models represent static
input/output relationships.
• Numeric Models vs. Generalized Models — Numeric Models are the basic numeric
representation of linear systems with fixed coefficients. Generalized Models represent
systems with tunable or uncertain components.
See Also
More About
• “What Are Model Objects?” on page 1-2
• “Dynamic System Models” on page 1-10
• “Static Models” on page 1-12
• “Numeric Models” on page 1-13
• “Generalized Models” on page 1-16
1-9
1 Linear System Model Objects
Most commands for analyzing linear systems, such as bode, margin, and
linearSystemAnalyzer, work on most Dynamic System Model objects. For Generalized
Models, analysis commands use the current value of tunable parameters and the nominal
value of uncertain parameters. Commands that generate response plots display random
samples of uncertain models.
1-10
See Also
See Also
More About
• “Numeric Linear Time Invariant (LTI) Models” on page 1-13
• “Identified LTI Models” on page 1-14
• “Identified Nonlinear Models” on page 1-14
• “Generalized and Uncertain LTI Models” on page 1-16
• “Control Design Blocks” on page 1-16
1-11
1 Linear System Model Objects
Static Models
Static Models represent static input/output relationships and generalize the notions of
matrix and numeric array to parametric or uncertain arrays. You can use static models to
create parametric or uncertain expressions, and to construct Generalized LTI models
whose coefficients are parametric or uncertain expressions. The Static Models family
includes:
For more information about using these objects to create parametric models, see “Models
with Tunable Coefficients” on page 1-19. For information about creating uncertain static
models, see “Uncertain Real Parameters” (Robust Control Toolbox) and “Uncertain
Matrices” (Robust Control Toolbox).
1-12
Numeric Models
Numeric Models
Numeric Linear Time Invariant (LTI) Models
Numeric LTI models are the basic numeric representation of linear systems or
components of linear systems. Use numeric LTI models for modeling dynamic
components, such as transfer functions or state-space models, whose coefficients are
fixed, numeric values. You can use numeric LTI models for linear analysis or control
design tasks.
The following table summarizes the available types of numeric LTI models.
You can use Numeric LTI models to represent block diagram components such as plant or
sensor dynamics. By connecting Numeric LTI models together, you can derive Numeric
LTI models of block diagrams. Use Numeric LTI models for most modeling, analysis, and
control design tasks, including:
1-13
1 Linear System Model Objects
• Analyzing linear system dynamics using analysis commands such as bode, step, or
impulse.
• Designing controllers for linear systems using the Control System Designer app or
the PID Tuner GUI.
• Designing controllers using control design commands such as pidtune, rlocus, or
lqr/lqg.
The following table summarizes the available types of identified LTI models.
The following table summarizes the available types of identified nonlinear models.
1-14
Numeric Models
1-15
1 Linear System Model Objects
Generalized Models
Uncertain LTI Models are a special type of Generalized LTI model that include uncertain
coefficients but not tunable coefficients. For more information about using uncertain
models, see “Uncertain State-Space Models” (Robust Control Toolbox) and “Create
Uncertain Frequency Response Data Models” (Robust Control Toolbox).
1-16
Generalized Models
Tunable Control Design Blocks include tunable parameter objects as well as tunable
linear models with predefined structure. For more information about using tunable
Control Design Blocks, see “Models with Tunable Coefficients” on page 1-19.
If you have Robust Control Toolbox software, you can use uncertain Control Design Blocks
to model uncertain parameters or uncertain system dynamics. For more information
about using uncertain blocks, see “Uncertain LTI Dynamics Elements” (Robust Control
Toolbox), “Uncertain Real Parameters” (Robust Control Toolbox), and “Uncertain Complex
Parameters and Matrices” (Robust Control Toolbox).
The following tables summarize the available types of Control Design Blocks.
1-17
1 Linear System Model Objects
Generalized Matrices
Generalized Matrices extend the notion of numeric matrices to matrices that include
tunable or uncertain values.
If you have Robust Control Toolbox software, you can create uncertain matrices by
building rational expressions involving uncertain parameters such as ureal or
ucomplex.
For more information about generalized matrices and their applications, see “Models with
Tunable Coefficients” on page 1-19.
1-18
Models with Tunable Coefficients
• Model a tunable (or parametric) component of a control system, such as a tunable low-
pass filter.
• Model a control system that contains both:
You can use tunable Generalized LTI models for parameter studies. For an example, see
“Study Parameter Variation by Sampling Tunable Model” on page 9-9. You can also use
tunable Generalized LTI models for tuning fixed control structures using tuning
commands such as systune or the Control System Tuner app. See “Multiloop,
Multiobjective Tuning”.
To create tunable components with a specific custom structure that is not covered by the
Control Design Blocks:
1 Use the tunable real parameter realp or the generalized matrix genmat to
represent the tunable coefficients of your component.
2 Use the resulting realp or genmat objects as inputs to tf or ss to model the
component. The result is a generalized state-space (genss) model of the component.
1-19
1 Linear System Model Objects
1 Model the nontunable components of your system using numeric LTI models on page
1-13.
2 Model each tunable component using Control Design Blocks or expressions involving
such blocks. See “Modeling Tunable Components” on page 1-19.
3 Use model interconnection commands such as series, parallel or connect, or
the arithmetic operators +, -, *, /, \, and ^, to combine all the components of your
system.
For an example of constructing a genss model of a control system with both fixed and
tunable components, see “Control System with Tunable Components” on page 2-83.
1-20
Models with Tunable Coefficients
w z
H
u y
B1 0 ... 0
.
0 B2 ..
.. ..
. . 0
0 ... 0 BN
B
w and z represent the inputs and outputs of the Generalized model.
H represents all portions of the Generalized model that have fixed (non-parametric)
coefficients. H is:
B represents the parametric components of the Generalized model, which are the Control
Design Blocks B1, . . . , BN. The Blocks property of the Generalized model stores a list of
the names of these blocks. If the Generalized model has blocks that occur multiple times
in B1, . . . , BN, these are only listed once in the Blocks property.
To access the internal representation of a Generalized model, including H and B, use the
getLFTModel command.
1-21
1 Linear System Model Objects
This Standard Form can represent any control structure. To understand why, consider the
control structure as an aggregation of fixed-coefficient elements interacting with the
parametric elements:
external
inputs H
w
Fixed system
components
(actuators, external
sensors, etc.) outputs
y1
uN z
B1 BN
yN
u1
B2
...
y2
u2
u := [u1 ,…, uN ]
y := [ y1 ,… , yN ] ,
and group the tunable control elements B1, . . . , BN into the block-diagonal configuration
C. P includes all the fixed components of the control architecture—actuators, sensors, and
other nontunable elements—and their interconnections.
1-22
Using Model Objects
• Attach additional information to the model using model attributes (properties). See
“Model Attributes”.
• Manipulate the model using arithmetic and model interconnection operations. See
“Model Interconnection”.
• Analyze the model response using commands such as bode and step. See “Linear
Analysis”.
• Perform parameter studies using model arrays. See “Model Arrays”.
• Design compensators. You can:
1-23
1 Linear System Model Objects
References
[1] Dorf, R.C. and R.H. Bishop, Modern Control Systems, Addison-Wesley, Menlo Park, CA,
1998.
1-24
2
Model Creation
2-2
Transfer Functions
Transfer Functions
Transfer Function Representations
Control System Toolbox software supports transfer functions that are continuous-time or
discrete-time, and SISO or MIMO. You can also have time delays in your transfer function
representation.
N ( s)
G ( s) = ,
D( s )
of polynomials N(s) and D(s), called the numerator and denominator polynomials,
respectively.
You can represent linear systems as transfer functions in polynomial or factorized (zero-
pole-gain) form. For example, the polynomial-form transfer function:
s2 - 3 s - 4
G ( s) =
s2 + 5 s + 6
( s + 1) (s - 4)
G ( s) = .
( s + 2)( s + 3)
The tf model object represents transfer functions in polynomial form. The zpk model
object represents transfer functions in factorized form.
MIMO transfer functions are arrays of SISO transfer functions. For example:
Ès - 3˘
Ís + 4˙
G ( s) = Í ˙
Í s + 1˙
ÍÎ s + 2 ˙˚
2-3
2 Model Creation
Command Description
tf Create tf objects representing continuous-time or discrete-
time transfer functions in polynomial form.
zpk Create zpk objects representing continuous-time or discrete-
time transfer functions in zero-pole-gain (factorized) form.
filt Create tf objects representing discrete-time transfer
functions using digital signal processing (DSP) convention.
s
Create the transfer function G ( s ) = :
2
s + 3s + 2
num = [1 0];
den = [1 3 2];
G = tf(num,den);
num and den are the numerator and denominator polynomial coefficients in descending
powers of s. For example, den = [1 3 2] represents the denominator polynomial
s2 + 3s + 2.
Tip Alternatively, you can specify the transfer function G(s) as an expression in s:
s = tf('s');
2 Specify G(s) as a ratio of polynomials in s.
2-4
See Also
s
Create the factored transfer function G ( s ) = 5 :
( s + 1 + i) ( s + 1 - i) ( s + 2)
Z = [0];
P = [-1-1i -1+1i -2];
K = 5;
G = zpk(Z,P,K);
Z and P are the zeros and poles (the roots of the numerator and denominator,
respectively). K is the gain of the factored form. For example, G(s) has a real pole at s = –
2 and a pair of complex poles at s = –1 ± i. The vector P = [-1-1i -1+1i -2] specifies
these pole locations.
G is a zpk model object, which is a data container for representing transfer functions in
zero-pole-gain (factorized) form.
See Also
filt | tf | zpk
Related Examples
• “MIMO Transfer Functions” on page 2-28
• “State-Space Models” on page 2-6
• “Discrete-Time Numeric Models” on page 2-23
More About
• “What Are Model Objects?” on page 1-2
• “Store and Retrieve Model Data” on page 3-2
2-5
2 Model Creation
State-Space Models
State-Space Model Representations
State-space models rely on linear differential equations or difference equations to
describe system dynamics. Control System Toolbox software supports SISO or MIMO
state-space models in continuous or discrete time. State-space models can include time
delays. You can represent state-space models in either explicit or descriptor (implicit)
form.
dx
= Ax + Bu
dt
y = Cx + Du
where x is the state vector. u is the input vector, and y is the output vector. A, B, C, and D
are the state-space matrices that express the system dynamics.
x [ n + 1] = Ax[ n] + Bu [ n]
y [ n] = Cx [ n ] + Du [ n]
where the vectors x[n], u[n], and y[n] are the state, input, and output vectors for the nth
sample.
2-6
State-Space Models
dx
E = Ax + Bu
dt
y = Cx + Du
where x is the state vector. u is the input vector, and y is the output vector. A, B, C, D, and
E are the state-space matrices.
Command Description
ss Create explicit state-space model.
dss Create descriptor (implicit) state-space model.
delayss Create state-space models with specified time delays.
dx
= Ax + Bu
dt
y = Cx + Du
where the state variables are the angular position θ and angular velocity dθ/dt:
Èq ˘
x = Í dq ˙ ,
Í ˙
ÎÍ dt ˙˚
2-7
2 Model Creation
u is the electric current, the output y is the angular velocity, and the state-space matrices
are:
È0 1˘ È0 ˘
A=Í ˙, B = Í ˙ , C = [ 0 1] , D = [ 0 ].
Î -5 -2 ˚ Î3 ˚
A = [0 1;-5 -2];
B = [0;3];
C = [0 1];
D = 0;
sys = ss(A,B,C,D);
sys is an ss model object, which is a data container for representing state-space models.
dx
E = Ax + Bu
dt
y = Cx + Du
use dss. This command creates a ss model with a nonempty E matrix, also called a
descriptor state-space model. See “MIMO Descriptor State-Space Models” on page 2-32
for an example.
See Also
delayss | dss | ss
Related Examples
• “MIMO State-Space Models” on page 2-31
• “Transfer Functions” on page 2-3
• “Discrete-Time Numeric Models” on page 2-23
2-8
See Also
More About
• “What Are Model Objects?” on page 1-2
• “Store and Retrieve Model Data” on page 3-2
2-9
2 Model Creation
For example, suppose you measure frequency response data for the SISO system you
want to model. You can measure such data by driving the system with a sine wave at a set
of frequencies ω1, ω2, ,...,ωn, as shown:
At steady state, the measured response yi(t) to the driving signal at each frequency ωi
takes the following form:
The measurement yields the complex frequency response G at each input frequency:
You can do most frequency-domain analysis tasks on frd models, but you cannot perform
time-domain simulations with them. For information on frequency response analysis of
linear systems, see Chapter 8 of [1].
Command Description
frd Create frd objects from frequency response data.
2-10
Frequency Response Data (FRD) Models
Command Description
frestimate Create frd objects by estimating the frequency response of a
Simulink® model. This approach requires Simulink Control
Design™ software. See “Frequency Response Estimation”
(Simulink Control Design) for more information.
load AnalyzerData
This command loads the data into the MATLAB workspace as the column vectors
freq and resp. The variables freq and resp contain 256 test frequencies and the
corresponding complex-valued frequency response points, respectively.
sys = frd(resp,freq);
sys is an frd model object, which is a data container for representing frequency
response data.
You can use frd models with many frequency-domain analysis commands. For example,
visualize the frequency response data using bode.
2-11
2 Model Creation
Tip By default, the frd command assumes that the frequencies are in radians/second. To
specify different frequency units, use the TimeUnit and FrequencyUnit properties of
the frd model object. For example:
sys = frd(resp,freq,'TimeUnit','min','FrequencyUnit','rad/TimeUnit')
See Also
frd | frestimate
Related Examples
• “MIMO Frequency Response Data Models” on page 2-37
• “Discrete-Time Numeric Models” on page 2-23
More About
• “What Are Model Objects?” on page 1-2
• “Store and Retrieve Model Data” on page 3-2
2-12
Proportional-Integral-Derivative (PID) Controllers
Form Formula
Parallel (pid object) Ki Kd s
C = Kp + + ,
s Tf s + 1
where:
• Kp = proportional gain
• Ki = integrator gain
• Kd = derivative gain
• Tf = derivative filter time
Standard (pidstd Ê ˆ
object) Á 1 Td s ˜
C = K p Á1 + + ˜,
Á Ti s Td
Á s + 1 ˜˜
Ë N ¯
where:
• Kp = proportional gain
• Ti = integrator time
• Td = derivative time
• N = derivative filter divisor
2-13
2 Model Creation
Use a controller form that is convenient for your application. For example, if you want to
express the integrator and derivative actions in terms of time constants, use standard
form.
26 .2 4.3 s
Create the following parallel-form PID controller: C = 29 .5 + - .
s 0 .06 s + 1
Kp = 29.5;
Ki = 26.2;
Kd = 4.3;
Tf = 0.06;
C = pid(Kp,Ki,Kd,Tf)
C is a pid model object, which is a data container for representing parallel-form PID
controllers. For more examples of how to create PID controllers, see the pid reference
page.
Ê ˆ
Á 1 0 .15 s ˜
Create the following standard-form PID controller: C = 29 .5 Á 1 + + ˜.
ÁÁ 1.13s 0 .15 s + 1 ˜
˜
Kp = 29.5; Ë 2.3 ¯
Ti = 1.13;
Td = 0.15;
N = 2.3;
C = pidstd(Kp,Ti,Td,N)
2-14
See Also
C is a pidstd model object, which is a data container for representing standard-form PID
controllers. For more examples of how to create standard-form PID controllers, see the
pidstd reference page.
See Also
pid | pidTuner | pidstd | pidtune
Related Examples
• “Transfer Functions” on page 2-3
• “Discrete-Time Proportional-Integral-Derivative (PID) Controllers” on page 2-24
• “Two-Degree-of-Freedom PID Controllers” on page 2-16
More About
• “What Are Model Objects?” on page 1-2
• “Store and Retrieve Model Data” on page 3-2
2-15
2 Model Creation
You can represent PID controllers using the specialized model objects pid2 and
pidstd2. This topic describes the representation of 2-DOF PID controllers in MATLAB.
For information about automatic PID controller tuning, see “PID Controller Tuning”.
The relationship between the 2-DOF controller’s output (u) and its two inputs (r and y)
can be represented in either parallel or standard form. The two forms differ in the
parameters used to express the proportional, integral, and derivative actions of the
controller, as expressed in the following table.
2-16
Two-Degree-of-Freedom PID Controllers
Form Formula
Parallel (pid2 object) Ki K s
u = K p ( br - y ) + ( r - y) + d ( cr - y) .
s Tf s + 1
In this representation:
• Kp = proportional gain
• Ki = integrator gain
• Kd = derivative gain
• Tf = derivative filter time
• b = setpoint weight on proportional term
• c = setpoint weight on derivative term
Standard (pidstd2 object) È ˘
Í 1 Td s ˙
u = K p Í( br - y ) + (r - y) + T ( cr - y ) ˙ .
Í Ti s d ˙
s +1
ÍÎ N ˙˚
In this representation:
• Kp = proportional gain
• Ti = integrator time
• Td = derivative time
• N = derivative filter divisor
• b = setpoint weight on proportional term
• c = setpoint weight on derivative term
Use a controller form that is convenient for your application. For instance, if you want to
express the integrator and derivative actions in terms of time constants, use standard
form. For examples showing how to create parallel-form and standard-form controllers,
see the pid2 and pidstd2 reference pages, respectively.
2-17
2 Model Creation
Each of the components Cr(s) and Cy(s) is a PID controller, with different weights on the
proportional and derivative terms. For example, in continuous time, these components are
given by:
Ki cK d s
Cr ( s ) = bK p + + ,
s Tf s + 1
È K Kd s ˘
Cy ( s ) = - Í K p + i + ˙.
ÍÎ s Tf s + 1 ˙˚
You can access these components by converting the PID controller into a two-input, one-
output transfer function. For example, suppose that C2 is a 2-DOF PID controller, stored
as a pid2 object.
C2tf = tf(C2);
Cr = C2tf(1);
Cy = C2tf(2);
Cr(s) is the transfer function from the first input of C2 to the output. Similarly, Cy(s) is the
transfer function from the second input of C2 to the output.
2-18
Two-Degree-of-Freedom PID Controllers
Suppose that G is a dynamic system model, such as a zpk model, representing the plant.
Build the closed-loop transfer function from r to y. Note that the Cy(s) loop has positive
feedback, by the definition of Cy(s).
T = Cr*feedback(G,Cy,+1)
G.InputName = 'u';
G.OutputName = 'y';
C2.Inputname = {'r','y'};
C2.OutputName = 'u';
T = connect(G,C2,'r','y');
There are other configurations in which you can decompose a 2-DOF PID controller into
SISO components. For particular choices of C(s) and X(s), each of the following
configurations is equivalent to the 2-DOF architecture with C2(s). You can obtain C(s) and
X(s) for each of these configurations using the getComponents command.
Feedforward
For a continuous-time, parallel-form 2-DOF PID controller, the components are given by:
2-19
2 Model Creation
Ki Kd s
C ( s) = K p + + ,
s Tf s + 1
( c - 1 ) Kd s
X ( s) = ( b - 1 ) K p + .
Tf s + 1
[C,X] = getComponents(C2,'feedforward');
The following command constructs the closed-loop system from r to y for the feedforward
configuration.
T = G*(C+X)*feedback(1,G*C);
Feedback
For a continuous-time, parallel-form 2-DOF PID controller, the components are given by:
Ki cK d s
C ( s) = bK p + + ,
s Tf s + 1
(1 - c ) Kd s
X ( s) = (1 - b ) K p + .
Tf s + 1
2-20
Two-Degree-of-Freedom PID Controllers
[C,X] = getComponents(C2,'feedback');
The following command constructs the closed-loop system from r to y for the feedback
configuration.
T = G*C*feedback(1,G*(C+X));
Filter
In the filter configuration, the 2-DOF PID controller is decomposed into a conventional
SISO PID controller and a prefilter on the reference signal.
For a continuous-time, parallel-form 2-DOF PID controller, the components are given by:
Ki Kd s
C ( s) = K p + + ,
s Tf s + 1
X ( s) =
(bK pTf + cK d ) s2 + ( bK p + K iTf ) s + K i .
( K pTf + Kd ) s2 + ( K p + KiTf ) s + Ki
The filter X(s) can also be expressed as the ratio: –[Cr(s)/Cy(s)].
The following command constructs the closed-loop system from r to y for the filter
configuration.
T = X*feedback(G*C,1);
For an example illustrating the decomposition of a 2-DOF PID controller into these
configurations, see “Decompose a 2-DOF PID Controller into SISO Components” on page
5-8.
2-21
2 Model Creation
See Also
getComponents | pid2 | pidTuner | pidstd2 | pidtune
Related Examples
• “Discrete-Time Proportional-Integral-Derivative (PID) Controllers” on page 2-24
• “Proportional-Integral-Derivative (PID) Controllers” on page 2-13
More About
• “What Are Model Objects?” on page 1-2
• “Store and Retrieve Model Data” on page 3-2
2-22
Discrete-Time Numeric Models
z
Create the transfer function G ( z ) = with a sample time of 0.1 s.
2
z - 2z - 6
num = [1 0];
den = [1 -2 -6];
Ts = 0.1;
G = tf(num,den,Ts)
num and den are the numerator and denominator polynomial coefficients in descending
powers of z. G is a tf model object.
The sample time is stored in the Ts property of G. Access the sample time Ts, using dot
notation:
G.Ts
See Also
frd | ss | tf | zpk
More About
• “What Are Model Objects?” on page 1-2
2-23
2 Model Creation
Form Formula
Parallel (pid) Kd
C = K p + Ki IF ( z) + ,
Tf + DF ( z )
where:
• Kp = proportional gain
• Ki = integrator gain
• Kd = derivative gain
• Tf = derivative filter time
Standard (pidstd) Ê ˆ
Á 1 Td ˜
C = K p Á 1 + IF ( z) + ˜,
Á Ti Td
Á + DF ( ) ˜˜
z
Ë N ¯
where:
• Kp = proportional gain
• Ti = integrator time
• Td = derivative time
• N = derivative filter divisor
2-24
Discrete-Time Proportional-Integral-Derivative (PID) Controllers
Form Formula
2-DOF Parallel (pid2) The relationship between the 2-DOF controller’s output (u) and
its two inputs (r and y) is:
Kd
u = K p ( br - y ) + Ki IF ( z ) ( r - y ) + ( cr - y) .
Tf + DF ( z )
In this representation:
• Kp = proportional gain
• Ki = integrator gain
• Kd = derivative gain
• Tf = derivative filter time
• b = setpoint weight on proportional term
• c = setpoint weight on derivative term
2-DOF Standard È ˘
(pidstd2 object) Í 1 Td ˙
u = K p Í( br - y ) + IF ( z) ( r - y) + ( cr - y) ˙ .
Í Ti Td ˙
+ DF ( z )
ÍÎ N ˙˚
In this representation:
• Kp = proportional gain
• Ti = integrator time
• Td = derivative time
• N = derivative filter divisor
• b = setpoint weight on proportional term
• c = setpoint weight on derivative term
In all of these expressions, IF(z) and DF(z) are the discrete integrator formulas for the
integrator and derivative filter, respectively. Use the IFormula and DFormula properties
of the controller objects to set the IF(z) and DF(z) formulas. The next table shows
available formulas for IF(z) and DF(z). Ts is the sample time.
2-25
2 Model Creation
If you do not specify a value for IFormula, DFormula, or both when you create the
controller object, ForwardEuler is used by default. For more information about setting
and changing the discrete integrator formulas, see the reference pages for the controller
objects, pid, pidstd, pid2, and pidstd2.
Ts z + 1 Tz
This command creates a pidstd model with IF ( z) = and DF ( z ) = s .
2 z -1 z -1
You can set the discrete integrator formulas for a parallel-form controller in the same way,
using pid.
2-26
See Also
b = 0.5;
c = 0;
Ts = 0.1;
C2 = pidstd2(Kp,Ti,Td,N,b,c,Ts,'IFormula','Trapezoidal')
C2 =
1 Ts*(z+1)
u = Kp * [(b*r-y) + ---- * -------- * (r-y)]
Ti 2*(z-1)
Setting Td = 0 specifies a PI controller with no derivative term. As the display shows, the
values of N and c are not used in this controller. The display also shows that the
trapezoidal formula is used for the integrator.
See Also
pid | pid2 | pidstd | pidstd2
Related Examples
• “Proportional-Integral-Derivative (PID) Controllers” on page 2-13
• “Two-Degree-of-Freedom PID Controllers” on page 2-16
More About
• “What Are Model Objects?” on page 1-2
• “Store and Retrieve Model Data” on page 3-2
2-27
2 Model Creation
È s-1 ˘
Í s+1 ˙
H ( s) = Í ˙.
Í s+ 2 ˙
ÍÎ s2 + 4 s + 5 ˙˚
You can specify H(s) by concatenation of its SISO entries. For instance,
or, equivalently,
s = tf('s')
h11 = (s-1)/(s+1);
h21 = (s+2)/(s^2+4*s+5);
H = [h11; h21]
This syntax mimics standard matrix concatenation and tends to be easier and more
readable for MIMO systems with many inputs and/or outputs.
Tip Use zpk instead of tf to create MIMO transfer functions in factorized form on page
2-5.
2-28
See Also
For example, for the rational transfer matrix H(s), the two cell arrays N and D should
contain the row-vector representations of the polynomial entries of
È s-1 ˘ È s +1 ˘
N ( s) = Í ˙, D( s) = Í ˙.
Îs + 2˚ Î s2 + 4 s + 5 ˚
s + 2
#2: -------------
s^2 + 4 s + 5
Notice that both N and D have the same dimensions as H. For a general MIMO transfer
matrix H(s), the cell array entries N{i,j} and D{i,j} should be row-vector
representations of the numerator and denominator of Hij(s), the ijth entry of the transfer
matrix H(s).
See Also
tf | zpk
Related Examples
• “Transfer Functions” on page 2-3
2-29
2 Model Creation
More About
• “What Are Model Objects?” on page 1-2
• “Store and Retrieve Model Data” on page 3-2
2-30
MIMO State-Space Models
# of columns =
# of inputs
A B
# of rows =
# of outputs C D
In this example, you create a state-space model for a rotating body with inertia tensor J,
damping force F, and three axes of rotation, related as:
dw
J + Fw = T
dt
y = w.
The system input T is the driving torque. The output y is the vector of angular velocities of
the rotating body.
2-31
2 Model Creation
dx
= Ax + Bu
dt
y = Cx + Du
rewrite it as:
dw
= - J -1 Fw + J -1T
dt
y = w.
A = - J -1 F, B = J -1 , C = I , D = 0.
These commands assume that J is the inertia tensor of a cube rotating about its corner,
and the damping force has magnitude 0.2.
sys_mimo is an ss model.
This example uses the same rotating-body system shown in “MIMO Explicit State-Space
Models” on page 2-31, where you inverted the inertia matrix J to obtain the value of the B
matrix. If J is poorly-conditioned for inversion, you can instead use a descriptor (implicit)
state-space model. A descriptor (implicit) state-space model is of the form:
2-32
MIMO State-Space Models
dx
E = Ax + Bu
dt
y = Cx + Du
Create a state-space model for a rotating body with inertia tensor J, damping force F, and
three axes of rotation, related as:
dw
J + Fw = T
dt
y = w.
The system input T is the driving torque. The output y is the vector of angular velocities of
the rotating body. You can write this system as a descriptor state-space model having the
following state-space matrices:
A = - F, B = I, C = I, D = 0, E = J.
These commands assume that J is the inertia tensor of a cube rotating about its corner,
and the damping force has magnitude 0.2.
The jet model during cruise flight at MACH = 0.8 and H = 40,000 ft. is
2-33
2 Model Creation
B = [ 0.0073 0
-0.4750 0.0077
0.1530 0.1430
0 0];
C = [0 1 0 0
0 0 0 1];
D = [0 0
0 0];
Use the following commands to specify this state-space model as an LTI object and attach
names to the states, inputs, and outputs.
sys_mimo = ss(A,B,C,D,'statename',states,...
'inputname',inputs,...
'outputname',outputs);
sys_mimo
a =
beta yaw roll phi
beta -0.0558 -0.9968 0.0802 0.0415
yaw 0.598 -0.115 -0.0318 0
roll -3.05 0.388 -0.465 0
phi 0 0.0805 1 0
b =
rudder aileron
beta 0.0073 0
yaw -0.475 0.0077
roll 0.153 0.143
2-34
MIMO State-Space Models
phi 0 0
c =
beta yaw roll phi
yaw rate 0 1 0 0
bank angle 0 0 0 1
d =
rudder aileron
yaw rate 0 0
bank angle 0 0
Continuous-time model.
The model has two inputs and two outputs. The units are radians for beta (sideslip angle)
and phi (bank angle) and radians/sec for yaw (yaw rate) and roll (roll rate). The rudder
and aileron deflections are in degrees.
tf(sys_mimo)
2-35
2 Model Creation
See Also
ss
Related Examples
• “State-Space Models” on page 2-6
More About
• “What Are Model Objects?” on page 1-2
• “Store and Retrieve Model Data” on page 3-2
2-36
MIMO Frequency Response Data Models
Frequency response data for a MIMO system includes a vector of complex response data
for each of the input/output (I/O) pair of the system. Thus, if you measure the frequency
response of each I/O pair of your system at a set of test frequencies, you can use the data
to create a frequency response model:
1 Load frequency response data in AnalyzerDataMIMO.mat.
load AnalyzerDataMIMO H11 H12 H21 H22 freq
This command loads the data into the MATLAB workspace as five column vectors
H11, H12, H21, H22, and freq. The vector freq contains 100 test frequencies. The
other four vectors contain the corresponding complex-valued frequency response of
each I/O pair of a two-input, two-output system.
The dimensions of Hresp are the number of outputs, number of inputs, and the
number of frequencies for which there is response data. Hresp(i,j,:) contains the
frequency response from input j to output i.
3 Create a frequency-response model.
H = frd(Hresp,freq);
H is an frd model object, which is a data container for representing frequency response
data.
You can use frd models with many frequency-domain analysis commands. For example,
visualize the response of this two-input, two-output system using bode.
2-37
2 Model Creation
Tip By default, the frd command assumes that the frequencies are in radians/second. To
specify different frequency units, use the TimeUnit and FrequencyUnit properties of
the frd model object. For example:
H = frd(Hresp,freq,'TimeUnit','min','FrequencyUnit','rad/TimeUnit')
See Also
frd
Related Examples
• “Frequency Response Data (FRD) Models” on page 2-10
More About
• “What Are Model Objects?” on page 1-2
• “Store and Retrieve Model Data” on page 3-2
2-38
Select Input/Output Pairs in MIMO Models
Note For more information about using cell arrays to create MIMO transfer
functions, see the tf reference page.
2 Select the response from the second input to the output of H.
H12 = H(1,2)
For any MIMO system H, the index notation H(i,j) selects the response from the jth
input to the ith output.
See Also
Related Examples
• “MIMO Transfer Functions” on page 2-28
• “MIMO State-Space Models” on page 2-31
More About
• “Store and Retrieve Model Data” on page 3-2
2-39
2 Model Creation
In discrete-time models, these properties are constrained to integer values that represent
delays expressed as integer multiples of the sample time. To approximate discrete-time
models with delays that are a fractional multiple of the sample time, use thiran.
To create the following first-order transfer function with a 2.1 s time delay:
1
G ( s ) = e-2.1s ,
s + 10
enter:
G = tf(1,[1 10],'InputDelay',2.1)
where InputDelay specifies the delay at the input of the transfer function.
Tip You can use InputDelay with zpk the same way as with tf:
G = zpk([],-10,1,'InputDelay',2.1)
For SISO transfer functions, a delay at the input is equivalent to a delay at the output.
Therefore, the following command creates the same transfer function:
G = tf(1,[1 10],'OutputDelay',2.1)
Use dot notation to examine or change the value of a time delay. For example, change the
time delay to 3.2 as follows:
2-40
Time Delays in Linear Systems
G.OutputDelay = 3.2;
ans =
3.2000
Tip An alternative way to create a model with a time delay is to specify the transfer
function with the delay as an expression in s:
1 Create a transfer function model for the variable s.
s = tf('s');
2 Specify G(s) as an expression in s.
G = exp(-2.1*s)/(s+10);
dx ( t )
= -2 x ( t ) + 3u ( t - 1 .5 )
dt
È x ( t - 0 .7 ) ˘
y (t ) = Í ˙.
Î - x (t ) ˚
This system has an input delay of 1.5. The first output has an output delay of 0.7, and the
second output is not delayed.
Note In contrast to SISO transfer functions, input delays are not equivalent to output
delays for state-space models. Shifting a delay from input to output in a state-space model
requires introducing a time shift in the model states. For example, in the model of this
2-41
2 Model Creation
example, defining T = t – 1.5 and X(T) = x(T + 1.5) results in the following equivalent
system:
dX ( T )
= -2 X ( T ) + 3u ( T )
dT
È X ( T - 2 .2 ) ˘
y (T ) = Í ˙.
Î - X ( T - 1 .5 ) ˚
All of the time delays are on the outputs, but the new state variable X is time-shifted
relative to the original state variable x. Therefore, if your states have physical meaning,
or if you have known state initial conditions, consider carefully before shifting time delays
between inputs and outputs.
A = -2;
B = 3;
C = [1;-1];
D = 0;
2 Create the model.
G = ss(A,B,C,D,'InputDelay',1.5,'OutputDelay',[0.7;0])
G is a ss model.
Tip Use delayss to create state-space models with more general combinations of input,
output, and state delays, of the form:
N
dx
= Ax (t ) + Bu( t ) + Â ( Ajx (t - tj ) + Bju (t - t j))
dt j =1
N
y (t ) = Cx (t ) + Du (t ) + Â ( Cjx( t - tj) + Dju (t - tj ))
j =1
2-42
Time Delays in Linear Systems
È - 0 .1 2 s +1 ˘
Íe e - 0 .3
s s + 10 ˙
H (s ) = Í ˙.
Í 10 -0.2 s - 1 ˙
e
ÍÎ s + 5 ˙˚
Time delays in MIMO systems can be specific to each I/O pair, as in this example. You
cannot use InputDelay and OutputDelay to model I/O-specific transport delays.
Instead, use ioDelay to specify the transport delay across each I/O pair.
s = tf('s');
2 Use the variable s to specify the transfer functions of H without the time delays.
H is a two-input, two-output tf model. Each I/O pair in H has the time delay specified by
the corresponding entry in tau.
2-43
2 Model Creation
H = tf(2,[1 -0.95],0.1,'InputDelay',25)
H =
2
z^(-25) * --------
z - 0.95
If system has a time delay that is not an integer multiple of the sampling time, you can
use the thiran command to approximate the fractional portion of the time delay with an
all-pass filter. See “Time-Delay Approximation” on page 2-48.
See Also
Related Examples
• “Closing Feedback Loops with Time Delays” on page 2-45
• “Convert Time Delay in Discrete-Time Model to Factors of 1/z” on page 2-64
More About
• “Time-Delay Approximation” on page 2-48
2-44
Closing Feedback Loops with Time Delays
2.3 e-2.1s
r 0.5 + s +10
y
- s
C G
G is the plant model, which has an input delay. C is a proportional-integral (PI) controller.
G = tf(1,[1 10],'InputDelay',2.1);
C = pid(0.5,2.3);
T = feedback(C*G,1);
The time delay in T is not an input delay as it is in G. Because the time delay is internal to
the closed-loop system, the software returns T as an ss model with an internal time delay
of 2.1 seconds.
T.InternalDelay
2-45
2 Model Creation
step(T)
Note Most analysis commands, such as step, bode and margin, support models with
internal delays.
The internal time delay is stored in the InternalDelay property of T. Use dot notation
to access InternalDelay. For example, to change the internal delay to 3.5 seconds,
enter:
T.InternalDelay = 3.5
2-46
See Also
You cannot modify the number of internal delays because they are structural properties of
the model.
See Also
Related Examples
• “Convert Time Delay in Discrete-Time Model to Factors of 1/z” on page 2-64
More About
• “Internal Delays” on page 2-73
2-47
2 Model Creation
Time-Delay Approximation
Many control design algorithms cannot handle time delays directly. For example,
techniques such as root locus, LQG, and pole placement do not work properly if time
delays are present. A common technique is to replace delays with all-pass filters that
approximate the delays.
To approximate time delays in continuous-time LTI models, use the pade command to
compute a Padé approximation. The Padé approximation is valid only at low frequencies,
and provides better frequency-domain approximation than time-domain approximation. It
is therefore important to compare the true and approximate responses to choose the right
approximation order and check the approximation validity.
Use the thiran command to approximate a time delay that is a fractional multiple of the
sample time as a Thiran all-pass filter.
For a time delay of tau and a sample time of Ts, the syntax thiran(tau,Ts) creates a
discrete-time transfer function that is the product of two terms:
• A term representing the integer portion of the time delay as a pure line delay, (1/z)N,
where N = ceil(tau/Ts).
• A term approximating the fractional portion of the time delay (tau - NTs) as a Thiran
all-pass filter.
Discretizing a Padé approximation does not guarantee good phase matching between the
continuous-time delay and its discrete approximation. Using thiran to generate a
discrete-time approximation of a continuous-time delay can yield much better phase
matching. For example, the following figure shows the phase delay of a 10.2-second time
delay discretized with a sample time of 1 s, approximated in three ways:
2-48
See Also
The Thiran filter yields the closest approximation of the 10.2-second delay.
See the thiran reference page for more information about Thiran filters.
See Also
absorbDelay | pade | thiran
Related Examples
• “Time-Delay Approximation in Continuous-Time Open-Loop Model” on page 2-50
• “Convert Time Delay in Discrete-Time Model to Factors of 1/z” on page 2-64
• “Approximate Different Delays with Different Approximation Orders” on page 2-60
2-49
2 Model Creation
Padé approximation is helpful when using analysis or design tools that do not support
time delays.
1
u e-2.6s y
s 2 + 0.9s + 1
s = tf('s');
P = exp(-2.6*s)/(s^2+0.9*s+1);
Pnd1 = pade(P,1)
Pnd1 =
-s + 0.7692
----------------------------------
s^3 + 1.669 s^2 + 1.692 s + 0.7692
h = bodeoptions;
h.PhaseMatching = 'on';
bodeplot(P,'-b',Pnd1,'-.r',{0.1,10},h)
legend('Exact delay','First-Order Pade','Location','SouthWest')
2-50
Time-Delay Approximation in Continuous-Time Open-Loop Model
The magnitude of P and Pnd1 match exactly. However, the phase of Pnd1 deviates
from the phase of P beyond approximately 1 rad/s.
4 Increase the Padé approximation order to extend the frequency band in which the
phase approximation is good.
Pnd3 = pade(P,3);
5 Compare the frequency response of P, Pnd1 and Pnd3.
bodeplot(P,'-b',Pnd3,'-.r',Pnd1,':k',{0.1 10},h)
legend('Exact delay','Third-Order Pade','First-Order Pade',...
'Location','SouthWest')
2-51
2 Model Creation
stepplot(P,'-b',Pnd3,'-.r',Pnd1,':k')
legend('Exact delay','Third-Order Pade','First-Order Pade',...
'Location','Southeast')
2-52
Time-Delay Approximation in Continuous-Time Open-Loop Model
Using the Padé approximation introduces a nonminimum phase artifact (“wrong way”
effect) in the initial transient response. The effect is quite pronounced in the first-
order approximation, which dips significantly below zero before changing direction.
The effect is reduced in the higher-order approximation, which far more closely
matches the exact system’s response.
Note Using too high an approximation order may result in numerical issues and
possibly unstable poles. Therefore, avoid Padé approximations with order N>10.
2-53
2 Model Creation
See Also
pade
Related Examples
• “Time-Delay Approximation in Continuous-Time Closed-Loop Model” on page 2-55
More About
• “Time-Delay Approximation” on page 2-48
• “Internal Delays” on page 2-73
2-54
Time-Delay Approximation in Continuous-Time Closed-Loop Model
Padé approximation is helpful when using analysis or design tools that do not support
time delays.
0.15 e-4.2s s +1
r 0.06 + + 0.006s s2 + 0.68s + 1 y
- s
C G
s = tf('s');
G = (s+1)/(s^2+.68*s+1)*exp(-4.2*s);
C = pid(0.06,0.15,0.006);
Tcl = feedback(G*C,1);
Tcl.InternalDelay
ans = 4.2000
2 Compute the first-order Padé approximation of Tcl.
Tnd1 = pade(Tcl,1);
h = bodeoptions;
h.PhaseMatching = 'on';
bodeplot(Tcl,'-b',Tnd1,'-.r',{.1,10},h);
legend('Exact delay','First-Order Pade','Location','SouthWest');
2-55
2 Model Creation
The magnitude and phase approximation errors are significant beyond 1 rad/s.
4 Compare the time domain response of Tcl and Tnd1 using stepplot.
stepplot(Tcl,'-b',Tnd1,'-.r');
legend('Exact delay','First-Order Pade','Location','SouthEast');
2-56
Time-Delay Approximation in Continuous-Time Closed-Loop Model
Using the Padé approximation introduces a nonminimum phase artifact (“wrong way”
effect) in the initial transient response.
5 Increase the Padé approximation order to see if this will extend the frequency with
good phase and magnitude approximation.
Tnd3 = pade(Tcl,3);
6 Observe the behavior of the third-order Padé approximation of Tcl. Compare the
frequency response of Tcl and Tnd3.
bodeplot(Tcl,'-b',Tnd3,'-.r',Tnd1,'--k',{.1,10},h);
legend('Exact delay','Third-Order Pade','First-Order Pade',...
'Location','SouthWest');
2-57
2 Model Creation
The magnitude and phase approximation errors are reduced when a third-order Padé
approximation is used.
Increasing the Padé approximation order extends the frequency band where the
approximation is good. However, too high an approximation order may result in numerical
issues and possibly unstable poles. Therefore, avoid Padé approximations with order
N>10.
See Also
pade
2-58
See Also
Related Examples
• “Approximate Different Delays with Different Approximation Orders” on page 2-60
More About
• “Time-Delay Approximation” on page 2-48
• “Internal Delays” on page 2-73
2-59
2 Model Creation
Load a sample continuous-time open-loop system that contains internal and output time
delays.
load(fullfile(matlabroot,'examples','control','PadeApproximation1.mat'),'sys')
sys
sys =
A =
x1 x2
x1 -1.5 -0.1
x2 1 0
B =
u1
x1 1
x2 0
C =
x1 x2
y1 0.5 0.1
D =
u1
y1 0
sys is a second-order continuous-time ss model with internal delay 3.4 s and output
delay 1.5 s.
2-60
Approximate Different Delays with Different Approximation Orders
Use the pade function to compute a third-order approximation of the internal delay and a
first-order approximation of the output delay.
P13 = pade(sys,inf,1,3);
size(P13)
The three input arguments following sys specify the approximation orders of any input,
output, and internal delays of sys, respectively. inf specifies that a delay is not to be
approximated. The approximation orders for the output and internal delays are one and
three respectively.
Approximating the time delays with pade absorbs delays into the dynamics, adding as
many states to the model as orders in the approximation. Thus, P13 is a sixth-order model
with no delays.
For comparison, approximate only the internal delay of sys, leaving the output delay
intact.
P3 = pade(sys,inf,inf,3);
size(P3)
P3.OutputDelay
ans = 1.5000
P3.InternalDelay
ans =
P3 retains the output delay, but the internal delay is approximated and absorbed into the
state-space matrices, resulting in a fifth-order model without internal delays.
Compare the frequency response of the exact and approximated systems sys, P13, P3.
h = bodeoptions;
h.PhaseMatching = 'on';
bode(sys,'b-',P13,'r-.',P3,'k--',h,{.01,10});
legend('sys','approximated output and internal delays','approximated internal delay onl
'location','SouthWest')
2-61
2 Model Creation
Notice that approximating the internal delay loses the gain ripple displayed in the exact
system.
See Also
pade
Related Examples
• “Time-Delay Approximation in Continuous-Time Open-Loop Model” on page 2-50
2-62
See Also
More About
• “Time-Delay Approximation” on page 2-48
• “Internal Delays” on page 2-73
2-63
2 Model Creation
Closing the feedback loop on a plant with input delays gives rise to internal delays in the
closed-loop system. Examine the order and internal delay of T.
order(T)
ans =
T.InternalDelay
ans =
2-64
Convert Time Delay in Discrete-Time Model to Factors of 1/z
Tnd = absorbDelay(T);
This command converts the internal delay to seven poles at z = 0. To confirm this,
examine the order and internal delay of Tnd.
order(Tnd)
ans =
Tnd.InternalDelay
ans =
Tnd has no internal delay, but it is a ninth-order model, due to the seven extra poles
introduced by absorbing the seven-unit delay into the model dynamics.
Despite this difference in representation, the responses of Tnd exactly match those of T.
stepplot(T,Tnd,'r--')
legend('T','Tnd')
2-65
2 Model Creation
bodeplot(T,Tnd,'r--')
legend('T','Tnd')
2-66
See Also
See Also
pade
Related Examples
• “Time-Delay Approximation in Continuous-Time Open-Loop Model” on page 2-50
More About
• “Time-Delay Approximation” on page 2-48
2-67
2 Model Creation
2-68
Frequency Response Data (FRD) Model with Time Delay
When you collect frequency response data for a system that includes time delays, you can
absorb the time delay into the frequency response as a phase shift. Alternatively, if you
are able to separate time delays from your measured frequency response, you can
represent the delays using the InputDelay, OutputDelay, or ioDelay properties of the
frd model object. The latter approach can give better numerical results, as this example
illustrates.
The frd model fsys includes a transport delay of 2 s. Load the model into the MATLAB®
workspace and inspect the time delay.
load(fullfile(matlabroot,'examples','control','frddelayexample.mat'),'fsys')
fsys.IODelay
ans =
A Bode plot of fsys shows the effect of the transport delay, causing the accumulation of
phase as frequency increases.
bodeplot(fsys)
2-69
2 Model Creation
The absorbDelay command absorbs all time delays directly into the frequency response,
resulting in an frd model with IODelay = 0.
fsys2 = absorbDelay(fsys);
fsys2.IODelay
ans =
Comparing the two ways of representing the delay shows that absorbing the delay into
the frequency response causes phase-wrapping.
2-70
See Also
bode(fsys,fsys2)
Phase wrapping can introduce numerical inaccuracy at high frequencies or where the
frequency grid is sparse. For that reason, if your system takes the form , you
might get better results by measuring frequency response data for G(s) and using
InputDelay, OutputDelay, or ioDelay to model the time delay .
See Also
absorbDelay
2-71
2 Model Creation
More About
• “Time-Delay Approximation” on page 2-48
2-72
Internal Delays
Internal Delays
Using the InputDelay, OutputDelay, and ioDelay properties, you can model simple
processes with transport delays. However, these properties cannot model more complex
situations, such as feedback loops with delays. In addition to the InputDelay and
OutputDelay properties, state-space (ss) models have an InternalDelay property.
This property lets you model the interconnection of systems with input, output, or
transport delays, including feedback loops with delays. You can use InternalDelay
property to accurately model and analyze arbitrary linear systems with delays. Internal
delays can arise from the following:
2-73
2 Model Creation
e-2s
s+2
e- 2 s
s + 2 + e- 2s
The delay term in the numerator can be represented as an output delay. However, the
delay term in the denominator cannot. In order to model the effect of the delay on the
feedback loop, the InternalDelay property is needed to keep track of internal coupling
between delays and ordinary dynamics.
Typically, you do not create state-space models with internal delays directly, by specifying
the A, B, C, and D matrices together with a set of internal delays. Rather, such models
arise when you interconnect models having delays. There is no limitation on how many
delays are involved and how the models are connected. For an example of creating an
internal delay by closing a feedback loop, see “Closing Feedback Loops with Time Delays”
on page 2-45.
• When a model interconnection gives rise to internal delays, the software returns an ss
model regardless of the interconnected model types. This occurs because only ss
supports internal delays.
• The software fully supports feedback loops. You can wrap a feedback loop around any
system with delays.
• When displaying the A, B, C, and D matrices, the software sets all delays to zero
(creating a zero-order Padé approximation). This approximation occurs for the display
only, and not for calculations using the model.
For some systems, setting delays to zero creates singular algebraic loops, which result
in either improper or ill-defined, zero-delay approximations. For these systems:
2-74
Internal Delays
• Entering sys returns only sizes for the matrices of a system named sys.
• Entering sys.A produces an error.
The limited display and the error do not imply a problem with the model sys itself.
2-75
2 Model Creation
You need not bother with this internal representation to use the tools. If, however, you
want to extract H or the matrices A, B1, B2, ... , you can use getDelayModel, For the
example:
P = 5*exp(-3.4*s)/(s+1);
C = 0.1 * (1 + 1/(5*s));
T = feedback(ss(P*C),1);
[H,tau] = getDelayModel(T,'lft');
size(H)
Note that H is a two-input, two-output model whereas T is SISO. The inverse operation
(combining H and tau to construct T) is performed by setDelayModel.
The following commands support internal delays for both continuous- and discrete-time
systems and have certain limitations:
2-76
See Also
To use these functions on a system with internal delays, use pade to approximate the
internal delays. See “Time-Delay Approximation” on page 2-48.
References
[1] P. Gahinet and L.F. Shampine, "Software for Modeling and Analysis of Linear Systems
with Delays," Proc. American Control Conf., Boston, 2004, pp. 5600-5605
See Also
Related Examples
• “Closing Feedback Loops with Time Delays” on page 2-45
2-77
2 Model Creation
You cannot use tunableTF to represent F, because the numerator and denominator
coefficients of a tunableTF block are independent. Instead, construct F using the
tunable real parameter object realp.
a = realp('a',10);
F = tf(a,[1 a]);
F is a genss object which has the tunable parameter a in its Blocks property. You can
connect F with other tunable or numeric models to create more complex control system
models. For example, see “Control System with Tunable Components” on page 2-83.
See Also
genss | realp | tunableTF
More About
• “Models with Tunable Coefficients” on page 1-19
• “Create Tunable Second-Order Filter” on page 2-79
• “Create State-Space Model with Both Fixed and Tunable Parameters” on page 2-81
• “Control System with Tunable Components” on page 2-83
2-78
Create Tunable Second-Order Filter
where the damping and the natural frequency are tunable parameters.
wn and zeta are realp parameter objects, with initial values 3 and 0.8, respectively.
The inputs to tf are the vectors of numerator and denominator coefficients expressed in
terms of wn and zeta.
F is a genss model. The property F.Blocks lists the two tunable parameters wn and
zeta.
F.Blocks
You can examine the number of tunable blocks in a generalized model using nblocks.
nblocks(F)
ans = 6
F has two tunable parameters, but the parameter wn appears five times - Twice in the
numerator and three times in the denominator.
2-79
2 Model Creation
nblocks(F)
ans = 4
In the new formulation, there are only three occurrences of the tunable parameter wn.
Reducing the number of occurrences of a block in a model can improve the performance
of calculations involving the model. However, the number of occurrences does not affect
the results of tuning the model or sampling it for parameter studies.
See Also
genss | nblocks | realp
More About
• “Models with Tunable Coefficients” on page 1-19
• “Create Tunable Low-Pass Filter” on page 2-78
• “Create State-Space Model with Both Fixed and Tunable Parameters” on page 2-81
• “Control System with Tunable Components” on page 2-83
2-80
Create State-Space Model with Both Fixed and Tunable Parameters
where a and b are tunable parameters, whose initial values are -1 and 3, respectively.
A is a generalized matrix whose Blocks property contains a and b. The initial value of A
is [1 2;0 -3], from the initial values of a and b.
sys =
Type "ss(sys)" to see the current value, "get(sys)" to see all properties, and "sys.Blo
sys is a generalized LTI model (genss) with tunable parameters a and b. Confirm that
the A property of sys is stored as a generalized matrix.
2-81
2 Model Creation
sys.A
ans =
Type "double(ans)" to see the current value, "get(ans)" to see all properties, and "ans
See Also
More About
• “Models with Tunable Coefficients” on page 1-19
• “Create Tunable Low-Pass Filter” on page 2-78
• “Create Tunable Second-Order Filter” on page 2-79
• “Control System with Tunable Components” on page 2-83
2-82
Control System with Tunable Components
Create models representing the plant and sensor dynamics. Since the plant and sensor
dynamics are fixed, represent them using numeric LTI models zpk and tf.
G = zpk([],[-1,-1],1);
S = tf(5,[1 4]);
a is a realp (real tunable parameter) object with initial value 10. Using a as a coefficient
in tf creates the tunable genss model object F.
Connect the models together to construct a model of the closed-loop response from to
.
2-83
2 Model Creation
T = feedback(G*C,S)*F
T =
Type "ss(T)" to see the current value, "get(T)" to see all properties, and "T.Blocks" t
T.Blocks
You can use tuning commands such as systune to tune the free parameters of T to meet
design requirements you specify.
See Also
Related Examples
• “Create Tunable Low-Pass Filter” on page 2-78
• “Create Tunable Second-Order Filter” on page 2-79
• “Create State-Space Model with Both Fixed and Tunable Parameters” on page 2-81
More About
• “Models with Tunable Coefficients” on page 1-19
2-84
Control System with Multichannel Analysis Points
The plant G has two inputs and two outputs. Therefore, the line marked y in the block
diagram represents two signals, y(1) and y(2). Similarly, r and e each represent two
signals.
Suppose you want to create tuning requirements or extract responses that require
injecting or measuring signals at the locations L and V. To do so, create an
AnalysisPoint block and include it in the closed-loop model of the control system as
shown in the following illustration.
To create a model of this system, first create the numeric LTI models and control design
blocks that represent the plant and controller elements. D is a tunable gain block, and
C_L and C_V are tunable PI controllers. Suppose the plant model is the following:
s = tf('s');
G = [87.8 -86.4 ; 108.2 -109.6]/(75*s+1);
2-85
2 Model Creation
D = tunableGain('Decoupler',eye(2));
C_L = tunablePID('C_L','pi');
C_V = tunablePID('C_V','pi');
AP_1 = AnalysisPoint('AP_1',2)
AP_1 =
Type "ss(AP_1)" to see the current value and "get(AP_1)" to see all properties.
AP_1.Location = {'L';'V'}
AP_1 =
Type "ss(AP_1)" to see the current value and "get(AP_1)" to see all properties.
The following diagram illustrates the input names, output names, and channel names
(locations) in the block AP_1.
The input and output names of the AnalysisPoint block are distinct from the channel
names. Use the channel names to refer to the analysis-point locations when extracting
responses or defining design goals for tuning. You can use the input and output names
AP_1.u and AP_1.y, for example, when interconnecting blocks using the connect
command.
2-86
Control System with Multichannel Analysis Points
You can now build the closed-loop model of the control system. First, join all the plant and
controller blocks along with the first AnalysisPoint block.
GC = G*AP_1*append(C_L,C_V)*D;
Then, close the feedback loop. Recall that GC has two inputs and outputs.
CL = feedback(GC,eye(2));
You can now use the analysis points for analysis or tuning. For example, extract the SISO
closed-loop transfer function from 'L' to the first output. Assign a name to the output so
you can reference it in analysis functions. The software automatically expands the
assigned name 'y' to the vector-valued output signals {y(1),y(2)}.
CL.OutputName = 'y';
TLy1 = getIOTransfer(CL,'L','y(1)');
bodeplot(TLy1);
2-87
2 Model Creation
See Also
AnalysisPoint
More About
• “Mark Signals of Interest for Control System Analysis and Design” on page 2-89
2-88
Mark Signals of Interest for Control System Analysis and Design
Analysis Points
Whether you model your control system in MATLAB or Simulink, use analysis points to
mark points of interest in the model. Analysis points allow you to access internal signals,
perform open-loop analysis, or specify requirements for controller tuning. In the block
diagram representation, an analysis point can be thought of as an access port to a signal
flowing from one block to another. In Simulink, analysis points are attached to the
outports of Simulink blocks. For example, in the following model, the reference signal, r,
and the control signal, u, are analysis points that originate from the outputs of the
setpoint and C blocks respectively.
Each analysis point can serve one or more of the following purposes:
• Input — The software injects an additive input signal at an analysis point, for
example, to model a disturbance at the plant input.
• Output — The software measures the signal value at a point, for example, to study the
impact of a disturbance on the plant output.
• Loop Opening — The software inserts a break in the signal flow at a point, for
example, to study the open-loop response at the plant input.
You can apply these purposes concurrently. For example, to compute the open-loop
response from u to y, you can treat u as both a loop opening and an input. When you use
an analysis point for more than one purpose, the software applies the purposes in this
sequence: output measurement, then loop opening, then input.
2-89
2 Model Creation
Using analysis points, you can extract open-loop and closed-loop responses from a control
system model. For example, suppose T represents the closed-loop system in the model
above, and u and y are marked as analysis points. T can be either a generalized state-
space model or an slLinearizer or slTuner interface to a Simulink model. You can
plot the closed-loop response to a step disturbance at the plant input with the following
commands:
Tuy = getIOTransfer(T,'u','y');
stepplot(Tuy)
Analysis points are also useful to specify design requirements when tuning control
systems with the systune command. For example, you can create a requirement that
attenuates disturbances at the plant input by a factor of 10 (20 dB) or more.
Req = TuningGoal.Rejection('u',10);
2-90
Mark Signals of Interest for Control System Analysis and Design
G = tf(10,[1 3 10]);
C = pid(0.2,1.5);
T = feedback(G*C,1);
With this model, you can obtain the closed-loop response from r to y. However, you
cannot analyze the open-loop response at the plant input or simulate the rejection of a
step disturbance at the plant input. To enable such analysis, mark the signal u as an
analysis point by inserting an AnalysisPoint block between the plant and controller.
AP = AnalysisPoint('u');
T = feedback(G*AP*C,1);
T.OutputName = 'y';
In creating the model T, you manually created the analysis point block AP and explicitly
included it in the feedback loop. When you combine models using the connect command,
you can instruct the software to insert analysis points automatically at the locations you
specify. For more information, see connect.
To mark an analysis point explicitly in the model, right-click a signal and, under Linear
Analysis Points, select an analysis point type.
2-91
2 Model Creation
You can select any of the following closed-loop analysis point types, which are equivalent
within an slLinearizer or slTuner interface; that is, they are treated the same way by
analysis functions, such as getIOTransfer, and tuning goals, such as
TuningGoal.StepTracking.
2-92
Mark Signals of Interest for Control System Analysis and Design
• Input Perturbation
• Output Measurement
• Sensitivity
• Complementary Sensitivity
If you want to introduce a permanent loop opening at a signal as well, select one of the
following open-loop analysis point types:
• Open-Loop Input
• Open-Loop Output
• Loop Transfer
• Loop Break
When you create an slLinearizer or slTuner interface for a model, any analysis
points defined in the model are automatically added to the interface. If you defined an
analysis point using:
To mark analysis points programmatically, use the addPoint command. For example,
consider the scdcascade model.
open_system('scdcascade')
2-93
2 Model Creation
ST = slTuner('scdcascade');
To add a signal as an analysis point, use the addPoint command, specifying the source
block and port number for the signal.
addPoint(ST,'scdcascade/C1',1);
If the source block has a single output port, you can omit the port number.
addPoint(ST,'scdcascade/G2');
For convenience, you can also mark analysis points using the:
addPoint(ST,'y2');
• Combined source block path and port number.
addPoint(ST,'scdcascade/C1/1')
• End of the full source block path when unambiguous.
addPoint(ST,'G1/1')
You can also add permanent openings to an slLinearizer or slTuner interface using
the addOpening command, and specifying signals in the same way as for addPoint. For
2-94
Mark Signals of Interest for Control System Analysis and Design
more information on how the software treats loop openings during linearization, see
“How the Software Treats Loop Openings” (Simulink Control Design).
addOpening(ST,'y1m');
You can also define analysis points by creating linearization I/O objects using the linio
command.
io(1) = linio('scdcascade/C1',1,'input');
io(2) = linio('scdcascade/G1',1,'output');
addPoint(ST,io);
As when you define analysis points directly in your model, if you specify a linearization I/O
object with:
When you specify response I/Os in a tool such as Linear Analysis Tool or Control System
Tuner, the software creates analysis points as needed.
You can also create tuning goals that constrain the system response at these points. The
tools to perform these operations operate in a similar manner for models created at the
command line and models created in Simulink.
To view the available analysis points, use the getPoints function. You can view the
analysis for models created:
2-95
2 Model Creation
For closed-loop models created at the command line, you can also use the model input
and output names when:
2-96
Mark Signals of Interest for Control System Analysis and Design
Use the same method to refer to analysis points for models created in Simulink. In
Simulink models, for convenience, you can use any unambiguous abbreviation of the
analysis point names returned by getPoints.
ioSys = getIOTransfer(ST,'u1','y1');
sensG2 = getSensitivity(ST,'G2');
R = TuningGoal.Margins('u1',10,60);
Finally, if some analysis points are vector-valued signals or multichannel locations, you
can use indices to select particular entries or channels. For example, suppose u is a two-
entry vector in a closed-loop MIMO model.
2-97
2 Model Creation
You can compute the open-loop response of the second channel and measure the impact
of a disturbance on the first channel.
L = getLoopTransfer(T,'u(2)',-1);
stepplot(getIOTransfer(T,'u(1)','y'))
When you create tuning goals in Control System Tuner, the software creates analysis
points as needed.
2-98
See Also
See Also
AnalysisPoint | getIOTransfer | getPoints
More About
• “Control System with Multichannel Analysis Points” on page 2-85
• “Mark Analysis Points in Closed-Loop Models” on page 4-13
2-99
2 Model Creation
Model Arrays
and so on. Model arrays are a convenient way to store and analyze such a collection.
Model arrays are collections of multiple linear models, stored as elements in a single
MATLAB array.
For all models collected in a single model array, the following attributes must be the
same:
Using model arrays, you can apply almost all of the basic model operations that work on
single model objects to entire sets of models at once. Functions operate on arrays model
by model, allowing you to manipulate an entire collection of models in a vectorized
fashion. You can also use analysis functions such as bode, nyquist, and step to model
2-100
Model Arrays
arrays to analyze multiple models simultaneously. You can access the individual models in
the collection through MATLAB array indexing.
Just as you might collect a set of two-by-two matrices in a multidimensional array, you can
collect this set of five transfer function models as a list in a model array under one
variable name, say, sys. Each element of the model array is a single model object.
2-101
2 Model Creation
The following illustration shows selection of models from the two-dimensional model
array m2d.
See Also
Related Examples
• “Query Array Size and Characteristics” on page 2-106
• “Select Models from Array” on page 2-103
• “Model Array with Variations in Two Parameters” on page 9-6
2-102
Select Models from Array
1 Load the transfer function array m2d into the MATLAB workspace.
step(m2d)
The step response shows that m2d contains six one-input, two-output models. The
step command plots all of the models in an array on a single plot.
3 (Optional) Examine the dimensions of m2d.
arraydim = size(m2d)
arraydim =
2 1 2 3
2-103
2 Model Creation
• The first entries of arraydim, 2 and 1, show that m2d is an array of two-output,
one-input transfer functions.
• The remaining entries in arraydim give the array dimensions of m2d, 2-by-3.
sys = m2d(:,:,2,1)
Tip You can also access models using single index referencing of the array
dimensions. For example,
sys = m2d(:,:,4)
m11 = m2d(1,1,:,:)
6 (Optional) Plot the step response of m11.
step(m11)
2-104
See Also
The step response shows that m11 is an array of six single-input, single-output (SISO)
models.
Note For frequency response data (FRD) models, the array indices can be followed
by the keyword 'frequency' and some expression selecting a subset of the
frequency points, as in:
sys(outputs,inputs,n1,...,nk,'frequency',SelectedFreqs)
See Also
More About
• “Model Arrays” on page 2-100
• “Query Array Size and Characteristics” on page 2-106
2-105
2 Model Creation
Array Size
Model arrays have two different sets of dimensions, the I/O dimensions and the array
dimensions. The I/O dimensions are the numbers of inputs and outputs of the models in
the array. (Each model in an array must have the same I/O dimensions.) The array
dimensions are the dimensions of the array itself. Load a saved model array and query its
dimensions.
load(fullfile(matlabroot,'examples','control','queryexample.mat'),'sysarr')
size(sysarr)
When you use the size command on a model array with no output argument, the display
shows the two sets of dimensions.
To obtain the array dimensions as a numeric array, use size with an output argument.
dims = size(sysarr)
dims = 1×4
3 1 2 4
The first two entries in dims are the I/O dimensions of the models in sysarr, which each
have three outputs and one input. The remaining entries in dims are the dimensions of
the array itself. Thus, sysarr is a 2-by-4 array of models.
To query the number of dimensions in the array, rather than the values of those
dimensions, use ndims.
dims = ndims(sysarr)
dims = 4
2-106
Query Array Size and Characteristics
In this case, sysarr has 4 = 2 + 2 dimensions: The I/O dimensions (outputs and inputs),
and the array dimensions. Query the I/O dimensions alone using the iosize command.
ios = iosize(sysarr)
ios = 1×2
3 1
N = nmodels(sysarr)
N = 8
Query commands such as isproper and isstable work on model arrays. For example,
query whether the models in sysarr are stable.
Bsiso = isstable(sysarr)
Bsiso = logical
1
By default, isstable returns 1 (true) if all of the models in the array are stable. The
commands returns 0 (false) if one or more of the models is not stable. To perform an
element-by-element query of a model array, use the 'elem' option.
Bsiso = isstable(sysarr,'elem')
1 1 1 1
1 1 1 1
Now isstable returns an array of Boolean values. The dimensions of this array match
the array dimensions of sysarr. Each entry in the array Bsiso indicates whether the
2-107
2 Model Creation
corresponding model of sysarr is stable. The 'elem' option works similarly for many
query commands.
See Also
More About
• “Model Arrays” on page 2-100
• “Select Models from Array” on page 2-103
2-108
Linear Parameter-Varying Models
dx ( t ) = A ( p) x ( t ) + B ( p) u ( t )
y ( t ) = C ( p) x ( t ) + D ( p) u ( t)
x ( 0 ) = x0
where
2-109
2 Model Creation
For example, the aerodynamic behavior of an aircraft is often scheduled over a grid of
incidence angle (α) and wind speed (V) values. For each scheduling parameter, a range of
values is chosen, such as α = 0:5:20 degrees, V = 700:100:1400 m/s. For each
combination of (α,V) values, a linear approximation of the aircraft behavior is obtained.
The local models are connected as shown in the following figure:
Each donut represents a local LTI model, and the connecting curves represent the
interpolation rules. The abscissa and ordinate of the surface are the scheduling
parameters (α, V).
This form is sometimes called the grid-based LPV representation. This is the form used by
the LPV System block. For meaningful interpolations of system matrices, all the local
models must use the same state basis.
2-110
Linear Parameter-Varying Models
The LPV system representation can be extended to allow offsets in dx, x, u and y
variables. This form is known as affine form of the LPV model. Mathematically, the
following represents an LPV system:
(
dx ( t ) = A ( p) x ( t ) + B ( p) u ( t ) + dx ( p) - A ( p) x ( p) - B( p)u( p) )
y ( t ) = C ( p) x ( t ) + D ( p) u ( t) + ( y ( p) - C ( p) x ( p) - D( p)u ( p) )
x ( 0 ) = x0
dx ( p) , x ( p) , u ( p) , y ( p) are the offsets in the values of dx(t), x(t), u(t) and y(t) at
a given parameter value p = p(t).
To obtain such representations of the linear system array, linearize a Simulink model over
a batch of operating points (see “Batch Linearization” (Simulink Control Design).) The
offsets correspond to the operating points at which you linearized the model.
You can obtain the offsets by returning additional linearization information when calling
functions such as linearize or getIOTransfer. You can then extract the offsets using
getOffsetsForLPV. For an example, see “LPV Approximation of a Boost Converter
Model” (Simulink Control Design).
In the affine representation, the linear model at a given point p = p* in the scheduling
space is:
( ) ( ) ( ) ( )
dDx(t, p* ) = A p* Dx t, p* + B p* Du t, p*
D y( t, p ) = C ( p* ) Dx ( t, p* ) + D ( p* ) D u ( t, p* )
*
The states of this linear model are related to the states of the overall LPV model
2-111
2 Model Creation
When parameters co-vary, that is, α and β increase together, an irregular grid is formed.
The system array parameters are available only along the diagonal in the parameter
plane.
2-112
Linear Parameter-Varying Models
If certain samples are missing from an otherwise regular grid, the grid is considered to be
irregular.
2-113
2 Model Creation
The system array size is equal to the grid size in scheduling space. In the aircraft
example, α takes 5 values in the 0–20 degrees range and V takes 8 values in the 700–1400
m/s range. If you define a linear model at every combination of (α,V) values (i.e., the grid
is regular), the grid size is 5-by-8. Therefore, the model array size must be 5-by-8.
The information about scheduling parameters is attached to the linear model array using
its SamplingGrid property. The value of the SamplingGrid property must be a
structure with as many fields as there are scheduling parameters. For each field, the
value must be set to all the values assumed by the corresponding variable in the
scheduling space.
For the aircraft example, you can define the SamplingGrid property as:
Alpha = 0:5:20;
V = 700:100:1400;
2-114
Linear Parameter-Varying Models
Note When obtaining linear models by linearization, do not reduce or alter the state
variables used by the models.
The operating region is usually of a high dimension because it consists of all the input and
state variables. Generating or interpolating local models in such high-dimensional spaces
is usually infeasible. A simpler approach is to use a small set of scheduling parameters as
a proxy for the operating space variables. The scheduling parameters are derived from
the inputs and state variables of the original system. You must choose the values carefully
so that for a fixed value of the scheduling parameters, the system behavior is
approximately linear. This approach is not always possible.
Suppose you use p( t) = x& 1 as a scheduling variable. At a given time instant t = t0, you
have:
x& 1 ª 2 x1 ( t0 ) x1 + 2 x2 ( t0 ) x2 - x&1 ( t0 )
x& 2 = -2 x1 - 3 x2 + 2u
y = x1 + 2
2-115
2 Model Creation
Thus, the dynamics are linear (affine) in the neighborhood of a given value of x& . The
approximation holds for all time spans and values of input u as long as of x& does not
deviate much from its nominal value at sampling point t0. Note that scheduling on input u
or states x1 or x2 does not help locally linearize the system. Therefore, they are not good
candidates for scheduling parameters.
For an example of this approach, see “Approximating Nonlinear Behavior Using an Array
of LTI Systems” (Simulink Control Design).
You can use LPV models to represent systems that exhibit multiple modes (regimes) of
operation. Examples of such systems include colliding bodies, systems controlled by
operator switches, and approximations of systems affected by dry friction and hysteresis
effects. For an example, see “Using LTI Arrays for Simulating Multi-Mode Dynamics” on
page 2-118.
This approach is useful for generating surrogate models that you can use in place of the
original system for enabling faster simulations, reducing memory footprint of target
hardware code, and hardware-in-loop (HIL) simulations. You can also use surrogate
models of this type for designing gain-scheduled controllers and for initializing the
parameter estimation tasks in Simulink. For an example of approximating a general
nonlinear system behavior by an LPV model, see “Approximating Nonlinear Behavior
Using an Array of LTI Systems” (Simulink Control Design).
LPV models can help speed up the simulation of physical component based systems, such
as those built using Simscape™ Multibody™ and Simscape Power Systems™ software.
For an example of this approach, see “LPV Approximation of a Boost Converter Model”
(Simulink Control Design).
See Also
LPV System | getOffsetsForLPV
2-116
See Also
More About
• “Using LTI Arrays for Simulating Multi-Mode Dynamics” on page 2-118
• “Approximating Nonlinear Behavior Using an Array of LTI Systems” (Simulink
Control Design)
• “LPV Approximation of a Boost Converter Model” (Simulink Control Design)
2-117
2 Model Creation
Introduction
We often encounter situations where an elastic body collides with, or presses against, a
possibly elastic surface. Examples of such situations are:
In these situations, the motion of the moving body exhibits different dynamics when it is
moving freely than when it is in contact with a surface. In the case of a bouncing ball, the
motion of the mass can be described by rigid body dynamics when it is falling freely.
When the ball collides and deforms while in contact with the surface, the dynamics have
to take into account the elastic properties of the ball and of the surface. A simple way of
modeling the impact dynamics is to use lumped mass spring-damper descriptions of the
colliding bodies. By adjusting the relative stiffness and damping coefficients of the two
bodies, we can model the various situations described above.
Figure 1 shows a mass-spring-damper model of the system. Mass 1 is falling freely under
the influence of gravity. Its elastic properties are described by stiffness constant and
damping coefficient . When this mass hits the fixed surface, the impact causes Mass 1
and Mass 2 to move downwards together. After a certain "residence time" during which
the Mass 1 deforms and recovers, it loses contact with Mass 2 completely to follow a
projectile motion. The overall dynamics are thus broken into two distinct modes - when
the masses are not in contact and when they are moving jointly.
2-118
Using LTI Arrays for Simulating Multi-Mode Dynamics
The unstretched (load-free) length of spring attached to Mass 1 is , while that of Mass 2
is . The variables and denote the positions of the two masses. When the
masses are not in contact ("Mode 1"), their motions are governed by the following
equations:
When Mass 1 touches Mass 2 ("Mode 2"), their displacements and velocities get
interlinked. The governing equations in this mode are:
LPV Representation
The governing equations are linear and time invariant. However, there are two distinct
behavioral modes corresponding to different equations of motion. Both modes are
governed by sets of second order equations. If we pick the positions and velocities of the
masses as state variables, we can represent each mode by a 4th order state-space
equation.
In the state-space view, it becomes possible to treat the two modes as a single system
whose coefficients change as a function of a certain condition which determines which
mode is active. The condition is, of course, whether the two masses are moving freely or
jointly. Such a representation, where the coefficients of a linear system are parameterized
by an external but measurable parameter is called a Linear Parameter Varying (LPV)
model. A common representation of an LPV model is by means of an array of linear state-
space models and a set of scheduling parameters that dictate the rules for choosing the
correct model under a given condition. The array of linear models must all be defined
using the same state variables.
2-119
2 Model Creation
For our example, we need two state-space models, one for each mode of operation. We
also need to define a scheduling variable to switch between them. We begin by writing the
above equations of motion in state-space form.
First mode: state-space representation of dynamics when the masses are not in contact.
A11 = [0 1; 0 0];
B11 = [0; -g];
C11 = [1 0];
D11 = 0;
A1 = blkdiag(A11, A12);
B1 = [B11; B12];
C1 = blkdiag(C11, C12);
D1 = [D11; D12];
sys1 = ss(A1,B1,C1,D1);
Second mode: state-space representation of dynamics when the masses are in contact.
A2 = [ 0 1, 0, 0; ...
-k1/m1, -c1/m1, k1/m1, c1/m1;...
2-120
Using LTI Arrays for Simulating Multi-Mode Dynamics
0, 0, 0, 1; ...
k1/m2, c1/m2, -(k1+k2)/m2, -(c1+c2)/m2];
sys2 = ss(A2,B2,C2,D2);
Now we stack the two models sys1 and sys2 together to create a state-space array.
sys = stack(1,sys1,sys2);
Use the information on whether the masses are moving freely or jointly for scheduling.
Let us call this parameter "FreeMove" which takes the value of 1 when masses are
moving freely and 0 when they are in contact and moving jointly. The scheduling
parameter information is incorporated into the state-space array object (sys) by using its
"SamplingGrid" property:
Whether the masses are in contact or not is decided by the relative positions of the two
masses; when , the masses are not in contact.
The state-space array sys has the necessary information to represent an LPV model. We
can simulate this model in Simulink using the "LPV System" block from the Control
System Toolbox™'s block library.
open_system('LPVBouncingMass')
open_system('LPVBouncingMass/Bouncing Mass Model','mask')
2-121
2 Model Creation
The block called "Bouncing Mass Model" is an LPV System block. Its parameters are
specified as follows:
• For "State-space array" field, specify the state-space model array sys that was created
above.
• For "Initial state" field, specify the initial positions and velocities of the two masses.
Note that the state vector is: . Specify its value as [h1 0 h2 0]'.
• Under the "Scheduling" tab, set the "Interpolation method" to "Nearest". This choice
causes only one of the two models in the array to be active at any time. In our
example, the behavior modes are mutually exclusive.
• Under the "Outputs" tab, uncheck all the checkboxes for optional output ports. We will
be observing only the positions of the two masses.
The constant block outputs a unit value. This serves as the input to the model and is
supplied from the first input port of the LPV block. The block has only one output port
which outputs the positions of the two masses as a 2-by-1 vector.
The second input port of the LPV block is for specifying the scheduling signal. As
discussed before, this signal represents the scheduling parameter "FreeMove" and takes
discrete values 0 (masses in contact) or 1 (masses not in contact). The value of this
parameter is computed as a function of the block's output signal. This computation is
performed by the blocks with cyan background color. We take the difference between the
two outputs (after demuxing) and compare the result to the unstretched length of spring
attached to Mass 1. The resulting Boolean result is converted into a double signal which
serves as the scheduling parameter value.
2-122
Using LTI Arrays for Simulating Multi-Mode Dynamics
open_system('LPVBouncingMass/Scope')
sim('LPVBouncingMass')
The yellow curve shows the position of Mass 1 while the magenta curve shows the
position of Mass 2. At the start of simulation, Mass 1 undergoes free fall until it hits Mass
2. The collision causes the Mass 2 to be displaced but it recoils quickly and bounces Mass
1 back. The two masses are in contact for the time duration where . When the
masses settle down, their equilibrium values are determined by the static settling due to
gravity. For example, the absolute location of Mass 1 is
2-123
2 Model Creation
Conclusions
This example shows how a Linear Parameter Varying model can be constructed by using
an array of state-space models and suitable scheduling variables. The example describes
the case of mutually exclusive modes, although a similar approach can be used in cases
where the dynamics behavior at a given value of scheduling parameters is influenced by
several linear models.
The LPV System block facilitates the simulation of parameter varying systems. The block
also supports code generation for various hardware targets.
2-124
Working with Linear Models
125
3
Data Manipulation
Model Properties
Model properties are the data fields that store all data about a dynamic system model.
Data stored in model properties includes model dynamics, such as transfer-function
coefficients, state-space matrices, and time delays. Model properties also let you specify
other model attributes such as sample time, channel names, and state names.
For information about the properties associated with each model type, see the
corresponding reference page, such as tf, pid, or ss.
You can specify other values for model properties at model creation using the
Name,Value pair syntax of the model-creation command. In this syntax, you specify the
name of the property you want to set, followed by the value. You can set multiple property
values in one command. For example, assign a transport delay and input and output
names to a new transfer function model.
H = tf(1,[1 10],'IODelay',6.5,'InputName','torque','OutputName','velocity')
H =
Some property values are reflected in the model display, such as the input and output
names. You can use Name,Value pair syntax when creating any type of model.
3-2
Store and Retrieve Model Data
sys =
A =
x1 x2
x1 -1.5 -0.1
x2 1 0
B =
u1
x1 1
x2 0
C =
x1 x2
y1 0.5 0.1
D =
u1
y1 0
The display shows that sys is a state-space model, and includes some of the property
values of sys. To see all properties of sys, use the get command.
get(sys)
A: [2x2 double]
B: [2x1 double]
C: [0.5000 0.1000]
D: 0
E: []
Scaled: 0
3-3
3 Data Manipulation
Use dot notation to access the values of particular properties. For example, display the A
matrix of sys.
Amat = sys.A
Amat = 2×2
-1.5000 -0.1000
1.0000 0
Dot notation also lets you change the value of individual model properties.
sys.InputDelay = 4.2;
sys.InputName = 'thrust';
sys.OutputName = 'velocity';
When you must change multiple property values at the same time to preserve the validity
of the model, such as changing the dimensions of the state-space matrices, you can use
the set command. For example, create a 1-state state-space model, and then replace the
matrices with new values representing a 2-state model.
sys2 = rss(1);
Anew = [-2, 1; 0.5 0];
Bnew = [1; -1];
Cnew = [0, -0.4];
3-4
See Also
set(sys2,'A',Anew,'B',Bnew,'C',Cnew)
sys2
sys2 =
A =
x1 x2
x1 -2 1
x2 0.5 0
B =
u1
x1 1
x2 -1
C =
x1 x2
y1 0 -0.4
D =
u1
y1 0.3426
See Also
Related Examples
• “Attach Metadata to Models” on page 3-9
• “Extract Model Coefficients” on page 3-6
3-5
3 Data Manipulation
Command Result
tfdata Extract transfer function coefficients
zpkdata Extract zero and pole locations and system gain
ssdata Extract state-space matrices
dssdata Extract descriptor state-space matrices
frdata Extract frequency response data from frd model
piddata Extract parallel-form PID data
pidstddata Extract standard-form PID data
get Access all model property values
s = tf('s');
H = exp(-2.5*s)/(s+12);
3-6
Extract Model Coefficients
The variables num and den are numerical arrays. Without the 'v' flag, tfdata
returns cell arrays.
Note For SISO transfer function models, you can also extract coefficients using:
num = H.Numerator{1};
den = H.Denominator{1};
In a SISO tf model, you can express a time delay as an input delay, an output
delay, or a transport delay (I/O delay).
get(H)
3-7
3 Data Manipulation
1 Create a transfer function that represents a PID controller with a first-order filter on
the derivative term.
Czpk = zpk([-6.6,-0.7],[0,-2],0.2)
2 Obtain the PID gains and filter constant.
[Kp,Ki,Kd,Tf] = piddata(Czpk)
This command returns the proportional gain Kp, integral gain Ki, derivative gain Kd,
and derivative filter time constant Tf. Because piddata automatically computes the
PID controller parameters, you can extract the PID coefficients without creating a
pid model.
See Also
Related Examples
• “Attach Metadata to Models” on page 3-9
More About
• “Store and Retrieve Model Data” on page 3-2
3-8
Attach Metadata to Models
The TimeUnit property of the tf model object specifies units of the time variable, time
delays (for continuous-time models), and the sample time Ts (for discrete-time models).
The default time units is seconds.
4s + 2
Create a SISO transfer function model sys = with time units in milliseconds:
2
s + 3 s + 10
num = [4 2];
den = [1 3 10];
sys = tf(num,den,'TimeUnit','milliseconds');
You can specify the time units of any dynamic system on page 1-10 in a similar way.
The system time units appear on the time- and frequency-domain plots. For multiple
systems with different time units, the units of the first system are used if the time and
frequency units in the “Toolbox Preferences Editor” on page 19-2 are auto.
Note Changing the TimeUnit property changes the system behavior. If you want to use
different time units without modifying system behavior, use chgTimeUnit.
1 Create two transfer function models with time units of milliseconds and seconds,
respectively.
3-9
3 Data Manipulation
The FrequencyUnit property specifies units of the frequency vector in the Frequency
property of the frd model object. The default frequency units are rad/TimeUnit, where
TimeUnit is the time unit specified in the TimeUnit property.
You can independently specify the units in which you measure the frequency points and
sample time in the FrequencyUnit and TimeUnit properties, respectively. You can also
specify the frequency units of a genfrd in a similar way.
The frequency units appear on the frequency-domain plots. For multiple systems with
different frequency units, the units of the first system are used if the frequency units in
the “Toolbox Preferences Editor” on page 19-2 is auto.
Note Changing the FrequencyUnit property changes the system behavior. If you want
to use different frequency units without modifying system behavior, use chgFreqUnit.
Extracting subsystems is useful when, for example, you want to analyze a portion of a
complex system.
3-10
Attach Metadata to Models
G1 = tf(3,[1 10]);
G2 = tf([1 2],[1 0]);
G = [G1,G2];
Gsub = G(:,1);
This command uses MATLAB indexing to specify a subsystem as G(out,in), where out
specifies the output indices and in specifies the input indices.
Using channel names, you can use MATLAB indexing to extract all the dynamics relating
to a particular channel. By using this approach, you can avoid having to keep track of
channel order in a complex MIMO model.
G.InputName = {'temperature';'pressure'};
Because G has two inputs, use a cell array to specify the two channel names.
Extract the subsystem of G that contains all dynamics from the 'temperature' input to
all outputs.
Gt = G(:,'temperature');
Note When you extract a subsystem from a state-space (ss) model, the resulting state-
space model may not be minimal. Use sminreal to eliminate unnecessary states in the
subsystem.
Input and output groups are useful for keeping track of inputs and outputs in complex
MIMO models.
3-11
3 Data Manipulation
H = rss(3,4,3);
2 Group the inputs as follows:
H.InputGroup.controls = [1 2];
H.OutputGroup.temperature = [1 3];
H.OutputGroup.measurements = [1 3 4];
InputGroup and OutputGroup are structures. The name of each field in the
structure is the name of the input or output group. The value of each field is a vector
that identifies the channels in that group.
3 Extract the subsystem corresponding to the controls inputs and the temperature
outputs.
Hc = H('temperature','controls')
You can see the relationship between H and the subsystem Hc in this illustration.
Hc
1 1
controls 2 temperature
2 H
3
3 4
3-12
See Also
See Also
Related Examples
• “Store and Retrieve Model Data” on page 3-2
• “Extract Model Coefficients” on page 3-6
• “Query Model Characteristics” on page 3-14
3-13
3 Data Manipulation
Bstab = logical
1
The isstable command returns 1 (true) if all system poles are in the open left-half
plane (for continuous-time models) or inside the open unit disk (for discrete-time models).
Otherwise, isstable command returns 0 (false). Here, the result shows that the model
is stable.
Bdel = logical
1
The returned value, 1, indicates that T has a time delay. For a state-space model, time
delay can be stored as input delay, output delay, internal delay, or a combination. Use
get(T) to determine which properties of T hold the time delay, and use dot notation to
access the delay values. The hasInternalDelay command tells you whether there is
any internal delay.
Bprop = logical
1
3-14
See Also
The returned value indicates that the system has relative degree less than or equal to 0.
This is true of a SISO system when it can be represented as a transfer function in which
the degree of the numerator does not exceed the degree of the denominator.
N = order(T)
N = 5
For a state-space model, order returns the number of states, which is 5 in this case. For
a tf or zpk model, the order is the number of states required for a state-space realization
of the system.
Bdisc = isdt(T)
Bdisc = logical
1
The returned value indicates that T is a discrete-time model. Similarly, use isct to query
whether T is a continuous-time model.
load(fullfile(matlabroot,'examples','control','queryexample.mat'),'Tmimo')
ios = iosize(Tmimo)
ios = 1×2
7 4
In the resulting array, the number of outputs is first. Therefore, Tmimo has 4 inputs and 7
outputs.
See Also
isproper | isstable | size
3-15
3 Data Manipulation
Related Examples
• “Select Models from Array” on page 2-103
More About
• “Store and Retrieve Model Data” on page 3-2
3-16
Customize Model Display
You can use the same steps to configure the display variable of transfer function models
in factorized form (zpk models).
By default, tf and zpk models are displayed in terms of s in continuous time and z in
discrete time. Use the Variable property change the display variable to 'p' (equivalent
to 's'), 'q' (equivalent to 'z'), 'z^-1', or 'q^-1'.
1
z -1
Create the discrete-time transfer function H ( z) =
2
z - 3z + 2
with a sample time of 1 s.
H =
z - 1
-------------
z^2 - 3 z + 2
H.Variable = 'q^-1'
H =
q^-1 - q^-2
-------------------
1 - 3 q^-1 + 2 q^-2
3-17
3 Data Manipulation
When you change the Variable property, the software computes new coefficients
and displays the transfer function in terms of the new variable. The num and den
properties are automatically updated with the new coefficients.
Tip Alternatively, you can directly create the same transfer function expressed in terms
of 'q^-1'.
For the inverse variables 'z^-1' and 'q^-1', tf interprets the numerator and
denominator arrays as coefficients of ascending powers of 'z^-1' or 'q^-1'.
You can configure the display of the factorized numerator and denominator polynomials to
highlight:
See the DisplayFormat property on the zpk reference page for more information about
these quantities.
1 Create a zpk model having a zero at s = 5, a pole at s = –10, and a pair of complex
poles at s = –3 ± 5i.
H = zpk(5,[-10,-3-5*i,-3+5*i],10)
H =
10 (s-5)
----------------------
3-18
Customize Model Display
The default display format, 'roots', displays the standard factorization of the
numerator and denominator polynomials.
2 Configure the display format to display the natural frequency of each polynomial root.
H.DisplayFormat = 'frequency'
H =
-0.14706 (1-s/5)
-------------------------------------------
(1+s/10) (1 + 1.029(s/5.831) + (s/5.831)^2)
You can read the natural frequencies and damping ratios for each pole and zero from
the display as follows:
H =
-0.14706 (1-0.2s)
-------------------------------------------
(1+0.1s) (1 + 1.029(0.1715s) + (0.1715s)^2)
You can read the time constants and damping ratios from the display as follows:
• Factors corresponding to real roots are displayed as (τs). The variable τ is the
time constant of the root. For example, the time constant of the zero of H is 0.2.
3-19
3 Data Manipulation
See Also
tf | zpk
Related Examples
• “Transfer Functions” on page 2-3
3-20
4
Model Interconnections
For example, you can interconnect dynamic system models of a plant G(s), a controller
C(s), sensor dynamics S(s), and a filter F(s) to construct a single model that represents
the entire closed-loop control system in the following illustration:
+
r F(s) C(s) G(s) y
-
S(s)
See Also
More About
• “Catalog of Model Interconnections” on page 4-3
4-2
Catalog of Model Interconnections
H2
N/A H1/H2 (division)
u H2-1 H1 y
4-3
4 Model Interconnections
z2 H2 w2
Arithmetic Operations
You can apply almost all arithmetic operations to dynamic system models, including those
shown below.
Operation Description
+ Addition
- Subtraction
* Multiplication
.* Element-by-element multiplication
/ Right matrix divide
\ Left matrix divide
inv Matrix inversion
' Conjugate system. For a system G, the transfer function of G' is:
4-4
See Also
Operation Description
^ Powers of a dynamic system model, as in the following syntax for
creating transfer functions:
s = tf('s');
G = 25/(s^2 + 10*s + 25);
In some cases, you might obtain better results using model interconnection commands,
such as feedback or connect, instead of model arithmetic. For example, the command T
= feedback(H1,H2) returns better results than the algebraic expression T = H1/
(1+H2*H1). The latter expression duplicates the poles of H1, which inflates the model
order and might lead to computational inaccuracy.
See Also
connect | feedback | parallel | series
Related Examples
• “Numeric Model of SISO Feedback Loop” on page 4-6
• “Multi-Loop Control System” on page 4-10
• “MIMO Control System” on page 4-19
More About
• “How the Software Determines Properties of Connected Models” on page 4-27
• “Recommended Model Type for Building Block Diagrams” on page 4-31
4-5
4 Model Interconnections
+
r F(s) C(s) G(s) y
-
S(s)
The feedback loop includes a plant G(s), a controller C(s), and a representation of sensor
dynamics, S(s). The system also includes a prefilter F(s).
1 Create model objects representing each of the components.
G = zpk([],[-1,-1],1);
C = pid(2,1.3,0.3,0.5);
S = tf(5,[1 4]);
F = tf(1,[1 1]);
The plant G is a zero-pole-gain (zpk) model with a double pole at s = –1. Model object
C is a PID controller. The models F and S are transfer functions.
2 Connect the controller and plant models.
H = G*C;
To combine models using the multiplication operator *, enter the models in reverse
order compared to the block diagram.
3
H
Construct the unfiltered closed-loop response T ( s ) = .
1 + HS
4-6
See Also
T = feedback(H,S);
T = H/(1+H*S)
This computation duplicates the poles of H, which inflates the model order and might
lead to computational inaccuracy.
4 Construct the entire closed-loop system response from r to y.
T_ry = T*F;
T_ry is a Numeric LTI Model representing the aggregate closed-loop system. T_ry does
not keep track of the coefficients of the components G, C, F, and S.
You can operate on T_ry with any Control System Toolbox control design or analysis
commands.
See Also
connect | feedback | parallel | series
Related Examples
• “Control System Model With Both Numeric and Tunable Components” on page 4-8
• “Multi-Loop Control System” on page 4-10
• “MIMO Control System” on page 4-19
More About
• “Catalog of Model Interconnections” on page 4-3
4-7
4 Model Interconnections
Suppose that the plant response is , and that the model of the sensor
dynamics is . The controller is a tunable PID controller, and the
prefilter is a low-pass filter with one tunable parameter, a.
Create models representing the plant and sensor dynamics. Because the plant and sensor
dynamics are fixed, represent them using numeric LTI models.
G = zpk([],[-1,-1],1);
S = tf(5,[1 4]);
To model the tunable components, use Control Design Blocks. Create a tunable
representation of the controller C.
C = tunablePID('C','PID');
a is a realp (real tunable parameter) object with initial value 10. Using a as a coefficient
in tf creates the tunable genss model object F.
4-8
See Also
Interconnect the models to construct a model of the complete closed-loop response from r
to y.
T = feedback(G*C,S)*F
T =
Type "ss(T)" to see the current value, "get(T)" to see all properties, and "T.Blocks" t
T.Blocks
When you create a genss model of a control system that has tunable components, you
can use tuning commands such as systune to tune the free parameters to meet design
requirements you specify.
See Also
feedback | tunablePID
More About
• “Control Design Blocks” on page 1-16
• “Dynamic System Models” on page 1-10
4-9
4 Model Interconnections
u
P y
sum1
+ e yp y1 +
ysp C Gp Dp sum3
- -
ym
+
sum2
+
dp dy
F
For more information about the Smith Predictor, see “Control of Processes with Long
Dead Time: The Smith Predictor”.
The connect command lets you construct the overall transfer function from ysp to y. To
use connect, specify the input and output channel names of the components of the block
diagram. connect automatically joins ports that have the same name, as shown in the
following figure.
error
B1 B1
connect(B1,B2)
error
B2 error B2
To build the closed loop model of the Smith Predictor system from ysp to y:
1 Create the components of the block diagram: the process model P, the predictor
model Gp, the delay model Dp, the filter F, and the PI controller C. Specify names for
the input and output channels of each model so that connect can automatically join
them to build the block diagram.
4-10
See Also
s = tf('s');
P = exp(-93.9*s) * 5.6/(40.2*s+1);
P.InputName = 'u'; P.OutputName = 'y';
Gp = 5.6/(40.2*s+1);
Gp.InputName = 'u'; Gp.OutputName = 'yp';
Dp = exp(-93.9*s);
Dp.InputName = 'yp'; Dp.OutputName = 'y1';
F = 1/(20*s+1);
F.InputName = 'dy'; F.OutputName = 'dp';
C = pidstd(0.574,40.1);
C.Inputname = 'e'; C.OutputName = 'u';
2 Create the summing junctions needed to complete the block diagram.
The argument to sumblk is a formula that relates the input and output signals of the
summing junction. sumblk creates a summing junction with the input and output
signal names specified in the formula. For example, in sum1, the formula 'e = ysp
- ym' specifies an output signal named e, which is the difference between input
signals named ysp and ym.
3 Assemble the complete model from ysp to y.
T = connect(P,Gp,Dp,C,F,sum1,sum2,sum3,'ysp','y');
You can list the models and summing junctions in any order because connect
automatically interconnects them using their input and output channel names.
The last two arguments specify the input and output signals of the multi-loop control
structure. Thus, T is a ss model with input ysp and output y.
See Also
connect | sumblk
4-11
4 Model Interconnections
Related Examples
• “Control System Model With Both Numeric and Tunable Components” on page 4-8
• “MIMO Control System” on page 4-19
• “Mark Analysis Points in Closed-Loop Models” on page 4-13
More About
• “How the Software Determines Properties of Connected Models” on page 4-27
4-12
Mark Analysis Points in Closed-Loop Models
For this example, create a model of a Smith predictor, the SISO multiloop control system
shown in the following block diagram.
Points marked by x are analysis points to mark for this example. For instance, if you want
to calculate the step response of the closed-loop system to a disturbance at the plant
input, you can use an analysis point at u. If you want to calculate the response of the
system with one or both of the control loops open, you can use the analysis points at yp or
dp.
To build this system, first create the dynamic components of the block diagram. Specify
names for the input and output channels of each model so that connect can
automatically join them to build the block diagram.
s = tf('s');
% Process model
P = exp(-93.9*s) * 5.6/(40.2*s+1);
P.InputName = 'u';
P.OutputName = 'y';
% Predictor model
Gp = 5.6/(40.2*s+1);
4-13
4 Model Interconnections
Gp.InputName = 'u';
Gp.OutputName = 'yp';
% Delay model
Dp = exp(-93.9*s);
Dp.InputName = 'yp';
Dp.OutputName = 'y1';
% Filter
F = 1/(20*s+1);
F.InputName = 'dy';
F.OutputName = 'dp';
% PI controller
C = pidstd(0.574,40.1);
C.Inputname = 'e';
C.OutputName = 'u';
Create the summing junctions needed to complete the block diagram. (For more
information about creating summing junctions, see sumblk).
sum1 = sumblk('e = ysp - ym');
sum2 = sumblk('ym = yp + dp');
sum3 = sumblk('dy = y - y1');
T =
Type "ss(T)" to see the current value, "get(T)" to see all properties, and "T.Blocks" t
When you use the APs input argument, the connect command automatically inserts an
AnalysisPoint block into the generalized state-space (genss) model, T. The
automatically generated block is named AnalysisPoints_. The three channels of
AnalysisPoints_ correspond to the three locations specified in the APs argument to
4-14
Mark Analysis Points in Closed-Loop Models
the connect command. Use getPoints to see a list of the available analysis points in
the model.
getPoints(T)
ans =
{'dp'}
{'u' }
{'yp'}
Use these locations as inputs, outputs, or loop openings when you extract responses from
the model. For example, extract and plot the response at the system output to a step
disturbance at the plant input, u.
Tp = getIOTransfer(T,'u','y');
stepplot(Tp)
4-15
4 Model Interconnections
Similarly, calculate the open-loop response of the plant and controller by opening both
feedback loops.
openings = {'dp','yp'};
L = getIOTransfer(T,'ysp','y',openings);
bodeplot(L)
4-16
See Also
When you create a control system model, you can create an AnalysisPoint block
explicitly and assign input and output names to it. You can then include it in the input
arguments to connect as one of the blocks to combine. However, using the APs
argument to connect as illustrated in this example is a simpler way to mark points of
interest when building control system models.
See Also
AnalysisPoint | connect | sumblk
4-17
4 Model Interconnections
Related Examples
• “Control System with Multichannel Analysis Points” on page 2-85
More About
• “Mark Signals of Interest for Control System Analysis and Design” on page 2-89
4-18
MIMO Control System
pL L
+ e CL
r D G y
pV CV
-
V
The plant G is a distillation column with two inputs and two outputs. The two inputs are
the reflux L and boilup V. The two outputs are the concentrations of two chemicals,
represented by the vector signal y = [y1,y2]. You can represent this plant model as:
1 È 87 .8 -86 .4 ˘
G ( s) = Í ˙.
75s + 1 Î108.2 -109 .6 ˚
The vector setpoint signal r = [r1,r2] specifies the desired concentrations of the two
chemicals. The vector error signal e represents the input to D, a static 2-by-2 decoupling
matrix. CL and CV represent independent PI controllers that control the two inputs of G.
When you construct the closed-loop model, connect uses the input and output
names to form connections between the block diagram components. Therefore, you
must assign names to the inputs and outputs of the transfer function G in either of the
following ways: .
4-19
4 Model Interconnections
• You can assign input and output names to individual signals by specifying signal
names in a cell array, as in G.InputName = {'L','V'}
• Alternatively, you can use vector signal naming, which the software automatically
expands. For example, the command G.OutputName = 'y' assigns the names
'y(1)' and 'y(2)' to the outputs of G.
2 Create tunable Control Design Blocks representing the decoupling matrix D and the
PI controllers CL and CV.
D = tunableGain('Decoupler',eye(2));
D.u = 'e';
D.y = {'pL','pV'};
Note u and y are shorthand notations for the InputName and OutputName
properties, respectively. Thus, for example, entering:
D.u = 'e';
D.y = {'pL','pV'};
is equivalent to entering:
D.InputName = 'e';
D.OutputName = {'pL','pV'};
The summing junction produces the error signals e by taking the difference between
r and y.
Sum represents the transfer function for the summing junction described by the
formula 'e = r - y'. The second argument to sumblk specifies that the inputs and
outputs of Sum are each vector signals of length 2. The software therefore
automatically assigns the signal names {'r(1)','r(2)','y(1)','y(2)'} to
Sum.InputName and {'e(1)','e(2)'} to Sum.OutputName.
4-20
See Also
CLry = connect(G,D,C_L,C_V,Sum,'r','y');
The arguments to the connect function include all the components of the closed-loop
system, in any order. connect automatically combines the components using the
input and output names to join signals.
The last two arguments to connect specify the output and input signals of the
closed-loop model, respectively. The resulting genss model CLry has two-inputs and
two outputs.
See Also
connect | sumblk
Related Examples
• “Control System Model With Both Numeric and Tunable Components” on page 4-8
• “Multi-Loop Control System” on page 4-10
• “MIMO Control System” on page 4-19
More About
• “Catalog of Model Interconnections” on page 4-3
4-21
4 Model Interconnections
In this example, you obtain the response from Azref to Az of the MIMO feedback loop of
the following block diagram.
You can compute the closed-loop response using one of the following three approaches:
You can use whichever of these approaches is most convenient for your application.
Load the plant Aerodyn and the controller Autopilot into the MATLAB® workspace.
These models are stored in the datafile MIMOfeedback.mat.
load(fullfile(matlabroot,'examples','control','MIMOfeedback.mat'))
4-22
MIMO Feedback Loop
T1 = connect(Autopilot,Aerodyn,'Azref','Az');
The connect function combines the models by joining the inputs and outputs that have
matching names. The last two arguments to connect specify the input and output signals
of the resulting model. Therefore, T1 is a state-space model with input Azref and output
Az. The connect function ignores the other inputs and outputs in Autopilot and
Aerodyn.
When you use the feedback function, think of the closed-loop system as a feedback
interconnection between an open-loop plant-controller combination L and a diagonal
unity-gain feedback element K. The following block diagram shows this interconnection.
L = series(Autopilot,Aerodyn,'Fin');
FeedbackChannels = {'Alpha','Mach','Az','q'};
K = ss(eye(4),'InputName',FeedbackChannels,...
'OutputName',FeedbackChannels);
4-23
4 Model Interconnections
T2 = feedback(L,K,'name',+1);
Compute the closed-loop response from Azref to Az using feedback, using indices to
specify the interconnections between Aerodyn and Autopilot.
L = series(Autopilot,Aerodyn,1,4);
K = ss(eye(4));
T3 = feedback(L,K,[1 2 3 4],[4 3 6 5],+1);
Compare the step response from Azref to Az to confirm that the three approaches yield
the same results.
step(T1,T2('Az','Azref'),T3(6,5),2)
4-24
See Also
See Also
connect | feedback
Related Examples
• “Multi-Loop Control System” on page 4-10
• “MIMO Control System” on page 4-19
4-25
4 Model Interconnections
More About
• “How the Software Determines Properties of Connected Models” on page 4-27
4-26
How the Software Determines Properties of Connected Models
4-27
4 Model Interconnections
See Also
More About
• “Rules That Determine Model Type” on page 4-29
4-28
Rules That Determine Model Type
P = ss([-0.8,0.4;0.4,-1.0],[-3.0;1.4],[0.3,0],0);
C = pid(-0.13,-0.61);
CL = feedback(P*C,1)
The ss model has the highest precedence among Numeric LTI models. Therefore,
combining P and C with any model interconnection command returns an ss model.
Combining Numeric LTI models with Generalized LTI models on page 1-16 or with Control
Design Blocks on page 1-16 results in Generalized LTI models.
F = tunableTF('F',0,1);
CLF = F*CL
Note The software automatically converts all models to the resulting model type before
performing the connection operation.
See Also
connect | feedback | parallel | series
Related Examples
• “Numeric Model of SISO Feedback Loop” on page 4-6
4-29
4 Model Interconnections
More About
• “How the Software Determines Properties of Connected Models” on page 4-27
• “Recommended Model Type for Building Block Diagrams” on page 4-31
4-30
Recommended Model Type for Building Block Diagrams
You can represent block diagram components with any model type. However, certain
connection operations yield better numerical accuracy for models in ss form.
For example, interconnect two models in series using different model types to see how
different representations introduce numerical inaccuracies.
Load the models Pd and Cd. These models are ninth-order and second-order discrete-time
transfer functions, respectively.
load numdemo Pd Cd
Compute the open-loop transfer function L = Pd*Cd using the tf, zpk, ss, and frd
representations.
Ltf = Pd*Cd;
Lzp = zpk(Pd)*Cd;
Lss = ss(Pd)*Cd;
w = logspace(-1,3,100);
Lfrd = frd(Pd,w)*Cd;
Plot the magnitude of the frequency response to compare the four representations.
bodemag(Ltf,Lzp,Lss,Lfrd)
legend('tf','zpk','ss','frd')
4-31
4 Model Interconnections
See Also
More About
• “Rules That Determine Model Type” on page 4-29
4-32
5
Model Transformation
In general, you can convert from any model type to any other. However, there are a few
limitations. For example, you cannot convert:
• frd models to analytic model types such as ss, tf, or zpk (unless you perform system
identification with System Identification Toolbox software).
• ss models with internal delays to tf or zpk.
You can convert between Numeric LTI models and Generalized LTI models.
• Converting a Generalized LTI model to a Numeric LTI model evaluates any Control
Design Blocks at their current (nominal) value.
• Converting a Numeric LTI model to a Generalized LTI model creates a Generalized LTI
model with an empty Blocks property.
sys = ss(0,1,1,0)
[num,den] = tfdata(sys)
tfdata automatically converts the state-space model sys to transfer function form to
return numerator and denominator data.
Conversions to state-space form are not uniquely defined. For this reason, automatic
conversions to state space do not occur when the result depends on the choice of state
5-2
See Also
coordinates. For example, the initial and kalman commands require state-space
models.
• The accuracy of computations using high-order transfer functions (tf or zpk models)
is sometimes poor, particularly for MIMO or high-order systems. Conversions to a
transfer function representation can incur a loss of accuracy.
• When you convert tf or zpk models to state space using ss, the software
automatically performs balancing and scaling operations. Balancing and scaling
improves the numeric accuracy of computations involving the model. For more
information about balancing and scaling state-space models, see “Scaling State-Space
Models” on page 23-2.
In addition, converting back and forth between model types can introduce additional
states or orders, or introduce numeric inaccuracies. For example, conversions to state
space are not uniquely defined, and are not guaranteed to produce a minimal realization
for MIMO models. For a given state-space model sys,
ss(tf(sys))
can return a model with different state-space matrices, or even a different number of
states in the MIMO case.
See Also
frd | pid | ss | tf | zpk
Related Examples
• “Convert From One Model Type to Another” on page 5-4
5-3
5 Model Transformation
In general, you can convert a model from one type to another type using the model-
creation command for the target type. For example, you can use the tf command to
convert an ss model to transfer function form, or use the ss command to convert a zpk
model to state-space form.
pid_sys = pid(1,1.5,3)
pid_sys =
1
Kp + Ki * --- + Kd * s
s
with Kp = 1, Ki = 1.5, Kd = 3
C = tf(pid_sys)
C =
3 s^2 + s + 1.5
---------------
s
C is a tf representation of pid_sys. C has the same dynamics as pid_sys, but stores the
dynamic parameters as transfer-function numerator and denominator coefficients instead
of proportional, integral, and derivative gains.
You can similarly convert transfer function models to pid models, provided the tf model
object represents a parallel-form PID controller with .
5-4
See Also
In general, you can use the technique of this example to convert any type of model to
another type of model. For more specific information about converting to a particular
model type, see the reference page for that model type.
See Also
frd | pid | ss | tf | zpk
More About
• “Conversion Between Model Types” on page 5-2
5-5
5 Model Transformation
a = realp('a',10);
F = tf(a,[1 a]);
Typically, once of you have a generalized model, you tune the parameters of the model
using a tuning command such as systune. For this example, instead of tuning the model,
manually change the value of the tunable component of F.
F.Blocks.a.Value = 5;
Get the current value of the generalized model by converting it to a numeric model.
F_cur_val = tf(F)
F_cur_val =
5
-----
s + 5
5-6
See Also
See Also
realp | showBlockValue | tf
More About
• “Models with Tunable Coefficients” on page 1-19
• “Conversion Between Model Types” on page 5-2
• “Convert From One Model Type to Another” on page 5-4
5-7
5 Model Transformation
Obtain a 2-DOF PID controller. For this example, create a plant model, and tune a 2-DOF
PID controller for it.
C2 is a pid2 controller object. The control architecture for C2 is as shown in the following
illustration.
This control system can be equivalently represented in several other architectures that
use only SISO components. In the feedforward configuration, the 2-DOF controller is
represented as a SISO PID controller and a feedforward compensator.
[Cff,Xff] = getComponents(C2,'feedforward')
5-8
Decompose a 2-DOF PID Controller into SISO Components
Cff =
1 s
Kp + Ki * --- + Kd * --------
s Tf*s+1
Xff =
-10.898 (s+0.2838)
------------------
(s+8.181)
This command returns the SISO PID controller Cff as a pid object. The feedforward
compensator X is returned as a zpk object.
Tff = G*(Cff+Xff)*feedback(1,G*Cff);
Decompose C2 using the feedback configuration and construct that closed-loop system.
5-9
5 Model Transformation
In the filter configuration, the 2-DOF controller is represented as a SISO PID controller
and prefilter on the reference signal.
Decompose C2 using the filter configuration. Construct that closed-loop system as well.
Construct the closed-loop system for the original 2-DOF controller, C2. To do so, convert
C2 to a two-input, one-output transfer function, and use array indexing to access the
channels.
Ctf = tf(C2);
Cr = Ctf(1);
Cy = Ctf(2);
T = Cr*feedback(G,Cy,+1);
stepplot(T,Tff,Tfb,Tfr)
legend('2-DOF','feedforward','feedback','filter','Location','Southeast')
5-10
See Also
The plots coincide, demonstrating that all the systems are equivalent.
Using a 2-DOF PID controller can yield improved performance compared to a 1-DOF
controller. For more information, see “Tune 2-DOF PID Controller (Command Line)” on
page 11-15.
See Also
getComponents | pid2 | pidstd2
5-11
5 Model Transformation
Related Examples
• “Two-Degree-of-Freedom PID Controllers” on page 2-16
5-12
Discretize a Compensator
Discretize a Compensator
This example shows how to convert a compensator from continuous to discrete time using
several discretization methods, to identify a method that yields a good match in the
frequency domain.
You might design a compensator in continuous time, and then need to convert it to
discrete time for a digital implementation. When you do so, you want the discretization to
preserve frequency-domain characteristics that are essential to your performance and
stability requirements.
One valid controller for this system includes a notch filter in series with an integrator.
Create a model of this controller.
notch = tf([1,0.5,9],[1,5,9]);
integ = pid(0,0.34);
C = integ*notch;
bodeplot(C)
5-13
5 Model Transformation
The notch filter centered at 3 rad/s counteracts the effect of the resonance in G. This
configuration allows higher loop gain for a faster overall response.
Cdz = c2d(C,0.5);
The c2d command supports several different discretization methods. Since this command
does not specify a method, c2d uses the default method, Zero-Order Hold (ZOH). In the
ZOH method, the time-domain response of the discretized compensator matches the
continuous-time response at each time step.
5-14
Discretize a Compensator
The discretized controller Cdz has a sample time of 0.5 s. In practice, the sample time you
choose might be constrained by the system in which you implement your controller, or by
the bandwidth of your control system.
bodeplot(C,Cdz)
legend('C','Cdz');
The vertical line marks the Nyquist frequency, , where is the sample time. Near
the Nyquist frequency, the response of the discretized compensator is distorted relative to
the continuous-time response. As a result, the discretized notched filter may not properly
counteract the plant resonance.
5-15
5 Model Transformation
To fix this, try discretizing the compensator using the Tustin method and compare to the
ZOH result. The Tustin discretization method often yields a better match in the frequency
domain than the ZOH method.
Cdt = c2d(C,0.5,'tustin');
plotopts = bodeoptions;
plotopts.Ylim = {[-60,40],[-225,0]};
bodeplot(C,Cdz,Cdt,plotopts)
legend('C','Cdz','Cdt')
The Tustin method preserves the depth of the notch. However, the method introduces a
frequency shift that is unacceptable for many applications. You can remedy the frequency
shift by specifying the notch frequency as the prewarping frequency in the Tustin
transform.
5-16
Discretize a Compensator
Discretize the compensator using the Tustin method with frequency prewarping, and
compare the results.
discopts = c2dOptions('Method','tustin','PrewarpFrequency',3.0);
Cdtp = c2d(C,0.5,discopts);
bodeplot(C,Cdt,Cdtp,plotopts)
legend('C','Cdt','Cdtp')
5-17
5 Model Transformation
Using the Tustin method with frequency prewarping yields a better-matching frequency
response than Tustin without prewarping.
See Also
c2d | c2dOptions
More About
• “Continuous-Discrete Conversion Methods” on page 5-26
• “Improve Accuracy of Discretized System with Time Delay” on page 5-19
5-18
Improve Accuracy of Discretized System with Time Delay
For systems with time delays that are not integer multiples of the sample time, the
Tustin and Matched methods by default round the time delays to the nearest multiple of
the sample time. To improve the accuracy of these methods for such systems, c2d can
optionally approximate the fractional portion of the time delay by a discrete-time all-pass
filter (a Thiran filter). In this example, discretize the system both without and with an
approximation of the fractional portion of the delay and compare the results.
G = tf(1,[1,0.2,4],'ioDelay',2.5);
discopts = c2dOptions('Method','tustin','PrewarpFrequency',2);
Gt = c2d(G,1,discopts)
Warning: Rounding delays to the nearest multiple of the sampling period. For more accur
Gt =
The software warns you that it rounds the fractional time delay to the nearest multiple of
the sample time. In this example, the time delay of 2.5 times the sample time (2.5 s)
converts to an additional factor of z^(-3) in Gt.
5-19
5 Model Transformation
plotopts = bodeoptions;
plotopts.Ylim = {[-100,20],[-1080,0]};
bodeplot(G,Gt,plotopts);
legend('G','Gt')
There is a phase lag between the discretized system Gt and the continuous-time system G,
which grows as the frequency approaches the Nyquist frequency. This phase lag is largely
due to the rounding of the fractional time delay. In this example, the fractional time delay
is half the sample time.
5-20
Improve Accuracy of Discretized System with Time Delay
discopts.FractDelayApproxOrder = 3;
Gtf = c2d(G,1,discopts);
The FractDelayApproxOrder option specifies the order of the Thiran filter that
approximates the fractional portion of the delay. The other options in discopts are
unchanged. Thus Gtf is a Tustin discretization of G with prewarp at 2 rad/s.
plotopts.PhaseMatching = 'on';
bodeplot(G,Gt,Gtf,plotopts);
legend('G','Gt','Gtf','Location','SouthWest')
5-21
5 Model Transformation
The magnitudes of Gt and Gtf are identical. However, the phase of Gtf provides a better
match to the phase of the continuous-time system through the resonance. As the
frequency approaches the Nyquist frequency, this phase match deteriorates. A higher-
order approximation of the fractional delay would improve the phase matching closer to
the Nyquist frequencies. However, each additional order of approximation adds an
additional order (or state) to the discretized system.
If your application requires accurate frequency-matching near the Nyquist frequency, use
c2dOptions to make c2d approximate the fractional portion of the time delay as a
Thiran filter.
See Also
c2d | c2dOptions | thiran
More About
• “Continuous-Discrete Conversion Methods” on page 5-26
• “Discretize a Compensator” on page 5-13
5-22
Convert Discrete-Time System to Continuous Time
Convert the following second-order discrete-time system to continuous time using the
zero-order hold (ZOH) method:
G = zpk(-0.5,[-2,5],1,0.1);
Gcz = d2c(G)
Warning: The model order was increased to handle real negative poles.
Gcz =
When you call d2c without specifying a method, the function uses ZOH by default. The
ZOH interpolation method increases the model order for systems that have real negative
poles. This order increase occurs because the interpolation algorithm maps real negative
poles in the domain to pairs of complex conjugate poles in the domain.
Gct = d2c(G,'tustin')
Gct =
5-23
5 Model Transformation
bode(G,Gcz,Gct)
legend('G','Gcz','Gct')
In this case, the Tustin method provides a better frequency-domain match between the
discrete system and the interpolation. However, the Tustin interpolation method is
5-24
See Also
undefined for systems with poles at z = -1 (integrators), and is ill-conditioned for systems
with poles near z = 1.
See Also
d2c | d2cOptions
More About
• “Continuous-Discrete Conversion Methods” on page 5-26
• “Discretize a Compensator” on page 5-13
5-25
5 Model Transformation
5-26
Continuous-Discrete Conversion Methods
Zero-Order Hold
The Zero-Order Hold (ZOH) method provides an exact match between the continuous-
and discrete-time systems in the time domain for staircase inputs.
The ZOH block generates the continuous-time input signal u(t) by holding each sample
value u(k) constant over one sample period:
u ( t ) = u [ k] , kTs £ t £ ( k + 1 ) Ts
The signal u(t) is the input to the continuous system H(s). The output y[k] results from
sampling y(t) every Ts seconds.
Conversely, given a discrete system Hd(z), d2c produces a continuous system H(s). The
ZOH discretization of H(s) coincides with Hd(z).
5-27
5 Model Transformation
You can use the ZOH method to discretize SISO or MIMO continuous-time models with
time delays. The ZOH method yields an exact discretization for systems with input delays,
output delays, or transfer delays.
For systems with internal delays (delays in feedback loops), the ZOH method results in
approximate discretizations. The following figure illustrates a system with an internal
delay.
H(s)
e-ts
For such systems, c2d performs the following actions to compute an approximate ZOH
discretization:
1
Decomposes the delay τ as t = kTs + r with 0 £ r < Ts .
2
Absorbs the fractional delay r into H(s).
3 Discretizes H(s) to H(z).
4 Represents the integer portion of the delay kTs as an internal discrete-time delay z–k.
The final discretized model appears in the following figure:
H(z)
H(s) e-sr
z-k
First-Order Hold
The First-Order Hold (FOH) method provides an exact match between the continuous-
and discrete-time systems in the time domain for piecewise linear inputs.
5-28
Continuous-Discrete Conversion Methods
FOH differs from ZOH by the underlying hold mechanism. To turn the input samples u[k]
into a continuous input u(t), FOH uses linear interpolation between samples:
t - kTs
u ( t ) = u [ k] +
Ts
(u [k + 1] - u [k]) , kTs £ t £ (k + 1) Ts
In general, this method is more accurate than ZOH for systems driven by smooth inputs.
This FOH method differs from standard causal FOH and is more appropriately called
triangle approximation (see [2], p. 228). The method is also known as ramp-invariant
approximation.
You can use the FOH method to discretize SISO or MIMO continuous-time models with
time delays. The FOH method handles time delays in the same way as the ZOH method.
See “ZOH Method for Systems with Time Delays” on page 5-28.
Impulse-Invariant Mapping
The impulse-invariant mapping produces a discrete-time model with the same impulse
response as the continuous time system. For example, compare the impulse response of a
first-order continuous system with the impulse-invariant discretization:
G = tf(1,[1,1]);
Gd1 = c2d(G,0.01,'impulse');
impulse(G,Gd1)
5-29
5 Model Transformation
The impulse response plot shows that the impulse responses of the continuous and
discretized systems match.
Tustin Approximation
The Tustin or bilinear approximation yields the best frequency-domain match between the
continuous-time and discretized systems. This method relates the s-domain and z-domain
transfer functions using the approximation:
5-30
Continuous-Discrete Conversion Methods
sTs 1 + sTs / 2
z=e ª .
1 - sTs / 2
In c2d conversions, the discretization Hd(z) of a continuous transfer function H(s) is:
2 z-1
H d ( z ) = H ( s¢ ) , s¢ =
Ts z + 1
1 + sTs / 2
H ( s ) = Hd ( z¢ ) , z¢ =
1 - sTs / 2
When you convert a state-space model using the Tustin method, the states are not
preserved. The state transformation depends upon the state-space matrices and whether
the system has time delays. For example, for an explicit (E = I) continuous-time model
with no time delays, the state vector w[k] of the discretized model is related to the
continuous-time state vector x(t) by:
Ê T ˆ T T
w [ kTs ] = Á I - A s ˜ x ( kTs ) - s Bu ( kTs ) = x ( kTs ) - s ( Ax ( kTs ) + Bu ( kTs ) ) .
Ë 2 ¯ 2 2
Ts is the sample time of the discrete-time model. A and B are state-space matrices of the
continuous-time model.
If your system has important dynamics at a particular frequency that you want the
transformation to preserve, you can use the Tustin method with frequency prewarping.
This method ensures a match between the continuous- and discrete-time responses at the
prewarp frequency.
The Tustin approximation with frequency prewarping uses the following transformation of
variables:
w z-1
H d ( z ) = H ( s¢ ) , s¢ =
tan (w Ts / 2 ) z + 1
5-31
5 Model Transformation
This change of variable ensures the matching of the continuous- and discrete-time
frequency responses at the prewarp frequency ω, because of the following
correspondence:
(
H ( jw ) = H d e jw Ts )
Tustin Approximation for Systems with Time Delays
You can use the Tustin approximation to discretize SISO or MIMO continuous-time models
with time delays.
By default, the Tustin method rounds any time delay to the nearest multiple of the sample
time. Therefore, for any time delay tau, the integer portion of the delay, k*Ts, maps to a
delay of k sampling periods in the discretized model. This approach ignores the residual
fractional delay, tau - k*Ts.
You can to approximate the fractional portion of the delay by a discrete all-pass filter
(Thiran filter) of specified order. To do so, use the FractDelayApproxOrder option of
c2dOptions. See “Improve Accuracy of Discretized System with Time Delay” on page 5-
19 for an example.
To understand how the Tustin method handles systems with time delays, consider the
following SISO state-space model G(s). The model has input delay τi, output delay τo, and
internal delay τ.
G(s)
e-tis e-tos
H(s)
e-ts
The following figure shows the general result of discretizing G(s) using the Tustin
method.
5-32
Continuous-Discrete Conversion Methods
Gd(z)
z-m F(z)
By default, c2d converts the time delays to pure integer time delays. The c2d command
computes the integer delays by rounding each time delay to the nearest multiple of the
sample time Ts. Thus, in the default case, mi = round(τi/Ts), mo = round(τo/Ts), and m =
round(τ/Ts).. Also in this case, Fi(z) = Fo(z) = F(z) = 1.
The Thiran filters add additional states to the model. The maximum number of additional
states for each delay is FractDelayApproxOrder.
For example, for the input delay τi, the order of the Thiran filter Fi(z) is:
If ceil(τi/Ts) < FractDelayApproxOrder, the Thiran filter Fi(z) approximates the entire
input delay τi. If ceil(τi/Ts) > FractDelayApproxOrder, the Thiran filter only
approximates a portion of the input delay. In that case, c2d represents the remainder of
the input delay as a chain of unit delays z–mi, where
mi = ceil(τi/Ts) – FractDelayApproxOrder
When you discretizetf and zpk models using the Tustin method, c2d first aggregates all
input, output, and transfer delays into a single transfer delay τTOT for each channel. c2d
then approximates τTOT as a Thiran filter and a chain of unit delays in the same way as
described for each of the time delays in ss models.
5-33
5 Model Transformation
For more information about Thiran filters, see the thiran reference page and [4].
zi = esi Ts
where:
You can use zero-pole matching to discretize SISO continuous-time models with time
delay, except that the method does not support ss models with internal delays. The zero-
pole matching method handles time delays in the same way as the Tustin approximation.
See “Tustin Approximation for Systems with Time Delays” on page 5-32.
Least Squares
The least squares method minimizes the error between the frequency responses of the
continuous-time and discrete-time systems up to the Nyquist frequency using a vector-
fitting optimization approach. This method is useful when you want to capture fast system
dynamics but must use a larger sample time, for example, when computational resources
are limited.
This method is supported only by the c2d function and only for SISO systems.
As with Tustin approximation and zero-pole matching, the least squares method provides
a good match between the frequency responses of the original continuous-time system
and the converted discrete-time system. However, when using the least squares method
with:
5-34
See Also
• The same sample time as Tustin approximation or zero-pole matching, you get a
smaller difference between the continuous-time and discrete-time frequency
responses.
• A lower sample time than what you would use with Tustin approximation or zero-pole
matching, you can still get a result that meets your requirements. Doing so is useful if
computational resources are limited, since the slower sample time means that the
processor must do less work.
References
[1] Åström, K.J. and B. Wittenmark, Computer-Controlled Systems: Theory and Design,
Prentice-Hall, 1990, pp. 48-52.
[2] Franklin, G.F., Powell, D.J., and Workman, M.L., Digital Control of Dynamic Systems
(3rd Edition), Prentice Hall, 1997.
[3] Smith, J.O. III, "Impulse Invariant Method", Physical Audio Signal Processing, August
2007. http://www.dsprelated.com/dspbooks/pasp/
Impulse_Invariant_Method.html.
[4] T. Laakso, V. Valimaki, "Splitting the Unit Delay", IEEE Signal Processing Magazine,
Vol. 13, No. 1, p.30-60, 1996.
See Also
c2d | c2dOptions | d2c | d2cOptions | d2d | d2dOptions | thiran
Related Examples
• “Discretize a Compensator” on page 5-13
• “Improve Accuracy of Discretized System with Time Delay” on page 5-19
• “Convert Discrete-Time System to Continuous Time” on page 5-23
5-35
5 Model Transformation
Upsampling a system can be useful, for example, when you need to implement a digital
controller at a faster rate than you originally designed it for.
G = tf([1,0.4],[1,-0.7],0.3);
G_d2d = d2d(G,0.1)
G_d2d =
z - 0.4769
----------
z - 0.8879
By default, d2d uses the zero-order-hold (ZOH) method to resample the system. The
resampled system has the same order as G.
G_up = upsample(G,3)
G_up =
z^3 + 0.4
---------
z^3 - 0.7
5-36
Upsample Discrete-Time System
The second input, 3, tells upsample to resample G at a sample time three times faster
than the sample time of G. This input to upsample must be an integer.
Compare the step responses of the original model G with the resampled models G_d2d
and G_up.
step(G,'-r',G_d2d,':g',G_up,'--b')
legend('G','d2d','upsample','Location','SouthEast')
5-37
5 Model Transformation
The step response of the upsampled model G_up matches exactly the step response of the
original model G. The response of the resampled model G_d2d matches only at every third
sample.
Compare the frequency response of the original model with the resampled models.
bode(G,'-r',G_d2d,':g',G_up,'--b')
legend('G','d2d','upsample','Location','SouthWest')
In the frequency domain as well, the model G_up created with the upsample command
matches the original model exactly up to the Nyquist frequency of the original model.
Using upsample provides a better match than d2d in both the time and frequency
domains. However, upsample increases the model order, which can be undesirable.
5-38
See Also
Additionally, upsample is only available where the original sample time is an integer
multiple of the new sample time.
See Also
d2d | d2dOptions | upsample
More About
• “Choosing a Resampling Command” on page 5-40
5-39
5 Model Transformation
See Also
d2d | d2dOptions | upsample
Related Examples
• “Upsample Discrete-Time System” on page 5-36
5-40
6
Model Simplification
• You are working with a relatively high-order model obtained from linearizing a
Simulink model, performing a finite-element calculation, interconnecting model
elements, or other source.
• You want to improve the simulation speed of a Simulink model at a certain operating
point. In that case, you can linearize a portion of the model at that operating point and
compute a reduced-order simplification or approximation of the linearized model. You
can then replace the portion of the model with an LTI Block containing the reduced-
order model.
• You design a high-order controller that you want to implement as a lower-order
controller, such as a PID controller. For example, controller design using Linear-
Quadratic-Gaussian methods or H∞ synthesis techniques can yield a high-order result.
In this case, you can try reducing the plant order before synthesis, reducing the
controller order after synthesis, or both.
• You want to simplify a model obtained by identification with System Identification
Toolbox software.
The following diagram illustrates the relationship between model reduction and control
design.
6-2
Model Reduction Basics
Plant reduction
G GR
Controller design
Controller design
Controller reduction
C CR
Higher Lower
Order Order
• Discarding states that do not contribute to the system dynamics, such as structurally
disconnected states or canceling pole-zero pairs.
• Discarding low-energy states that contribute relatively little to system dynamics.
• Focusing on a particular frequency region and discarding dynamics outside that
region. For example, if your control bandwidth is limited by actuator dynamics,
discard higher-frequency dynamics.
In any case, when you reduce model order, you want to preserve model characteristics
that are important for your application. Whenever you compute a reduced-order model,
verify that the reduced model preserves time-domain or frequency-domain behavior that
you care about. For example, for control design, it is useful to verify that the reduced
closed-loop system is stable. It is also useful to check that the reduced open-loop transfer
function CRGR adequately matches the original models where the open-loop gain GC is
close to 1 (in the gain crossover region).
6-3
6 Model Simplification
Sometimes, approximation can yield better results, even if the model looks like a good
candidate for simplification. For example, models with near pole-zero cancellations are
sometimes better reduced by approximation than simplification. Similarly, using balred
to reduce state-space models can yield more accurate results than minreal.
When you use a reduced-order model, always verify that the simplification or
approximation preserves model characteristics that are important for your application.
For example, compare the frequency responses of the original and reduced models using
6-4
See Also
bodeplot or sigmaplot. Or, compare the open-loop responses for the original and
reduced plant and controller models.
See Also
Apps
Model Reducer
Functions
balred | freqsep | minreal | sminreal
Related Examples
• “Balanced Truncation Model Reduction” on page 6-17
• “Mode-Selection Model Reduction” on page 6-57
• “Pole-Zero Simplification” on page 6-47
6-5
6 Model Simplification
This example uses a model of the Los Angeles University Hospital building. The building
has eight floors, each with three degrees of freedom: two displacements and one rotation.
The input-output relationship for any one of these displacements is represented as a 48-
state model, where each state represents a displacement or its rate of change (velocity).
Load the building model and open Model Reducer with that model.
load build.mat
modelReducer(G)
Select the model in the Data Browser to display some information about the model in the
Preview section. Double-click the model to see more detailed information.
6-6
Reduce Model Order Using the Model Reducer App
Model Reducer has three model reduction methods: Balanced Truncation, Mode
Selection, and Pole/Zero Simplification. For this example, click Balanced Truncation.
6-7
6 Model Simplification
Model Reducer opens the Balanced Truncation tab and automatically generates a
reduced-order model. The top plot compares the original and reduced model in the
frequency domain. The bottom plot shows the energy contribution of each state, where
the states are sorted from high energy to low energy. The order of the reduced model, 14,
is highlighted in the bar chart. In the reduced model, all states with lower energy
contribution than this one are discarded.
Suppose that you want to preserve the first, second, and third peaks of the model
response, around 5.2 rad/s, 13 rad/s, and 25 rad/s. Try other model orders to see whether
6-8
Reduce Model Order Using the Model Reducer App
you can achieve this goal with a lower model order. Compute a 5th-order and a 10th-order
approximation in one of the following ways:
Model Reducer computes two new reduced-order models and displays them on the
response plot with the original model G. To examine the three peaks more closely, Zoom in
on the relevant frequency range. The 10th-order model captures the three peaks
successfully, while the 5th-order model only approximates the first two peaks. (For
information about zooming and other interactions with the analysis plots, see “Visualize
Reduced-Order Models in the Model Reducer App” on page 6-67.)
6-9
6 Model Simplification
In addition to the frequency response plot of all three models, Model Reducer lets you
examine the absolute and relative error between the original and reduced models. Select
Absolute error plot to see the difference between the building and reduced models.
6-10
Reduce Model Order Using the Model Reducer App
The 5th-order reduced model has at most -60dB error in the frequency region of the first
two peaks, below about 30 rad/s. The error increases at higher frequencies. The 10th-
order reduced model has smaller error over all frequencies.
Store the reduced models in the Data Browser by clicking Create Reduced Model. The
5th-order and 10th-order reduced models appear in the Data Browser with names
GReduced5 and Greduced10.
You can continue to change the model-reduction parameters and generate additional
reduced models. As you do so, GReduced5 and Greduced10 remain unchanged in the
Data Browser.
6-11
6 Model Simplification
You can also focus the balanced truncation on the model dynamics in a particular
frequency interval. For example, approximate only the second peak of the building model
around 13 rad/s. First, select the Model response plot to see the Bode plots of models.
Then check Select frequency range checkbox. Model Reducer analyzes state
contributions in the highlighted frequency interval only.
You can drag the boundaries to change the frequency range interactively. As you change
the frequency interval, the Hankel Singular Value plot reflects the changes in the energy
contributions of the states.
Enter the frequency limits [10 22] into the text box next to Select frequency range.
The 5th-order reduced model captures the essential dynamics. The 10th-order model has
almost the same dynamics as the original building model within this frequency range.
6-12
Reduce Model Order Using the Model Reducer App
Optionally, store these additional models in the Data Browser by clicking Create
Reduced Model.
You can compare time-domain responses of the stored reduced models and the original in
the Plots tab. In the Data Browser, control-click to select the models you want to
compare, G, GReduced5, and GReduced10. Then, click Step. Model Reducer creates a
step plot with all three models.
6-13
6 Model Simplification
Zooming on the transient behavior of this plot shows that GReduced10 captures the time
domain behavior of the original model well. However, the response of GReduced5
deviates from the original model after about 3 seconds.
Comparison of the reduced and original models in the time and frequency domains shows
that GReduced10 adequately captures the dynamics of interest. Export that model to the
MATLAB® workspace for further analysis and design. In the Model Reducer tab, click
Export Model. Clear the check boxes for G and Greduced5, and click Export to export
Greduced10.
6-14
See Also
See Also
Model Reducer
Related Examples
• “Model Reduction Basics” on page 6-2
• “Balanced Truncation Model Reduction” on page 6-17
• “Pole-Zero Simplification” on page 6-47
6-15
6 Model Simplification
6-16
Balanced Truncation Model Reduction
For more general information about model reduction, see “Model Reduction Basics” on
page 6-2.
1 Open the app, and import an LTI model to reduce. For instance, suppose that there is
a model named build in the MATLAB workspace. The following command opens
Model Reducer and imports the model.
modelReducer(build)
2
In the Data Browser, select the model to reduce. Click Balanced Truncation.
6-17
6 Model Simplification
In the Balanced Truncation tab, Model Reducer displays a plot of the frequency
response of the original model and a reduced version of the model. The frequency
response is a Bode plot for SISO models, and a singular-value plot for MIMO models.
The app also displays a Hankel singular-value plot of the original model.
6-18
Balanced Truncation Model Reduction
The Hankel singular-value plot shows the relative energy contributions of each state
in the system. Model Reducer computes an initial reduced-order model based on
these values. The highlighted bar is the lowest-energy state in the initial reduced-
order model. Model Reducer discards states that have lower Hankel singular values
than the highlighted bar.
6-19
6 Model Simplification
3 Try different reduced-model orders to find the lowest-order model that preserves the
dynamics that are important for your application. To specify different orders, either:
• Enter model orders in the Reduced model orders field. You can enter a single
integer or an array of integers, such as 10:14 or [8,11,12].
• Click a bar on the Hankel singular-value plot to specify the lowest-energy state of
the reduced-order model. Ctrl-click to specify multiple values.
When you change the specified reduced model order, Model Reducer automatically
computes a new reduced-order model. If you specify multiple model orders, Model
Reducer computes multiple reduced-order models and displays their responses on
the plot.
6-20
Balanced Truncation Model Reduction
4 Optionally, examine the absolute or relative error between the original and reduced-
order model, in addition to the frequency response. Select the error-plot type using
the buttons on the Balanced Truncation tab.
6-21
6 Model Simplification
For more information about using the analysis plots, see “Visualize Reduced-Order
Models in the Model Reducer App” on page 6-67.
5 If low-frequency dynamics are not important to your application, you can clear the
Preserve DC Gain checkbox. Doing so sometimes yields a better match at higher
frequencies between the original and reduced-order models.
6-22
Balanced Truncation Model Reduction
When you check or clear the Preserve DC Gain checkbox, Model Reducer
automatically computes new reduced-order models. For more information about this
option, see “Compare Truncated and DC Matched Low-Order Model Approximations”
on page 6-30.
6 Optionally, limit the Hankel singular-value computation to a specific frequency range.
Such a limit is useful when the model has modes outside the region of interest to your
particular application. When you apply a frequency limit, Model Reducer
determines which states to truncate based on their energy contribution within the
specified frequency range only. Neglecting energy contributions outside that range
can yield an even lower-order approximation that is still adequate for your
application.
6-23
6 Model Simplification
• In the text box, entering a vector of the form [fmin,fmax]. Units are rad/
TimeUnit, where TimeUnit is the TimeUnit property of the model you are
reducing.
• On the response plot or error plot, dragging the boundaries of the shaded region
or the shaded region itself. Model Reducer analyzes the state contributions
within the shaded region only.
When you check or clear the Select frequency range checkbox or change the
selected range, Model Reducer automatically computes new reduced-order models.
further, click . The new models appear in the Data Browser. If you have specified
multiple orders, each reduced model appears separately. Model names reflect the
reduced model order.
6-24
Balanced Truncation Model Reduction
After creating reduced models in the Data Browser, you can continue changing the
reduction parameters and create reduced models with different orders for analysis
and comparison.
You can now perform further analysis with the reduced model. For example:
• Examine other responses of the reduced system, such as the step response or Nichols
plot. To do so, use the tools on the Plots tab. See “Visualize Reduced-Order Models in
the Model Reducer App” on page 6-67 for more information.
• Export reduced models to the MATLAB workspace for further analysis or control
To create a MATLAB script you can use for further model-reduction tasks at the command
line, click Create Reduced Model, and select Generate MATLAB Script.
6-25
6 Model Simplification
Model Reducer creates a script that uses the balred command to perform model
reduction with the parameters and options you have set on the Balanced Truncation
tab. The script opens in the MATLAB editor.
To do so, first examine the contribution of the various states to the overall model
behavior. Choose the approximation order based on the number of states that make a
significant contribution to the overall model behavior.
For this example, load a high-order model. hplant is a 23rd-order SISO model.
6-26
Balanced Truncation Model Reduction
ans = 23
Examine the relative amount of energy per state in hplant using a Hankel singular-value
(HSV) plot.
hsvplot(hplant)
Small Hankel singular values indicate that the associated states contribute little to the
behavior of the system. The plot shows that two states account for most of the energy in
the system. Therefore, try simplifying the model to just first or second order.
6-27
6 Model Simplification
opts = balredOptions('StateElimMethod','Truncate');
hplant1 = balred(hplant,1,opts);
hplant2 = balred(hplant,2,opts);
The second argument to balred specifies the target approximation order, so that
hplant1 is a first-order approximation and hplant2 is a second-order approximation of
hplant. By default, balred discards the states with the smallest Hankel singular values,
and alters the remaining states to preserve the DC gain of the system. Setting the
StateElimMethod option to Truncate causes balred to discard low-energy states
without altering the remaining states.
When working with reduced-order models, it is important to verify that the approximation
does not introduce inaccuracies at frequencies that are important for your application.
Therefore, compare the frequency responses of the original and approximated systems.
For MIMO systems, use the sigmaplot command. For this SISO system, examine a Bode
plot.
bodeplot(hplant,hplant2,hplant1)
legend('Original','2nd order','1st order')
6-28
Balanced Truncation Model Reduction
The second-order approximation hplant2 matches the original 23rd-order system very
well, especially at lower frequencies. The first-order system does not match as well.
In general, as you decrease the order of the approximated model, the frequency response
of the approximated model begins to differ from the original model. Choose an
approximation that is sufficiently accurate in the bands that are important to you. For
example, in a control system you might want good accuracy inside the control bandwidth.
Accuracy at frequencies far above the control bandwidth, where the gain rapidly rolls off,
might be less important.
You can also validate the approximation in the time domain. For instance, examine the
step responses of the original and reduced-order systems.
6-29
6 Model Simplification
stepplot(hplant,hplant2,'r--',hplant1,'g--')
legend('Original','2nd order','1st order','Location','SouthEast')
This result confirms that the second-order approximation is a good match to the original
23rd-order system.
6-30
Balanced Truncation Model Reduction
• Discard the states that make the smallest contribution to system behavior, altering the
remaining states to preserve the DC gain of the system.
• Discard the low-energy states without altering the remaining states.
Which method you choose depends on what dynamics are most important to your
application. In general, preserving DC gain comes at the expense of accuracy in higher-
frequency dynamics. Conversely, state truncation can yield more accuracy in fast
transients, at the expense of low-frequency accuracy.
6-31
6 Model Simplification
T =
2 s (s+2)
--------------------------------
(s+0.004277) (s+1.588) (s+4.418)
Compute two second-order approximations to T, one that preserves the DC gain and one
that truncates the lowest-energy state without changing the other states. Use
balredOptions to specify the approximation methods, MatchDC and Truncate,
respectively.
matchopt = balredOptions('StateElimMethod','MatchDC');
truncopt = balredOptions('StateElimMethod','Truncate');
Tmatch = balred(T,2,matchopt);
Ttrunc = balred(T,2,truncopt);
bodeplot(T,Tmatch,Ttrunc)
legend('Original','DC Match','Truncate')
6-32
Balanced Truncation Model Reduction
The truncated model Ttrunc matches the original model well at high frequencies, but
differs considerably at low frequency. Conversely, Tmatch yields a good match at low
frequencies as expected, at the expense of high-frequency accuracy.
You can also see the differences between the two methods by examining the time-domain
response in different regimes. Compare the slow dynamics by looking at the step
response of all three models with a long time horizon.
stepplot(T,Tmatch,'r--',Ttrunc,1500)
legend('Original','DC Match','Truncate')
6-33
6 Model Simplification
As expected, on long time scales the DC-matched approximation Tmatch has a very
similar response to the original model.
stepplot(T,Tmatch,'r',Ttrunc,'g--',0.5)
legend('Original','DC Match','Truncate')
6-34
Balanced Truncation Model Reduction
On short time scales, the truncated approximation Ttrunc provides a better match to the
original model. Which approximation method you should use depends on which regime is
most important for your application.
When computing a reduced-order approximation, the balred command (or the Model
Reducer app) does not eliminate unstable poles because doing so would fundamentally
change the system dynamics. Instead, the software decomposes the model into stable and
unstable parts and reduces the stable part of the model.
6-35
6 Model Simplification
If your model has near-unstable poles, you might want to ensure that the reduced-order
approximation preserves these dynamics. This example shows how to use the Offset
option of balred to preserve poles that are close to the stable-unstable boundary. You
can achieve the same result in the Model Reducer app, on the Balanced Truncation
tab, under Options, using the Offset field, as shown:
load('reduce.mat','gasf35unst')
gasf35unst is a 25-state SISO model with two unstable poles (Re(s) > 0). Examine the
system poles to find the near-unstable poles.
pzplot(gasf35unst)
axis([-0.0015 0.0015 -0.0005 0.0005])
6-36
Balanced Truncation Model Reduction
The pole-zero plot shows several poles (marked by x) that fall in the left half-plane, but
relatively close to the imaginary axis. These are the near-unstable poles. Two of these fall
within 0.0005 of instability. Three more fall within 0.001 of instability.
hsvplot(gasf35unst)
6-37
6 Model Simplification
The plot shows the two unstable modes, but you cannot easily determine the energy
contribution of the near-unstable poles. In your application, you might want to reduce the
model without discarding those poles nearest to instability, even if they are of relatively
low energy. Use the Offset option of balred to calculate a reduced-order system that
preserves the two stable poles that are closest to the imaginary axis. The Offset option
sets the boundary between poles that balred can discard, and poles that balred must
preserve (treat as unstable).
opts = balredOptions('Offset',0.0005);
gasf_arr = balred(gasf35unst,[10 15],opts);
Providing balred an array of target approximation orders [10 15] causes balred to
return an array of approximated models. The array gasf_arr contains two models, a
6-38
Balanced Truncation Model Reduction
bodeplot(gasf35unst,gasf_arr,'r--')
The 15th order approximation is a good frequency-domain match to the original model.
However, the 10th-order approximation shows changes in high-frequency dynamics,
6-39
6 Model Simplification
which might be too large to be acceptable. The 15th-order approximation is likely a better
choice.
load(fullfile(matlabroot,'examples','control','build.mat'),'G')
bodeplot(G)
6-40
Balanced Truncation Model Reduction
G is a 48th-order model with several large peak regions around 5.2 rad/s, 13.5 rad/s, and
24.5 rad/s, and smaller peaks scattered across many frequencies. Examine the Hankel
singular-value plot to see the energy contributions of the model's 48 states.
hsvd(G)
6-41
6 Model Simplification
The singular-value plot suggests that you can discard at least 20 states without significant
impact on the overall system response. Suppose that for your application you are only
interested in the dynamics near the second large peak, between 10 rad/s and 22 rad/s.
Try a few reduced-model orders based on the Hankel singular value plot. Compare their
frequency responses to the original model, especially in the region of that peak.
G18 = balred(G,18);
G10 = balred(G,10);
bodeplot(G,G18,G10,logspace(0.5,1.5,100));
legend('Original','Order 18','Order 10');
6-42
Balanced Truncation Model Reduction
The 18th-order model is a good match to the dynamics in the region of interest. In the
10th order model, however, there is some degradation of the match.
Focus the model reduction on the region of interest to obtain a good match with a lower-
order approximation. First, examine the state energy contributions in that frequency
region only. Use hsvdOptions to specify the frequency interval for hsvd.
hopt = hsvdOptions('FreqIntervals',[10,22]);
hsvd(G,hopt)
6-43
6 Model Simplification
Comparing this plot to the previous Hankel singular-value plot shows that in this
frequency region, many fewer states contribute significantly to the dynamics than
contribute to the overall dynamics.
Try the same reduced-model orders again, this time choosing states to eliminate based
only on their contribution to the frequency interval. Use balredOptions to specify the
frequency interval for balred.
bopt = balredOptions('StateElimMethod','Truncate','FreqIntervals',[10,22]);
GLim18 = balred(G,18,bopt);
GLim10 = balred(G,10,bopt);
bodeplot(G,GLim18,GLim10,logspace(0.5,1.5,100));
legend('Original','Order 18','Order 10');
6-44
See Also
See Also
Apps
Model Reducer
Functions
balred | hsvplot
6-45
6 Model Simplification
Related Examples
• “Mode-Selection Model Reduction” on page 6-57
• “Pole-Zero Simplification” on page 6-47
• “Model Reduction Basics” on page 6-2
6-46
Pole-Zero Simplification
Pole-Zero Simplification
Pole-zero simplification reduces the order of your model exactly by canceling pole-zero
pairs or eliminating states that have no effect on the overall model response. Pole-zero
pairs can be introduced, for example, when you construct closed-loop architectures.
Normal small errors associated with numerical computation can convert such canceling
pairs to near-canceling pairs. Removing these states preserves the model response
characteristics while simplifying analysis and control design. Types of pole-zero
simplification include:
• Structural elimination — Eliminate states that are structurally disconnected from the
inputs or outputs. Eliminating structurally disconnected states is a good first step in
model reduction because the process does not involve any numerical computation. It
also preserves the state structure of the remaining states. At the command line,
perform structural elimination with sminreal.
• Pole-zero cancellation or minimal realization — Eliminate canceling or near-canceling
pole-zero pairs from transfer functions. Eliminate unobservable or uncontrollable
states from state-space models. At the command line, perform this kind of
simplification with minreal.
1 Open the app and import a model to reduce. For instance, suppose that there is a
model named build in the MATLAB workspace. The following command opens
Model Reducer and imports the LTI model build.
modelReducer(build)
2
In the Data Browser, select the model to reduce. Click Pole-Zero
Simplification.
6-47
6 Model Simplification
6-48
Pole-Zero Simplification
The pole-zero map marks pole locations with x and zero locations with o.
Note The frequency response is a Bode plot for SISO models, and a singular-value
plot for MIMO models.
3 Optionally, change the tolerance with which Model Reducer identifies canceling
pole-zero pairs. Model Reducer cancels pole-zero pairs that fall within the tolerance
specified by the Simplification of pole-zero pairs value. In this case, no pole-zero
6-49
6 Model Simplification
pairs are close enough together for Model Reducer to cancel them at the default
tolerance of 1e-05. To cancel pairs that are a little further apart, move the slider to
the right or enter a larger value in the text box.
The blue x and o marks on the pole-zero map show the near-canceling pole-zero pairs
in the original model that are eliminated from the simplified model. Poles and zeros
remaining in the simplified model are marked with red x and o.
4 Try different simplification tolerances while observing the frequency response of the
original and simplified model. Remove as many poles and zeros as you can while
preserving the system behavior in the frequency region that is important for your
6-50
Pole-Zero Simplification
application. Optionally, examine absolute or relative error between the original and
simplified model. Select the error-plot type using the buttons on the Pole-Zero
Simplification tab.
For more information about using the analysis plots, see “Visualize Reduced-Order
Models in the Model Reducer App” on page 6-67.
5 When you have a simplified model that you want to store and analyze further, click
. The new model appears in the Data Browser with a name that reflects the
reduced model order.
6-51
6 Model Simplification
After creating a reduced model in the Data Browser, you can continue changing the
simplification parameters and create reduced models with different orders for
analysis and comparison.
You can now perform further analysis with the reduced model. For example:
• Examine other responses of the reduced system, such as the step response or Nichols
plot. To do so, use the tools on the Plots tab. See “Visualize Reduced-Order Models in
the Model Reducer App” on page 6-67 for more information.
• Export reduced models to the MATLAB workspace for further analysis or control
To create a MATLAB script you can use for further model-reduction tasks at the command
line, click Create Reduced Model, and select Generate MATLAB Script.
6-52
Pole-Zero Simplification
Model Reducer creates a script that uses the minreal command to perform model
reduction with the parameters you have set on the Pole-Zero Simplification tab. The
script opens in the MATLAB editor.
Create a model of the following system, where C is a PI controller, and G has a zero at
rad/s. Such a low-frequency zero can arise from derivative action somewhere in
the plant dynamics. For example, the plant may include a component that computes speed
from position measurements.
6-53
6 Model Simplification
G = zpk(3e-8,[-1,-3],1);
C = pid(1,0.3);
T = feedback(G*C,1)
T =
(s+0.3) (s-3e-08)
----------------------
s (s+4.218) (s+0.7824)
In the closed-loop model T, the integrator from C very nearly cancels the low-
frequency zero of G.
Force a cancelation of the integrator with the zero near the origin.
Tred = minreal(T,1e-7)
Tred =
(s+0.3)
--------------------
(s+4.218) (s+0.7824)
By default, minreal reduces transfer function order by canceling exact pole-zero pairs or
near pole-zero pairs within sqrt(eps). Specifying 1e-7 as the second input causes
minreal to eliminate pole-zero pairs within rad/s of each other.
The reduced model Tred includes all the dynamics of the original closed-loop model T,
except for the near-canceling zero-pole pair.
6-54
Pole-Zero Simplification
bode(T,Tred,'r--')
legend('T','Tred')
Because the canceled pole and zero do not match exactly, some extreme low-frequency
dynamics evident in the original model are missing from Tred. In many applications, you
can neglect such extreme low-frequency dynamics. When you increase the matching
tolerance of minreal, make sure that you do not eliminate dynamic features that are
relevant to your application.
6-55
6 Model Simplification
See Also
Apps
Model Reducer
Functions
minreal | sminreal
Related Examples
• “Balanced Truncation Model Reduction” on page 6-17
• “Mode-Selection Model Reduction” on page 6-57
• “Model Reduction Basics” on page 6-2
6-56
Mode-Selection Model Reduction
For more general information about model reduction, see “Model Reduction Basics” on
page 6-2.
1 Open the app and import an LTI model to reduce. For instance, suppose that there is
a model named Gms in the MATLAB workspace. The following command opens Model
Reducer and imports the model.
modelReducer(Gms)
2
In the Data Browser, select the model to reduce. Click Mode Selection.
6-57
6 Model Simplification
In the Mode Selection tab, Model Reducer displays a plot of the frequency
response of the original model and a reduced version of the model. The app also
displays a pole-zero map of both models.
6-58
Mode-Selection Model Reduction
The pole-zero map marks pole locations with x and zero locations with o.
Note The frequency response is a Bode plot for SISO models, and a singular-value
plot for MIMO models.
6-59
6 Model Simplification
3 Model Reducer eliminates poles that lie outside the shaded region. Change the
shaded region to capture only the dynamics you want to preserve in the reduced
model. There are two ways to do so.
• On either the response plot or the pole-zero map, drag the boundaries of the
shaded region or the shaded region itself.
• On the Mode Selection tab, enter lower and upper cutoff frequencies.
When you change the shaded regions or cutoff frequencies, Model Reducer
automatically computes a new reduced-order model. All poles retained in the reduced
6-60
Mode-Selection Model Reduction
model fall within the shaded region on the pole-zero map. The reduced model might
contain zeros that fall outside the shaded region.
4 Optionally, examine absolute or relative error between the original and simplified
model. Select the error-plot type using the buttons on the Mode Selection tab.
For more information about using the analysis plots, see “Visualize Reduced-Order
Models in the Model Reducer App” on page 6-67.
5 When you have one or more reduced models that you want to store and analyze
6-61
6 Model Simplification
After creating a reduced model in the Data Browser, you can continue adjusting the
mode-selection region to create reduced models with different orders for analysis and
comparison.
You can now perform further analysis with the reduced model. For example:
• Examine other responses of the reduced system, such as the step response or Nichols
plot. To do so, use the tools on the Plots tab. See “Visualize Reduced-Order Models in
the Model Reducer App” on page 6-67 for more information.
• Export reduced models to the MATLAB workspace for further analysis or control
To create a MATLAB script you can use for further model-reduction tasks at the command
line, click Create Reduced Model, and select Generate MATLAB Script.
6-62
Mode-Selection Model Reduction
Model Reducer creates a script that uses the freqsep command to perform model
reduction with the parameters you have set on the Mode Selection tab. The script opens
in the MATLAB editor.
For this example, load the model Gms and examine its frequency response.
6-63
6 Model Simplification
Gms has two sets of resonances, one at relatively low frequency and the other at relatively
high frequency. Suppose that you want to tune a controller for Gms, but the actuator in
your system is limited to a bandwidth of about 3 rad/s, in between the two groups of
resonances. To simplify calculation and tuning using Gms, you can use mode selection to
eliminate the high-frequency dynamics.
[Gms_s,Gms_f] = freqsep(Gms,30);
freqsep decomposes Gms into slow and fast components such that Gms = Gms_s +
Gms_f. All modes (poles) with natural frequency less than 30 are in Gms_s, and the
higher-frequency poles are in Gms_f.
bodeplot(Gms,Gms_s,Gms_f)
legend('original','slow','fast')
6-64
Mode-Selection Model Reduction
The slow component, Gms_s, contains only the lower-frequency resonances and matches
the DC gain of the original model. Examine the orders of both models.
order(Gms)
ans = 18
order(Gms_s)
ans = 10
When the high-frequency dynamics are unimportant for your application, you can use the
10th-order Gms_s instead of the original 18th-order model. If neglecting low-frequency
dynamics is appropriate for your application, you can use Gms_f. To select modes that fall
between a low-frequency and a high-frequency cutoff, use additional calls to freqsep.
6-65
6 Model Simplification
See Also
Model Reducer | freqsep
Related Examples
• “Balanced Truncation Model Reduction” on page 6-17
• “Pole-Zero Simplification” on page 6-47
• “Model Reduction Basics” on page 6-2
6-66
Visualize Reduced-Order Models in the Model Reducer App
For more general information about model reduction, see “Model Reduction Basics” on
page 6-2.
Error Plots
By default, for any model reduction method, Model Reducer shows a frequency-response
plot of both the original and reduced models. This plot is a Bode plot for SISO models,
and a singular-value plot for MIMO models.
To more closely examine the differences between an original model and a reduced model,
you can use absolute error or relative error plots. On any model reduction tab, click
Absolute error plot or Relative error plot to view these plots.
6-67
6 Model Simplification
• Absolute error plot — Shows the singular values of G-Gr, where G is the original
model and Gr is the current reduced model.
• Relative error plot — Shows the singular values of (G-Gr)/G. This plot is useful
when the model has very high or very low gain in the region that is important to your
application. In such regions, absolute error can be misleading.
For SISO models, the singular-value plot is the magnitude of the frequency response.
Response Plots
After you click to add one or more reduced models to the Data Browser, compare
additional responses of the original and reduced models using the Plots tab.
In the Data Browser, select one or more models to plot. (Ctrl-click to select multiple
models.) Then, on the Plots tab, click the type of plot you want to create.
6-68
Visualize Reduced-Order Models in the Model Reducer App
In the Data Browser, select the model to add. Then, on the Plots tab, click the icon
corresponding to the plot you want to update. Plots you have created appear on the left
side of the plot gallery.
6-69
6 Model Simplification
Plot Characteristics
On any plot in Model Reducer:
• To see response information and data values, click a line on the plot.
6-70
Visualize Reduced-Order Models in the Model Reducer App
6-71
6 Model Simplification
Plot Tools
Mouse over any plot to access plot tools at the upper right corner of the plot.
6-72
Visualize Reduced-Order Models in the Model Reducer App
•
and — Zoom in and zoom out. Click to activate, and drag the cursor over the
region to zoom. The zoom icon turns dark when zoom is active. Right-click while zoom
is active to access additional zoom options.Click the icon again to deactivate.
•
— Pan. Click to activate, and drag the cursor across the plot area to pan. The pan
icon turns dark when pan is active. Right-click while pan is active to access additional
pan options. Click the icon again to deactivate.
•
— Legend. By default, the plot legend is active. To toggle the legend off and on,
click this icon. To move the legend, drag it to a new location on the plot.
To change the way plots are tiled or sorted, use the options on the View tab.
6-73
6 Model Simplification
See Also
Model Reducer
Related Examples
• “Balanced Truncation Model Reduction” on page 6-17
• “Mode-Selection Model Reduction” on page 6-57
• “Pole-Zero Simplification” on page 6-47
6-74
Linear Analysis
75
7
Time Responses
sys =
8 s^2 + 18 s + 32
-----------------------
s^3 + 6 s^2 + 14 s + 24
You can plot the step and impulse responses of this system using the step and impulse
commands:
subplot(2,1,1)
step(sys)
subplot(2,1,2)
impulse(sys)
7-2
Plotting System Responses
You can also simulate the response to an arbitrary signal, for example, a sine wave, using
the lsim command. The input signal appears in gray and the system's response in blue.
clf
t = 0:0.01:4;
u = sin(10*t);
lsim(sys,u,t) % u,t define the input signal
7-3
7 Time Domain Analysis
You can use the plotting commands with continuous or discrete TF, SS, or ZPK models.
For state-space models, you can also plot the unforced response from some given initial
state, for example:
7-4
Plotting System Responses
Frequency Responses
sys =
8 s^2 + 18 s + 32
-----------------------
7-5
7 Time Domain Analysis
s^3 + 6 s^2 + 14 s + 24
bode(sys)
grid
nyquist(sys)
grid
7-6
Plotting System Responses
nichols(sys)
grid
7-7
7 Time Domain Analysis
The poles and zeros of a system contain valuable information about its dynamics, stability,
and limits of performance. For example, consider the feedback loop in Figure 1 where
7-8
Plotting System Responses
For the gain value k = 0.7, you can plot the closed-loop poles and zeros using pzmap:
s = tf('s');
G = -(2*s+1)/(s^2+3*s+2);
k = 0.7;
T = feedback(G*k,1);
pzmap(T)
grid, axis([-2 0 -1 1])
7-9
7 Time Domain Analysis
The closed-loop poles (marked by blue x's) lie in the left half-plane so the feedback loop is
stable for this choice of gain k. You can read the damping ratio of the closed-loop poles
from this chart (see labels on the radial lines). Here the damping ratio is about 0.7,
suggesting a well-damped closed-loop response as confirmed by:
clf
step(T)
7-10
Plotting System Responses
To further understand how the loop gain k affects closed-loop stability, you can plot the
locus of the closed-loop poles as a function of k:
rlocus(G)
grid
7-11
7 Time Domain Analysis
Clicking where the locus intersects the y axis reveals that the closed-loop poles become
unstable for k = 1.51. So the loop gain should remain smaller than 1.5 for closed-loop
stability.
7-12
Plotting System Responses
Response Characteristics
Using the example from the previous section, plot the closed-loop step response:
step(T)
7-13
7 Time Domain Analysis
Now, right-click on the plot to display the Peak Response and Settling Time
Characteristics, and click on the blue dots to read the corresponding overshoot and
settling time values:
7-14
Plotting System Responses
All commands mentioned so far fully support multi-input multi-output (MIMO) systems. In
the MIMO case, these commands produce arrays of plots. For example, the step response
of the two-input, two-output system
sys = rss(3,2,2);
sys.A = [-0.5 -0.3 -0.2 ; 0 -1.3 -1.7; 0.4 1.7 -1.3];
is a 2-by-2 array of plots where each column shows the step response of a particular input
channel:
step(sys)
7-15
7 Time Domain Analysis
If desired, you can group all four responses on a single plot by right-clicking on the plot
and selecting the I/O Grouping -> All submenu. The resulting plot is shown below.
7-16
Plotting System Responses
The following additional plots are useful for analyzing MIMO systems:
• Singular value plot (sigma), which shows the principal gains of the frequency
response
• Pole/zero map for each I/O pair (iopzplot)
sigma(sys)
grid
7-17
7 Time Domain Analysis
Comparing Systems
You can plot multiple systems at once using any of the response plot commands. You can
assign a specific color, marker, or line style to each system for easy comparison. Using the
feedback example above, plot the closed-loop step response for three values of the loop
gain k in three different colors:
k1 = 0.4;
T1 = feedback(G*k1,1);
k2 = 1;
T2 = feedback(G*k2,1);
step(T,'b',T1,'r',T2,'g')
legend('k = 0.7','k = 0.4','k = 1')
7-18
Plotting System Responses
7-19
7 Time Domain Analysis
Time-Domain Responses
When you perform time-domain analysis of a dynamic system model, you may want one or
more of the following:
Control System Toolbox time-domain analysis commands can obtain these results for any
kind of dynamic system model (for example, continuous or discrete, SISO or MIMO, or
arrays of models) except for frequency response data models.
See Also
Related Examples
• “Time-Domain Response Data and Plots” on page 7-21
• “Joint Time-Domain and Frequency-Domain Analysis” on page 7-40
7-20
Time-Domain Response Data and Plots
Create a transfer function model and plot its response to a step input at = 0.
When call step without output arguments, it plots the step response on the screen.
Unless you specify a time range to plot, step automatically chooses a time range that
illustrates the system dynamics.
7-21
7 Time Domain Analysis
Calculate the step response data from = 0 (application of the step input) to = 8 s.
[y,t] = step(H,8);
When you call step with output arguments, the command returns the step response data
y. The vector t contains corresponding time values.
Plot the response of H to an impulse input applied at = 0. Plot the response with a grid.
opts = timeoptions;
opts.Grid = 'on';
impulseplot(H,opts)
Use the timeoptions command to define options sets for customizing time-domain plots
with commands like impulseplot and stepplot.
7-22
See Also
Calculate 200 points of impulse response data from = 1 (one second after application of
the impulse input) to = 3s.
[y,t] = impulse(H,linspace(1,3,200));
As for step, you can omit the time vector to allow impulse to automatically select a time
range.
See Also
impulse | impulseplot | step | stepplot | timeoptions
Related Examples
• “Time-Domain Characteristics on Response Plots” on page 7-24
• “Time-Domain Responses of Multiple Models” on page 7-36
• “Joint Time-Domain and Frequency-Domain Analysis” on page 7-40
More About
• “Time-Domain Responses” on page 7-20
7-23
7 Time Domain Analysis
You can use similar procedures to display system characteristics on impulse response
plots or initial value response plots, such as peak response or settling time.
Create a transfer function model and plot its response to a step input at t = 0.
H = tf([8 18 32],[1 6 14 24]);
stepplot(H)
Right-click anywhere in the figure and select Characteristics > Peak Response from
the menu.
7-24
Time-Domain Characteristics on Response Plots
A marker appears on the plot indicating the peak response. Horizontal and vertical dotted
lines indicate the time and amplitude of that response.
7-25
7 Time Domain Analysis
Click the marker to view the value of the peak response and the overshoot in a datatip.
7-26
See Also
You can use a similar procedure to select other characteristics such as settling time and
rise time from the Characteristics menu and view the values.
See Also
impulse | lsiminfo | step | stepinfo
Related Examples
• “Numeric Values of Time-Domain System Characteristics” on page 7-29
• “Joint Time-Domain and Frequency-Domain Analysis” on page 7-40
7-27
7 Time Domain Analysis
More About
• “Time-Domain Responses” on page 7-20
7-28
Numeric Values of Time-Domain System Characteristics
Create a dynamic system model and get numeric values of the system’s step response
characteristics.
The output is a structure that contains values for several step response characteristics. To
access these values or refer to them in other calculations, use dot notation. For example,
data.Overshoot is the overshoot value.
Calculate the time it takes the step response of H to settle within 0.5% of its final value.
data = stepinfo(H,'SettlingTimeThreshold',0.005);
t05 = data.SettlingTime
t05 = 4.8896
By default, stepinfo defines the settling time as the time it takes for the output to settle
within 0.02 (2%) of its final value. Specifying a more stringent
'SettlingTimeThreshold' of 0.005 results in a longer settling time.
For more information about the options and the characteristics, see the stepinfo
reference page.
7-29
7 Time Domain Analysis
See Also
lsiminfo | stepinfo
Related Examples
• “Time-Domain Characteristics on Response Plots” on page 7-24
• “Joint Time-Domain and Frequency-Domain Analysis” on page 7-40
More About
• “Time-Domain Responses” on page 7-20
7-30
Time-Domain Responses of Discrete-Time Model
You can use the techniques of this example with commands such as impulse, initial,
impulseplot, and initialpot to obtain time-domain responses of discrete-time
models.
Create a discrete-time transfer function model and plot its response to a step input at =
0.
H = tf([-0.06,0.4],[1,-1.6,0.78],0.1);
step(H)
7-31
7 Time Domain Analysis
For discrete-time models, step plots the response at multiples of the sample time,
assuming a hold between samples.
[y,t] = step(H,0.5:0.1:2.5);
When you specify a time vector for the response of a discrete-time model, the time step
must match the sample time Ts of the discrete-time model. The vector t contains the time
points between 0.5 and 2.5 seconds, at multiples of the sample time of H, 0.1 s. The vector
y contains the corresponding step response values.
7-32
See Also
See Also
impulse | impulseplot | initial | initialplot | step | stepplot
Related Examples
• “Time-Domain Responses of MIMO Model” on page 7-34
• “Time-Domain Responses of Multiple Models” on page 7-36
• “Joint Time-Domain and Frequency-Domain Analysis” on page 7-40
More About
• “Time-Domain Responses” on page 7-20
7-33
7 Time Domain Analysis
Create a MIMO model and plot its response to a t = 0 impulse at all inputs.
H = rss(2,2,2);
H.InputName = 'Control';
H.OutputName = 'Temperature';
impulse(H)
7-34
See Also
impulse plots the response of each output to an impulse applied at each input. (Because
rss generates a random state-space model, you might see different responses from those
pictured.) The first column of plots shows the response of each output to an impulse
applied at the first input, Control(1). The second column shows the response of each
output to an impulse applied at the second input, Control(2).
Calculate the impulse responses of all channels of H, and examine the size of the output.
[y,t] = impulse(H);
size(y)
ans = 1×3
207 2 2
The first dimension of the data array y is the number of samples in the time vector t. The
impulse command determines this number automatically if you do not supply a time
vector. The remaining dimensions of y are the numbers of outputs and inputs in H. Thus,
y(:,i,j) is the response at the i th output of H to an impulse applied at the j th input.
See Also
impulse | impulseplot | initial | initialplot | step | stepplot
Related Examples
• “Time-Domain Responses of Multiple Models” on page 7-36
• “Joint Time-Domain and Frequency-Domain Analysis” on page 7-40
More About
• “Time-Domain Responses” on page 7-20
7-35
7 Time Domain Analysis
For this example, obtain two models whose time responses you want to compare, and plot
them on a single step plot. For instance, you can compare a third-order plant G, and the
closed-loop response of G with a controller C1 having integral action.
G = zpk([],[-5 -5 -10],100);
C1 = pid(0,4.4);
CL1 = feedback(G*C1,1);
step(G,CL1);
7-36
Time-Domain Responses of Multiple Models
When you provide multiple models to step as input arguments, the command displays the
responses of both models on the same plot. If you do not specify a time range to plot,
step attempts to choose a time range that illustrates the dynamics of all the models.
Compare the step response of the closed-loop model with another controller. Specify plot
colors and styles for each response.
C2 = pid(2.9,7.1);
CL2 = feedback(G*C2,1);
step(G,'b--',CL1,'g-',CL2,'r-')
7-37
7 Time Domain Analysis
You can specify custom plot color and style for each response in the plot. For example,
'g-' specifies a solid green line for response CL2. For additional plot customization
options, use stepplot.
See Also
Linear System Analyzer | impulse | impulseplot | initial | initialplot | step |
stepplot
7-38
See Also
Related Examples
• “Time-Domain Responses of MIMO Model” on page 7-34
• “Joint Time-Domain and Frequency-Domain Analysis” on page 7-40
More About
• “Time-Domain Responses” on page 7-20
7-39
7 Time Domain Analysis
For example, compare a third-order plant G, and the closed-loop responses of G with two
different controllers, C1 and C2.
G = zpk([],[-5 -5 -10],100);
C1 = pid(0,4.4);
T1 = feedback(G*C1,1);
C2 = pid(2.9,7.1);
T2 = feedback(G*C2,1);
Open the Linear System Analyzer tool to examine the responses of the plant and the
closed-loop systems.
linearSystemAnalyzer(G,T1,T2)
7-40
Joint Time-Domain and Frequency-Domain Analysis
By default, the Linear System Analyzer launches with a plot of the step response of the
three systems. Click to add a legend to the plot.
Add plots of the impulse responses to the Linear System Analyzer display.
In the Linear System Analyzer, select Edit > Plot Configurations to open the Plot
Configurations dialog box.
7-41
7 Time Domain Analysis
Select the two-plot configuration. In the Response Type area, select Bode Magnitude for
the second plot type.
Click OK to add the Bode plots to the Linear System Analyzer display.
Right-click anywhere in the Bode Magnitude plot and select Characteristics > Peak
Response from the menu.
7-42
Joint Time-Domain and Frequency-Domain Analysis
Markers appear on the plot indicating the peak response values. Horizontal and vertical
dotted lines indicate the frequency and amplitude of those responses. Click on a marker
to view the value of the peak response in a datatip.
You can use a similar procedure to select other characteristics such as settling time and
rise time from the Characteristics menu and view the values.
You can also change the type of plot displayed in the Linear System Analyzer. For
example, to change the first plot type to a plot of the impulse response, right-click
anywhere in the plot. Select Plot Types > Impulse
7-43
7 Time Domain Analysis
The displayed plot changes to show the impulse of the three systems.
See Also
Linear System Analyzer | impulse | impulseplot | initial | initialplot | step |
stepplot
Related Examples
• “Time-Domain Responses of Multiple Models” on page 7-36
More About
• “Time-Domain Responses” on page 7-20
7-44
Response from Initial Conditions
sys_dc =
A =
Current w
Current -4 -0.03
w 0.75 -10
B =
Volts
Current 2
w 0
C =
Current w
w 0 1
D =
Volts
w 0
This example uses the SISO, 2-state model sys_dc. This model represents a DC motor.
The input is an applied voltage, and the output is the angular rate of the motor ω. The
states of the model are the induced current (x1), and ω (x2). The model display in the
command window shows the labeled input, output, and states.
Plot the undriven evolution of the motor's angular rate from an initial state in which the
induced current is 1.0 amp and the initial rotation rate is 5.0 rad/s.
7-45
7 Time Domain Analysis
x0 = [1.0 5.0];
initial(sys_dc,x0)
initial plots the time evolution from the specified initial condition on the screen.
Unless you specify a time range to plot, initial automatically chooses a time range that
illustrates the system dynamics.
Calculate the time evolution of the output and the states of sys_dc from =0
(application of the step input) to = 1 s.
t = 0:0.01:1;
[y,t,x] = initial(sys_dc,x0,t);
7-46
See Also
The vector y contains the output at each time step in t. The array x contains the state
values at each time step. Therefore, in this example x is a 2-by-101 array. Each row of x
contains the values of the two states of sys_dc at the corresponding time step.
See Also
impulse | initial | initialplot | step
Related Examples
• “Time-Domain Response Data and Plots” on page 7-21
• “Numeric Values of Time-Domain System Characteristics” on page 7-29
More About
• “Time-Domain Responses” on page 7-20
7-47
7 Time Domain Analysis
In the block parameters, set the LTI system variable parameter to the LTI model to
import. For state-space models, set the Initial states parameter to a vector to specify
non-zero initial states.
To specify a model for the LTI System block, set the LTI system variable block
parameter to either:
• The variable name of an LTI model in the MATLAB® workspace or model workspace,
such as sys.
• A MATLAB expression that evaluates to an LTI model, such as tf(1,[1 1]).
For example, you can specify a state-space (ss), zero-pole-gain (zpk), or transfer function
(tf) model. You can simulate SISO models or MIMO models, and continuous-time or
discrete-time models.
7-48
Import LTI Model Objects into Simulink
7-49
7 Time Domain Analysis
This example simulates the system response to a step input at t = 2 s. Use the LTI System
block to import an LTI model object anywhere in your Simulink model to simulate the
linear system response to any input.
The LTI System block has one input and one output, even when you specify a MIMO
model for the block. In that case, the block input and output become vector signals. For
instance, the model LTISystemBlockMIMO uses an LTI system block to represent a
MIMO plant in a control system.
In this model, the LTI System specified in the block is Gm, a 2-output, 2-input transfer
function model stored in the model workspace. A Mux block combines the two controller
outputs into a vector signal for the LTI System block input. Similarly, a Demux block
separates the vector output of the LTI System block into two scalar signals.
7-50
Import LTI Model Objects into Simulink
7-51
7 Time Domain Analysis
This example simulates a closed-loop system response to a t = 50 s step at the first input
and a t = 150 s step at the second input. You can use the LTI system block anywhere you
want to insert an LTI system into a Simulink model.
See Also
LTI System
7-52
Analysis of Systems with Time Delays
For example, consider the following control loop, where the plant is modeled as first-order
plus dead time:
You can model the closed-loop system from r to y with the following commands:
s = tf('s');
P = 5*exp(-3.4*s)/(s+1);
C = 0.1 * (1 + 1/(5*s));
T = feedback(P*C,1);
T is a state-space model with an internal delay. For more information about models with
internal delays, see “Closing Feedback Loops with Time Delays” on page 2-45.
stepplot(T)
7-53
7 Time Domain Analysis
For more complicated interconnections, you can name the input and output signals of
each block and use connect to automatically take care of the wiring. Suppose, for
example, that you want to add feedforward to the control loop of the previous model.
7-54
Analysis of Systems with Time Delays
F = 0.3/(s+4);
P.InputName = 'u';
P.OutputName = 'y';
C.InputName = 'e';
C.OutputName = 'uc';
F.InputName = 'r';
F.OutputName = 'uf';
Sum1 = sumblk('e','r','y','+-'); % e = r-y
Sum2 = sumblk('u','uf','uc','++'); % u = uf+uc
Tff = connect(P,C,F,Sum1,Sum2,'r','y');
stepplot(T,Tff)
legend('No feedforward','Feedforward')
7-55
7 Time Domain Analysis
The state-space representation keeps track of the internal delays in both models.
Gain ripple:
7-56
Analysis of Systems with Time Delays
s = tf('s');
G = exp(-5*s)/(s+1);
T = feedback(G,.5);
bodemag(T)
Gain oscillations:
G = 1 + 0.5 * exp(-3*s);
bodemag(G)
7-57
7 Time Domain Analysis
G = exp(-s) * (0.8*s^2+s+2)/(s^2+s);
T = feedback(G,1);
stepplot(T)
7-58
Analysis of Systems with Time Delays
Chaotic response:
G = 1/(s+1) + exp(-4*s);
T = feedback(1,G);
stepplot(T,150)
7-59
7 Time Domain Analysis
You can use Control System Toolbox tools to model and analyze these and other strange-
appearing artifacts of internal delays.
See Also
Related Examples
• “Closing Feedback Loops with Time Delays” on page 2-45
7-60
See Also
More About
• “Time Delays in Linear Systems” on page 2-40
• “Internal Delays” on page 2-73
7-61
8
Frequency-Domain Responses
When you perform frequency-domain analysis of a dynamic system model, you may want
one or more of the following:
• A plot of the system response as a function of frequency, or plots of pole and zero
locations.
• Numerical values of the system response in a data array.
• Numerical values of characteristics of the system response such as stability margins,
peak gains, or singular values.
Control System Toolbox frequency-domain analysis commands can obtain these results for
any kind of dynamic system model (for example, continuous or discrete, SISO or MIMO,
or arrays of models).
• pzplot, iopzplot — Plot pole and zero locations in the complex plane.
If you have a generalized state-space (genss) model of a control system, you can extract
various transfer functions from it for analysis using frequency-domain and time-domain
analysis commands. Extract responses from such models using getIOTransfer,
getLoopTransfer, getSensitivity, and getCompSensitivity.
8-2
See Also
See Also
Related Examples
• “Frequency Response of a SISO System” on page 8-4
• “Frequency Response of a MIMO System” on page 8-6
• “Joint Time-Domain and Frequency-Domain Analysis” on page 7-40
8-3
8 Frequency Domain Analysis
H = tf([10,21],[1,1.4,26]);
bode(H)
When you can bode without output arguments, it plots the frequency response on the
screen. Unless you specify a frequency range to plot, bode automatically chooses a
frequency range based on the system dynamics.
8-4
See Also
[mag,phase,w] = bode(H,{1,13});
When you call bode with output arguments, the command returns vectors mag and phase
containing the magnitude and phase of the frequency response. The cell array input
{1,13} tells bode to calculate the response at a grid of frequencies between 1 and 13
rad/s. bode returns the frequency points in the vector w.
See Also
bode | bodeoptions | bodeplot
Related Examples
• “Frequency Response of a MIMO System” on page 8-6
• “Numeric Values of Frequency-Domain Characteristics of SISO Model” on page 8-
13
More About
• “Frequency-Domain Responses” on page 8-2
8-5
8 Frequency Domain Analysis
Calculate the frequency response of a MIMO model and examine the size of the output.
H = rss(2,2,2);
H.InputName = 'Control';
H.OutputName = 'Temperature';
[mag,phase,w] = bode(H);
size(mag)
ans = 1×3
2 2 70
The first and second dimension of the data array mag are the number of outputs and
inputs of H. The third dimension is the number of points in the frequency vector w. (The
bode command determines this number automatically if you do not supply a frequency
vector.) Thus, mag(i,j,:) is the frequency response from the j th input of H to the i th
output, in absolute units. The phase data array phase takes the same form as mag.
bode(H)
8-6
Frequency Response of a MIMO System
bode plots the magnitude and the phase of the frequency response of each input/output
pair in H. (Because rss generates a random state-space model, you might see different
responses from those pictured.) The first column of plots shows the response from the
first input, Control(1), to each output. The second column shows the response from the
second input, Control(2), to each output.
sigma(H)
8-7
8 Frequency Domain Analysis
sigma plots the singular values of the MIMO system H as a function of frequency. The
maximum singular value at a particular frequency is the maximum gain of the system over
all linear combinations of inputs at that frequency. Singular values can provide a better
indication of the overall response, stability, and conditioning of a MIMO system than a
channel-by-channel Bode plot.
When you call sigma with output arguments, the command returns the singular values in
the data array sv. The cell array input {0.1,10} tells sigma to calculate the singular
values at a grid of frequencies between 0.1 and 10 rad/s. sigma returns these frequencies
in the vector w. Each row of sv contains the singular values of H at the frequencies of w.
8-8
See Also
See Also
bode | bodeplot | sigma | sigmaplot
Related Examples
• “Numeric Values of Frequency-Domain Characteristics of SISO Model” on page 8-
13
• “Joint Time-Domain and Frequency-Domain Analysis” on page 7-40
8-9
8 Frequency Domain Analysis
You can use similar procedures to display system characteristics on other types of
response plots.
Right-click anywhere in the figure and select Characteristics > Peak Response from
the menu.
8-10
Frequency-Domain Characteristics on Response Plots
A marker appears on the plot indicating the peak response. Horizontal and vertical dotted
lines indicate the frequency and magnitude of that response. The other menu options add
other system characteristics to the plot.
8-11
8 Frequency Domain Analysis
Click the marker to view the magnitude and frequency of the peak response in a datatip.
See Also
Related Examples
• “Numeric Values of Frequency-Domain Characteristics of SISO Model” on page 8-
13
• “Joint Time-Domain and Frequency-Domain Analysis” on page 7-40
• “Pole and Zero Locations” on page 8-16
8-12
Numeric Values of Frequency-Domain Characteristics of SISO Model
H = tf([10,21],[1,1.4,26]);
bodeplot(H)
8-13
8 Frequency Domain Analysis
[gpeak,fpeak] = getPeakGain(H);
gpeak_dB = mag2db(gpeak)
gpeak_dB = 17.7579
getPeakGain returns both the peak location fpeak and the peak gain gpeak in absolute
units. Using mag2db to convert gpeak to decibels shows that the gain peaks at almost 18
dB.
Find the band within which the system gain exceeds 0 dB, or 1 in absolute units.
wc = getGainCrossover(H,1)
wc = 2×1
1.2582
12.1843
The Bode response plot shows that the gain of H tends toward a finite value as the
frequency approaches zero. The dcgain command finds this value in absolute units.
k = dcgain(H);
Find the frequency at which the response of H rolls off to –10 dB relative to its dc value.
fb = bandwidth(H,-10);
bandwidth returns the first frequency at which the system response drops below the dc
gain by the specified value in dB.
8-14
See Also
See Also
bandwidth | getGainCrossover | getPeakGain
Related Examples
• “Pole and Zero Locations” on page 8-16
More About
• “Frequency-Domain Responses” on page 8-2
8-15
8 Frequency Domain Analysis
Examining the pole and zero locations can be useful for tasks such as stability analysis or
identifying near-canceling pole-zero pairs for model simplification. This example
compares two closed-loop systems that have the same plant and different controllers.
G = zpk([],[-5 -5 -10],100);
C1 = pid(2.9,7.1);
CL1 = feedback(G*C1,1);
C2 = pid(29,7.1);
CL2 = feedback(G*C2,1);
The controller C2 has a much higher proportional gain. Otherwise, the two closed-loop
systems CL1 and CL2 are the same.
Graphically examine the pole and zero locations of CL1 and CL2.
pzplot(CL1,CL2)
grid
8-16
Pole and Zero Locations
pzplot plots pole and zero locations on the complex plane as x and o marks,
respectively. When you provide multiple models, pzplot plots the poles and zeros of each
model in a different color. Here, there poles and zeros of CL1 are blue, and those of CL2
are green.
The plot shows that all poles of CL1 are in the left half-plane, and therefore CL1 is stable.
From the radial grid markings on the plot, you can read that the damping of the
oscillating (complex) poles is approximately 0.45. The plot also shows that CL2 contains
poles in the right half-plane and is therefore unstable.
8-17
8 Frequency Domain Analysis
zero and pole return column vectors containing the zero and pole locations of the
system.
See Also
pole | pzplot | zero
Related Examples
• “Numeric Values of Frequency-Domain Characteristics of SISO Model” on page 8-13
More About
• “Frequency-Domain Responses” on page 8-2
8-18
Assessing Gain and Phase Margins
Stability generally means that all internal signals remain bounded. This is a standard
requirement for control systems to avoid loss of control and damage to equipment. For
linear feedback systems, stability can be assessed by looking at the poles of the closed-
loop transfer function. Consider for example the SISO feedback loop:
For a unit loop gain k, you can compute the closed-loop transfer function T using:
G = tf([.5 1.3],[1 1.2 1.6 0]);
T = feedback(G,1);
ans =
-0.2305 + 1.3062i
-0.2305 - 1.3062i
-0.7389 + 0.0000i
The feedback loop for k=1 is stable since all poles have negative real parts.
8-19
8 Frequency Domain Analysis
rlocus(G)
Clicking on the point where the locus intersects the y axis reveals that this feedback loop
is stable for
8-20
Assessing Gain and Phase Margins
This range shows that with k=1, the loop gain can increase 270% before you lose stability.
Changes in the loop gain are only one aspect of robust stability. In general, imperfect
plant modeling means that both gain and phase are not known exactly. Because modeling
errors are most damaging near the gain crossover frequency (frequency where open-loop
gain is 0dB), it also matters how much phase variation can be tolerated at this frequency.
The phase margin measures how much phase variation is needed at the gain crossover
frequency to lose stability. Similarly, the gain margin measures what relative gain
variation is needed at the gain crossover frequency to lose stability. Together, these two
numbers give an estimate of the "safety margin" for closed-loop stability. The smaller the
stability margins, the more fragile stability is.
You can display the gain and phase margins on a Bode plot as follows. First create the
plot:
bode(G), grid
8-21
8 Frequency Domain Analysis
Then, right-click on the plot and select the Characteristics -> Minimum Stability
Margins submenu. Finally, click on the blue dot markers. The resulting plot is shown
below:
8-22
Assessing Gain and Phase Margins
This indicates a gain margin of about 9 dB and a phase margin of about 45 degrees. The
corresponding closed-loop step response exhibits about 20% overshoot and some
oscillations.
8-23
8 Frequency Domain Analysis
[Gm,Pm] = margin(2*G);
GmdB = 20*log10(Gm) % gain margin in dB
Pm % phase margin in degrees
GmdB =
2.7471
Pm =
8-24
Assessing Gain and Phase Margins
8.6328
and the closed-loop response has poorly damped oscillations, a sign of near instability.
Some systems have multiple gain crossover or phase crossover frequencies, which leads
to multiple gain or phase margin values. For example, consider the feedback loop
8-25
8 Frequency Domain Analysis
G = tf(20,[1 7]) * tf([1 3.2 7.2],[1 -1.2 0.8]) * tf([1 -8 400],[1 33 700]);
T = feedback(G,1);
step(T), title('Closed-loop response for k=1')
8-26
Assessing Gain and Phase Margins
To assess how robustly stable this loop is, plot its Bode response:
bode(G), grid
8-27
8 Frequency Domain Analysis
Then, right-click on the plot and select the Characteristics -> All Stability Margins
submenu to show all the crossover frequencies and associated stability margins. The
resulting plot is shown below.
8-28
Assessing Gain and Phase Margins
Note that there are two 180 deg phase crossings with corresponding gain margins of
-9.35dB and +10.6dB. Negative gain margins indicate that stability is lost by decreasing
the gain, while positive gain margins indicate that stability is lost by increasing the gain.
This is confirmed by plotting the closed-loop step response for a plus/minus 6dB gain
variation about k=1:
k1 = 2; T1 = feedback(G*k1,1);
k2 = 1/2; T2 = feedback(G*k2,1);
step(T,'b',T1,'r',T2,'g',12),
legend('k = 1','k = 2','k = 0.5')
8-29
8 Frequency Domain Analysis
The plot shows increased oscillations for both smaller and larger gain values.
You can use the command allmargin to compute all stability margins. Note that gain
margins are expressed as gain ratios, not dB. Use mag2db to convert the values to dB.
m = allmargin(G)
GainMargins_dB = mag2db(m.GainMargin)
m =
8-30
Assessing Gain and Phase Margins
GainMargins_dB =
-9.3510 10.6091
Interactive GUI
To gain additional insight into the connection between stability margins and closed-loop
responses, click on the link below to launch an interactive GUI for tuning the loop gain k
and seeing the effect on margins and closed-loop responses.
margin_gui
8-31
8 Frequency Domain Analysis
See Also
margin | pole
8-32
See Also
Related Examples
• “Pole and Zero Locations” on page 8-16
8-33
8 Frequency Domain Analysis
Many processes involve dead times, also referred to as transport delays or time lags.
Controlling such processes is challenging because delays cause linear phase shifts that
limit the control bandwidth and affect closed-loop stability.
Using the state-space representation, you can create accurate open- or closed-loop
models of control systems with delays and analyze their stability and performance without
approximation. The state-space (SS) object automatically keeps track of "internal" delays
when combining models, see the "Specifying Time Delays" tutorial for more details.
where the process model P has a 2.6 second dead time and the compensator C is a PI
controller:
To analyze the closed-loop response, construct a model T of the closed-loop transfer from
ysp to y. Because there is a delay in this feedback loop, you must convert P and C to state
space and use the state-space representation for analysis:
8-34
Analyzing Control Systems with Delays
T = feedback(P*C,1)
T =
A =
x1 x2 x3
x1 -0.36 -1.24 -0.18
x2 1 0 0
x3 0 1 0
B =
u1
x1 0.5
x2 0
x3 0
C =
x1 x2 x3
y1 0.12 0.48 0.36
D =
u1
y1 0
The result is a third-order model with an internal delay of 2.6 seconds. Internally, the
state-space object T tracks how the delay is coupled with the remaining dynamics. This
structural information is not visible to users, and the display above only gives the A,B,C,D
values when the delay is set to zero.
Use the STEP command to plot the closed-loop step response from ysp to y:
step(T)
8-35
8 Frequency Domain Analysis
The closed-loop oscillations are due to a weak gain margin as seen from the open-loop
response P*C:
margin(P*C)
8-36
Analyzing Control Systems with Delays
bode(T)
grid, title('Closed-loop frequency response')
8-37
8 Frequency Domain Analysis
To improve the design, you can try to notch out the resonance near 1 rad/s:
step(Tnotch), grid
8-38
Analyzing Control Systems with Delays
Many control design algorithms cannot handle time delays directly. A common
workaround consists of replacing delays by their Pade approximations (all-pass filters).
Because this approximation is only valid at low frequencies, it is important to compare the
true and approximate responses to choose the right approximation order and check the
approximation validity.
Use the PADE command to compute Pade approximations of LTI models with delays. For
the PI control example above, you can compare the exact closed-loop response T with the
response obtained for a first-order Pade approximation of the delay:
8-39
8 Frequency Domain Analysis
T1 = pade(T,1);
step(T,'b',T1,'r',100)
grid, legend('Exact','First-Order Pade')
The approximation error is fairly large. To get a better approximation, try a second-order
Pade approximation of the delay:
T2 = pade(T,2);
step(T,'b',T2,'r',100)
grid, legend('Exact','Second-Order Pade')
8-40
Analyzing Control Systems with Delays
The responses now match closely except for the non-minimum phase artifact introduced
by the Pade approximation.
Sensitivity Analysis
Delays are rarely known accurately, so it is often important to understand how sensitive a
control system is to the delay value. Such sensitivity analysis is easily performed using
LTI arrays and the InternalDelay property.
For example, to analyze the sensitivity of the notched PI control above, create 5 models
with delay values ranging from 2.0 to 3.0:
tau = linspace(2,3,5); % 5 delay values
Tsens = repsys(Tnotch,[1 1 5]); % 5 copies of Tnotch
8-41
8 Frequency Domain Analysis
for j=1:5
Tsens(:,:,j).InternalDelay = tau(j); % jth delay value -> jth model
end
step(Tsens)
grid, title('Closed-loop response for 5 delay values between 2.0 and 3.0')
This plot shows that uncertainty on the delay value has little effect on closed-loop
characteristics. Note that while you can change the values of internal delays, you cannot
change how many there are because this is part of the model structure. To eliminate some
internal delays, set their value to zero or use PADE with order zero:
8-42
Analyzing Control Systems with Delays
Tnotch0 = Tnotch;
Tnotch0.InternalDelay = 0;
bode(Tnotch,'b',Tnotch0,'r',{1e-2,3})
grid, legend('Delay = 2.6','No delay','Location','SouthWest')
Discretization
You can use C2D to discretize continuous-time delay systems. Available methods include
zero-order hold (ZOH), first-order hold (FOH), and Tustin. For models with internal
delays, the ZOH discretization is not always "exact," i.e., the continuous and discretized
step responses may not match:
8-43
8 Frequency Domain Analysis
Td = c2d(T,1);
step(T,'b',Td,'r')
grid, legend('Continuous','ZOH Discretization')
To correct such discretization gaps, reduce the sampling period until the continuous and
discrete responses match closely:
Td = c2d(T,0.05);
step(T,'b',Td,'r')
grid, legend('Continuous','ZOH Discretization')
8-44
Analyzing Control Systems with Delays
Note that internal delays remain internal in the discretized model and do not inflate the
model order:
order(Td)
Td.InternalDelay
ans =
8-45
8 Frequency Domain Analysis
ans =
52
The time and frequency responses of delay systems can look bizarre and suspicious to
those only familiar with delay-free LTI analysis. Time responses can behave chaotically,
Bode plots can exhibit gain oscillations, etc. These are not software quirks but real
features of such systems. Below are a few illustrations of these phenomena
Gain ripples:
G = exp(-5*s)/(s+1);
T = feedback(G,.5);
bodemag(T)
8-46
Analyzing Control Systems with Delays
Gain oscillations:
G = 1 + 0.5 * exp(-3*s);
bodemag(G)
8-47
8 Frequency Domain Analysis
G = exp(-s) * (0.8*s^2+s+2)/(s^2+s);
T = feedback(G,1);
step(T)
8-48
Analyzing Control Systems with Delays
Chaotic response:
G = 1/(s+1) + exp(-4*s);
T = feedback(1,G);
step(T)
8-49
8 Frequency Domain Analysis
See Also
margin | pade
Related Examples
• “Analyzing the Response of an RLC Circuit” on page 8-52
More About
• “Time Delays in Linear Systems” on page 2-40
8-50
See Also
8-51
8 Frequency Domain Analysis
The following figure shows the parallel form of a bandpass RLC circuit:
8-52
Analyzing the Response of an RLC Circuit
The product LC controls the bandpass frequency while RC controls how narrow the
passing band is. To build a bandpass filter tuned to the frequency 1 rad/s, set L=C=1 and
use R to tune the filter band.
The Bode plot is a convenient tool for investigating the bandpass characteristics of the
RLC network. Use tf to specify the circuit's transfer function for the values
%|R=L=C=1|:
R = 1; L = 1; C = 1;
G = tf([1/(R*C) 0],[1 1/(R*C) 1/(L*C)])
G =
s
-----------
s^2 + s + 1
bode(G), grid
8-53
8 Frequency Domain Analysis
As expected, the RLC filter has maximum gain at the frequency 1 rad/s. However, the
attenuation is only -10dB half a decade away from this frequency. To get a narrower
passing band, try increasing values of R as follows:
8-54
Analyzing the Response of an RLC Circuit
The resistor value R=20 gives a filter narrowly tuned around the target frequency of 1
rad/s.
We can confirm the attenuation properties of the circuit G2 (R=20) by simulating how this
filter transforms sine waves with frequency 0.9, 1, and 1.1 rad/s:
t = 0:0.05:250;
opt = timeoptions;
opt.Title.FontWeight = 'Bold';
subplot(311), lsim(G2,sin(t),t,opt), title('w = 1')
subplot(312), lsim(G2,sin(0.9*t),t,opt), title('w = 0.9')
subplot(313), lsim(G2,sin(1.1*t),t,opt), title('w = 1.1')
8-55
8 Frequency Domain Analysis
The waves at 0.9 and 1.1 rad/s are considerably attenuated. The wave at 1 rad/s comes
out unchanged once the transients have died off. The long transient results from the
poorly damped poles of the filters, which unfortunately are required for a narrow passing
band:
damp(pole(G2))
8-56
Analyzing the Response of an RLC Circuit
Interactive GUI
To analyze other standard circuit configurations such as low-pass and high-pass RLC
networks, click on the link below to launch an interactive GUI. In this GUI, you can
change the R,L,C parameters and see the effect on the time and frequency responses in
real time.
rlc_gui
8-57
8 Frequency Domain Analysis
See Also
bodeplot | lsim | stepplot
Related Examples
• “Joint Time-Domain and Frequency-Domain Analysis” on page 7-40
8-58
9
Sensitivity Analysis
Create an array of transfer functions representing the following low-pass filter at three
values of the roll-off frequency, a.
Create transfer function models representing the filter with roll-off frequency at a = 3, 5,
and 7.
F1 = tf(3,[1 3]);
F2 = tf(5,[1 5]);
F3 = tf(7,[1 7]);
Farray = stack(1,F1,F2,F3);
The first argument to stack specifies the array dimension along which stack builds an
array. The remaining arguments specify the models to arrange along that dimension.
Thus, Farray is a 3-by-1 array of transfer functions.
G = [F1;F2;F3];
When working with a model array that represents parameter variations, You can associate
the corresponding parameter value with each entry in the array. Set the SamplingGrid
property to a data structure that contains the name of the parameter and the sampled
parameter values corresponding with each model in the array. This assignment helps you
keep track of which model corresponds to which parameter value.
9-2
Model Array with Single Parameter Variation
Farray(:,:,1,1) [alpha=3] =
3
-----
s + 3
Farray(:,:,2,1) [alpha=5] =
5
-----
s + 5
Farray(:,:,3,1) [alpha=7] =
7
-----
s + 7
The parameter values in Farray.SamplingGrid are displayed along with the each transfer
function in the array.
Plot the frequency response of the array to examine the effect of parameter variation on
the filter behavior.
bodeplot(Farray)
9-3
9 Sensitivity Analysis
When you use analysis commands such as bodeplot on a model array, the resulting plot
shows the response of each model in the array. Therefore, you can see the range of
responses that results from the parameter variation.
See Also
stack
More About
• “Model Arrays” on page 2-100
9-4
See Also
9-5
9 Sensitivity Analysis
You can use the technique of this example to create higher-dimensional arrays with
variations of more parameters. Such arrays are useful for studying the effects of multiple-
parameter variations on system response.
depends on two parameters: the damping ratio, , and the natural frequency, . If both
and vary, you obtain multiple transfer functions of the form:
Preallocate memory for the model array. Preallocating memory is an optional step that
can enhance computation efficiency. To preallocate, create a model array of the required
size and initialize its entries to zero.
H = tf(zeros(1,1,3,3));
In this example, there are three values for each parameter in the transfer function H.
Therefore, this command creates a 3-by-3 array of single-input, single-output (SISO) zero
transfer functions.
9-6
Model Array with Variations in Two Parameters
H is a 3-by-3 array of transfer functions. varies as you move from model to model along
a single column of H. The parameter varies as you move along a single row.
Plot the step response of H to see how the parameter variation affects the step response.
stepplot(H)
9-7
9 Sensitivity Analysis
You can set the SamplingGrid property of the model array to help keep track of which
set of parameter values corresponds to which entry in the array. To do so, create a grid of
parameter values that matches the dimensions of the array. Then, assign these values to
H.SamplingGrid with the parameter names.
[zetagrid,wgrid] = ndgrid(zeta,w);
H.SamplingGrid = struct('zeta',zetagrid,'w',wgrid);
When you display H, the parameter values in H.SamplingGrid are displayed along with
the each transfer function in the array.
See Also
ndgrid
More About
• “Model Arrays” on page 2-100
• “Study Parameter Variation by Sampling Tunable Model” on page 9-9
9-8
Study Parameter Variation by Sampling Tunable Model
Sample this filter at varying values of the damping constant and the natural frequency
. Create a parametric model of the filter by using tunable elements for and .
wn = realp('wn',3);
zeta = realp('zeta',0.8);
F = tf(wn^2,[1 2*zeta*wn wn^2])
F =
Type "ss(F)" to see the current value, "get(F)" to see all properties, and "F.Blocks" t
F is a genss model with two tunable Control Design Blocks, the realp blocks wn and
zeta. The blocks wn and zeta have initial values of 3 and 0.8, respectively.
Here, sampleBlock samples the model independently over the two values and three
values. Thus, Fsample is a 2-by-3 array of state-space models. Each entry in the array
is a state-space model that represents F evaluated at the corresponding (wn, zeta) pair.
For example, Fsample(:,:,2,3) has wn = 5 and zeta = 1.0.
Set the SamplingGrid property of the model array to help keep track of which set of
parameter values corresponds to which entry in the array. To do so, create a grid of
9-9
9 Sensitivity Analysis
parameter values that matches the dimensions of the array. Then, assign these values to
Fsample.SamplingGrid in a structure with the parameter names.
[wngrid,zetagrid] = ndgrid(wnvals,zetavals);
Fsample.SamplingGrid = struct('wn',wngrid,'zeta',zetagrid);
The ndgrid command produces the full 2-by-3 grid of (wn, zeta) combinations. When
you display Fsample in the command window, the parameter values in
Fsample.SamplingGrid are displayed along with the each transfer function in the
array. The parameter information is also available in response plots. For instance,
examine the step response of Fsample.
stepplot(Fsample)
9-10
See Also
The step response plots show the variation in the natural frequency and damping
constant across the six models in the array. When you click on one of the responses in the
plot, the datatip includes the corresponding wn and zeta values as specified in
Fsample.SamplingGrid.
See Also
sampleBlock
More About
• “Models with Tunable Coefficients” on page 1-19
9-11
9 Sensitivity Analysis
Time delays are rarely known accurately, so it is often important to understand how
sensitive a control system is to the delay value. Such sensitivity analysis is easily
performed using LTI arrays and the InternalDelay property. For example, consider the
notched PI control system developed in "PI Control Loop with Dead Time" from the
example "Analyzing Control Systems with Delays." The following commands create an LTI
model of that closed-loop system, a third-order plant with an input delay, a PI controller
and a notch filter.
s = tf('s');
G = exp(-2.6*s)*(s+3)/(s^2+0.3*s+1);
C = 0.06 * (1 + 1/s);
T = feedback(ss(G*C),1);
notch = tf([1 0.2 1],[1 .8 1]);
C = 0.05 * (1 + 1/s);
Tnotch = feedback(ss(G*C*notch),1);
Tnotch.InternalDelay
ans = 2.6000
The 2.6-second input delay of the plant G becomes an internal delay of 2.6 s in the closed-
loop system. To examine the sensitivity of the responses of Tnotch to variations in this
delay, create an array of copies of Tnotch. Then, vary the internal delay across the array.
The array Tsens contains five models with internal delays that range from 2.0 to 3.0.
stepplot(Tsens)
9-12
See Also
The plot shows that uncertainty on the delay value has a small effect on closed-loop
characteristics.
See Also
More About
• “Time Delays in Linear Systems” on page 2-40
9-13
10
For example, a PID controller is passive because the control signal (the output) moves in
the same direction as the error signal (the input). But a PID controller with delay is not
passive, because the control signal can move in the opposite direction from the error, a
potential cause of instability.
Most physical systems are passive. The Passivity Theorem holds that the negative-
feedback interconnection of two strictly passive systems is passive and stable. As a result,
it can be desirable to enforce passivity of the controller for a passive system, or to
passivate the operator of a passive system, such as the driver of a car.
In practice, passivity can easily be destroyed by the phase lags introduced by sensors,
actuators, and communication delays. These problems have led to extension of the
Passivity Theorem that consider excesses or shortages of passivity, frequency-dependent
measures of passivity, and a mix of passivity and small-gain properties.
Passive Systems
where denotes the transpose of . For physical systems, the integral typically
represents the energy going into the system,. Thus passive systems are systems that only
consume or dissipate energy. As a result, passive systems are intrinsically stable.
10-2
About Passivity and Passivity Indices
For SISO systems, this is saying that at all frequencies, so the entire
Nyquist plot lies in the right-half plane.
Passive systems have the following important properties for control purposes:
10-3
10 Passivity and Conic Sectors
For stability, knowing whether a system is passive or not does not tell the full story. It is
often desirable to know by how much it is passive or fails to be passive. In addition, a
shortage of passivity in the plant can be compensated by an excess of passivity in the
controller, and vice versa. It is therefore important to measure the excess or shortage of
passivity, and this is where passivity indices come into play.
There are different types of indices with different applications. One class of indices
measure the excess or shortage of passivity in a particular direction of the input/output
space. For example, the input passivity index is defined as the largest such that:
for all trajectories and . The system G is input strictly passive (ISP)
when , and has a shortage of passivity when . The input passivity index is also
called the input feedforward passivity (IFP) index because it corresponds to the minimum
static feedforward action needed to make the system passive.
10-4
About Passivity and Passivity Indices
where denotes the smallest eigenvalue. In the SISO case, is the abscissa of the
leftmost point on the Nyquist curve.
Similarly, the output passivity index is defined as the largest such that:
for all trajectories and . The system G is output strictly passive (OSP)
when , and has a shortage of passivity when . The output passivity index is
also called the output feedback passivity (OFP) index because it corresponds to the
minimum static feedback action needed to make the system passive.
In the SISO case, is the abscissa of the leftmost point on the Nyquist curve of .
Combining these two notions leads to the I/O passivity index, which is the largest such
that:
10-5
10 Passivity and Conic Sectors
A system with is very strictly passive. More generally, we can define the index in
the direction as the largest such that:
The input, output, and I/O passivity indices all correspond to special choices of and
are collectively referred to as directional passivity indices. You can use
getPassiveIndex to compute any of these indices for linear systems in either
parametric or FRD form. You can also use passiveplot to plot the input, output, or I/O
passivity indices as a function of frequency. This plot provides insight into which
frequency bands have weaker or stronger passivity.
There are many results quantifying how the input and output passivity indices propagate
through parallel, series, or feedback interconnections. There are also results quantifying
the excess of input or output passivity needed to compensate a given shortage of passivity
in a feedback loop. For details, see:
10-6
About Passivity and Passivity Indices
for all trajectories and . When is minimum phase, you can use
passiveplot to plot the principal gains of . This plot is
entirely analogous to the singular value plot (see sigma), and shows how the degree of
passivity changes with frequency and direction.
The following result is analogous to the Small Gain Theorem for feedback loops. It gives a
simple condition on R-indices for compensating a shortage of passivity in one system by
an excess of passivity in the other.
Small-R Theorem: Let and be two linear systems with passivity R-indices
and , respectively. If , then the negative feedback interconnection of
and is stable.
10-7
10 Passivity and Conic Sectors
See Also
getPassiveIndex | isPassive | passiveplot
Related Examples
• “Passivity Indices” on page 10-19
• “Parallel Interconnection of Passive Systems” on page 10-24
• “Series Interconnection of Passive Systems” on page 10-27
• “Feedback Interconnection of Passive Systems” on page 10-31
• “About Sector Bounds and Sector Indices” on page 10-9
10-8
About Sector Bounds and Sector Indices
In its simplest form, a conic sector is the 2-D region delimited by two lines, and
.
where is a 2x2 symmetric indefinite matrix ( has one positive and one negative
eigenvalue). We call the sector matrix. This concept generalizes to higher dimensions.
In an N-dimensional space, a conic sector is a set:
10-9
10 Passivity and Conic Sectors
Sector Bounds
Sector bounds are constraints on the behavior of a system. Gain constraints and passivity
constraints are special cases of sector bounds. If for all nonzero input trajectories ,
the output trajectory of a linear system satisfies:
then the output trajectories of lie in the conic sector with matrix . Selecting different
matrices imposes different conditions on the system's response. For example, consider
trajectories and the following values:
In other words, passivity is a particular sector bound on the system defined by:
10-10
About Sector Bounds and Sector Indices
Frequency-Domain Condition
Because the time-domain condition must hold for all , deriving an equivalent
frequency-domain bound takes a little care and is not always possible. Let the following:
be (any) decomposition of the indefinite matrix into its positive and negative parts.
When is square and minimum phase (has no unstable zeros), the time-domain
condition:
It is therefore enough to check the sector inequality for real frequencies. Using the
decomposition of , this is also equivalent to:
Note that is square when has as many negative eigenvalues as input channels in
. If this condition is not met, it is no longer enough (in general) to just look at real
frequencies. Note also that if is square, then it must be minimum phase for the
sector bound to hold.
10-11
10 Passivity and Conic Sectors
For instance, examine the sector plot of a 2-output, 2-input system for a particular sector.
rng(4);
H = rss(3,4,2);
Q = [-5.12 2.16 -2.04 2.17
2.16 -1.22 -0.28 -1.11
-2.04 -0.28 -3.35 0.00
2.17 -1.11 0.00 0.18];
sectorplot(H,Q)
10-12
About Sector Bounds and Sector Indices
We can extend the notion of relative passivity index to arbitrary sectors. Let be an
LTI system, and let:
To understand the geometrical interpretation of the R-index, consider the family of cones
10-13
10 Passivity and Conic Sectors
In the diagram,
and
When is square and minimum phase, the R-index can also be characterized in
the frequency domain as the smallest such that:
10-14
About Sector Bounds and Sector Indices
In other words, the R-index is the peak gain of the (stable) transfer function
Similarly, we can extend the notion of directional passivity index to arbitrary sectors.
Given a conic sector with matrix , and a direction , the directional sector index is
the largest such that for all output trajectories :
The directional sector index measures by how much we need to deform the sector in the
direction to make it fit tightly around the output trajectories of . The sector bound
is satisfied if and only if the directional index is positive.
Common Sectors
There are many ways to specify sector bounds. Next we review commonly encountered
expressions and give the corresponding system and sector matrix for the standard
form used by getSectorIndex and sectorplot:
10-15
10 Passivity and Conic Sectors
Passivity
Gain constraint
Ratio of distances
The underlying conic sector is symmetric with respect to . Similarly, the "exterior"
constraint,
10-16
About Sector Bounds and Sector Indices
Double inequality
When dealing with static nonlinearities, it is common to consider conic sectors of the form
where is the nonlinearity output. While this relationship is not a sector bound
per se, it clearly implies:
along all I/O trajectories and for all . This condition in turn is equivalent to a sector
bound with:
Product form
correspond to:
10-17
10 Passivity and Conic Sectors
QSR dissipative
See Also
getSectorCrossover | getSectorIndex | sectorplot
Related Examples
• “About Passivity and Passivity Indices” on page 10-2
10-18
Passivity Indices
Passivity Indices
This example shows how to compute various measures of passivity for linear time-
invariant systems.
Passive Systems
•
The input passivity index is defined as the largest such that
The system G is "input strictly passive" (ISP) when . is also called the "input
feedforward passivity" (IFP) index and corresponds to the minimum feedforward action
needed to make the system passive.
•
The output passivity index is defined as the largest such that
10-19
10 Passivity and Conic Sectors
The system G is "output strictly passive" (OSP) when . is also called the "output
feedback passivity" (OFP) index and corresponds to the minimum feedback action needed
to make the system passive.
•
The I/O passivity index is defined as the largest such that
Circuit Example
Consider the following example. We take the current as the input and the voltage as
the output. Based on Kirchhoff's current and voltage law, we obtain the transfer function
for ,
Let , and .
R = 2; L = 1; C = 0.1;
s = tf('s');
G = (L*s+R)*(R*s+1/C)/(L*s^2 + 2*R*s+1/C);
10-20
Passivity Indices
PF = isPassive(G)
PF = logical
1
nu = 2
rho = 0.2857
tau = 0.2642
Frequency-Domain Characterization
The smallest eigenvalue of the left-hand-side is related to the input passivity index :
10-21
10 Passivity and Conic Sectors
Verify this for the circuit example. Plot the Nyquist plot of the circuit transfer function.
nyquist(G)
The entire Nyquist plot lies in the right-half plane so is positive real. The leftmost
point on the Nyquist curve is so the input passivity index is , the
same value we obtained earlier. Similarly, the leftmost point on the Nyquist curve for
gives the output passivity index value .
10-22
See Also
The relative passivity index (R-index) is the peak gain over frequency of
when is minimum phase, and otherwise:
The system is passive if and only if , and the smaller is, the more passive
the system is. Use getPassiveIndex to compute the R-index for the circuit example.
R = getPassiveIndex(G)
R = 0.5556
The resulting value indicates that the circuit is a very passive system.
See Also
getPassiveIndex | isPassive
Related Examples
• “About Passivity and Passivity Indices” on page 10-2
• “Parallel Interconnection of Passive Systems” on page 10-24
• “Series Interconnection of Passive Systems” on page 10-27
• “Feedback Interconnection of Passive Systems” on page 10-31
10-23
10 Passivity and Conic Sectors
If both systems and are passive, then the interconnected system is guaranteed
to be passive. Take for example
ans = logical
1
G2 = tf([1,2,1],[1,3,10]);
isPassive(G2)
ans = logical
1
10-24
Parallel Interconnection of Passive Systems
ans = logical
1
There is a relationship between the passivity indices of and and the passivity
indices of the interconnected system . Let and denote the input passivity indices
for and , and let and denote the output passivity indices. If all these indices
are nonnegative, then the input passivity index and the output passivity index for the
parallel interconnection satisfy
In other words, we can infer some minimum level of input and output passivity for the
parallel connection from the input and output passivity indices of and . For
details, see the paper by Yu, H., "Passivity and dissipativity as design and analysis tools
for networked control systems," Chapter 2, PhD Thesis, University of Notre Dame, 2012.
Verify the lower bound for the input passivity index .
% Input passivity index for G1
nu1 = getPassiveIndex(G1,'input');
% Input passivity index for G2
nu2 = getPassiveIndex(G2,'input');
% Input passivity index for H
nu = getPassiveIndex(H,'input')
nu = 0.3777
% Lower bound
nu1+nu2
ans = 0.1474
10-25
10 Passivity and Conic Sectors
Similarly, verify the lower bound for the output passivity index of .
rho = 0.6450
% Lower bound
rho1*rho2/(rho1+rho2)
ans = 0.2098
See Also
getPassiveIndex | isPassive
Related Examples
• “About Passivity and Passivity Indices” on page 10-2
• “Series Interconnection of Passive Systems” on page 10-27
• “Feedback Interconnection of Passive Systems” on page 10-31
10-26
Series Interconnection of Passive Systems
ans = logical
1
G2 = tf([1,1,5,.1],[1,2,3,4]);
isPassive(G2)
ans = logical
1
10-27
10 Passivity and Conic Sectors
H = G2*G1;
isPassive(H)
ans = logical
0
This is confirmed by verifying that the Nyquist plot of is not positive real.
nyquist(H)
10-28
Series Interconnection of Passive Systems
While the series interconnection of passive systems is not passive in general, there is a
relationship between the passivity indices of and and the passivity indices of
. Let and denote the input passivity indices for and , and let
and denote the output passivity indices. If all these indices are positive, then the input
passivity index and the output passivity index for the series interconnection
satisfy
In other words, the shortage of passivity at the inputs or outputs of is no worse than
the right-hand-side expressions. For details, see the paper by Arcak, M. and Sontag, E.D.,
"Diagonal stability of a class of cyclic systems and its connection with the secant
criterion," Automatica, Vol 42, No. 9, 2006, pp. 1531-1537. Verify these lower bounds for
the example above.
% Output passivity index for G1
rho1 = getPassiveIndex(G1,'output');
% Output passivity index for G2
rho2 = getPassiveIndex(G2,'output');
% Input passivity index for H=G2*G1
nu = getPassiveIndex(H,'input')
nu = -1.2875
% Lower bound
-0.125/(rho1*rho2)
ans = -2.4119
Similarly, verify the lower bound for the output passivity index of .
% Input passivity index for G1
nu1 = getPassiveIndex(G1,'input');
% Input passivity index for G2
nu2 = getPassiveIndex(G2,'input');
% Output passivity index for H=G2*G1
rho = getPassiveIndex(H,'output')
10-29
10 Passivity and Conic Sectors
rho = -0.6966
% Lower bound
-0.125/(nu1*nu2)
ans = -5.9420
See Also
getPassiveIndex | isPassive
Related Examples
• “About Passivity and Passivity Indices” on page 10-2
• “Parallel Interconnection of Passive Systems” on page 10-24
• “Feedback Interconnection of Passive Systems” on page 10-31
10-30
Feedback Interconnection of Passive Systems
If both systems and are passive, then the interconnected system is guaranteed
to be passive. Take for example
G1 = tf([1,1,1],[1,1,4]);
isPassive(G1)
ans = logical
1
G2 = tf([1,2],[1,5]);
isPassive(G2)
ans = logical
1
10-31
10 Passivity and Conic Sectors
H = feedback(G1,G2);
isPassive(H)
ans = logical
1
nyquist(H)
10-32
Feedback Interconnection of Passive Systems
There is a relationship between the passivity indices of and and the passivity
indices of the interconnected system . Let and denote the input passivity indices
for and , and let and denote the output passivity indices. If all these indices
are positive, then the input passivity index and the output passivity index for the
feedback interconnection satisfy
In other words, we can infer some minimum level of input and output passivity for the
closed-loop system from the input and output passivity indices of and . For
details, see the paper by Zhu, F. and Xia, M and Antsaklis, P.J., "Passivity analysis and
passivation of feedback systems using passivity indices," American Control Conference ,
2014, pp. 1833-1838. Verify the lower bound for the input passivity index .
% Input passivity index for G1
nu1 = getPassiveIndex(G1,'input');
% Output passivity index for G2
rho2 = getPassiveIndex(G2,'output');
% Input passivity index for H
nu = getPassiveIndex(H,'input')
nu = 0.1293
% Lower bound
nu1*rho2/(nu1+rho2)
ans = 2.4923e-06
Similarly, verify the lower bound for the output passivity index of .
% Output passivity index for G1
rho1 = getPassiveIndex(G1,'output');
% Input passivity index for G2
nu2 = getPassiveIndex(G2,'input');
% Output passivity index for H
rho = getPassiveIndex(H,'output')
10-33
10 Passivity and Conic Sectors
rho = 0.4485
% Lower bound
rho1+nu2
ans = 0.4000
See Also
getPassiveIndex | isPassive
Related Examples
• “About Passivity and Passivity Indices” on page 10-2
• “Parallel Interconnection of Passive Systems” on page 10-24
• “Series Interconnection of Passive Systems” on page 10-27
• “Passive Control with Communication Delays” on page 17-282
10-34
Control Design
35
11
As a first pass, create a model of the plant and design a simple PI controller for it.
C_pi =
1
Kp + Ki * ---
s
info =
Stable: 1
CrossoverFrequency: 0.5205
PhaseMargin: 60.0000
C_pi is a pid controller object that represents a PI controller. The fields of info show
that the tuning algorithm chooses an open-loop crossover frequency of about 0.52 rad/s.
Examine the closed-loop step response (reference tracking) of the controlled system.
11-2
PID Controller Design at the Command Line
To improve the response time, you can set a higher target crossover frequency than the
result that pidtune automatically selects, 0.52. Increase the crossover frequency to 1.0.
[C_pi_fast,info] = pidtune(sys,'PI',1.0)
C_pi_fast =
1
Kp + Ki * ---
s
11-3
11 PID Controller Design
info =
Stable: 1
CrossoverFrequency: 1
PhaseMargin: 43.9973
The new controller achieves the higher crossover frequency, but at the cost of a reduced
phase margin.
T_pi_fast = feedback(C_pi_fast*sys,1);
step(T_pi,T_pi_fast)
axis([0 30 0 1.4])
legend('PI','PI,fast')
11-4
PID Controller Design at the Command Line
This reduction in performance results because the PI controller does not have enough
degrees of freedom to achieve a good phase margin at a crossover frequency of 1.0 rad/s.
Adding a derivative action improves the response.
Design a PIDF controller for Gc with the target crossover frequency of 1.0 rad/s.
[C_pidf_fast,info] = pidtune(sys,'PIDF',1.0)
C_pidf_fast =
1 s
Kp + Ki * --- + Kd * --------
s Tf*s+1
11-5
11 PID Controller Design
info =
Stable: 1
CrossoverFrequency: 1
PhaseMargin: 60.0000
The fields of info show that the derivative action in the controller allows the tuning
algorithm to design a more aggressive controller that achieves the target crossover
frequency with a good phase margin.
Compare the closed-loop step response and disturbance rejection for the fast PI and PIDF
controllers.
T_pidf_fast = feedback(C_pidf_fast*sys,1);
step(T_pi_fast, T_pidf_fast);
axis([0 30 0 1.4]);
legend('PI,fast','PIDF,fast');
11-6
PID Controller Design at the Command Line
You can compare the input (load) disturbance rejection of the controlled system with the
fast PI and PIDF controllers. To do so, plot the response of the closed-loop transfer
function from the plant input to the plant output.
S_pi_fast = feedback(sys,C_pi_fast);
S_pidf_fast = feedback(sys,C_pidf_fast);
step(S_pi_fast,S_pidf_fast);
axis([0 50 0 0.4]);
legend('PI,fast','PIDF,fast');
11-7
11 PID Controller Design
This plot shows that the PIDF controller also provides faster disturbance rejection.
See Also
pid | pidtune
More About
• “Choosing a PID Controller Design Tool”
• “Designing Cascade Control System with PI Controllers” on page 11-9
• “PID Controller Design for Fast Reference Tracking”
11-8
Designing Cascade Control System with PI Controllers
Controller C1 in the outer loop is the primary controller that regulates the primary
controlled variable y1 by setting the set-point of the inner loop. Controller C2 in the inner
loop is the secondary controller that rejects disturbance d2 locally before it propagates to
P1. For a cascade control system to function properly, the inner loop must respond much
faster than the outer loop.
In this example, you will design a single loop control system with a PI controller and a
cascade control system with two PI controllers. The responses of the two control systems
are compared for both reference tracking and disturbance rejection.
Plant
11-9
11 PID Controller Design
P2 = zpk([],-2,3);
P1 = zpk([],[-1 -1 -1],10);
Use pidtune command to design a PI controller in standard form for the whole plant
model P = P1 * P2.
The desired open loop bandwidth is 0.2 rad/s, which roughly corresponds to the response
time of 10 seconds.
C =
1 1
Kp * (1 + ---- * ---)
Ti s
11-10
Designing Cascade Control System with PI Controllers
The best practice is to design the inner loop controller C2 first and then design the outer
loop controller C1 with the inner loop closed. In this example, the inner loop bandwidth is
selected as 2 rad/s, which is ten times higher than the desired outer loop bandwidth. In
order to have an effective cascade control system, it is essential that the inner loop
responds much faster than the outer loop.
C2 = pidtune(P2,pidstd(1,1),2);
C2
C2 =
1 1
Kp * (1 + ---- * ---)
Ti s
Tune outer-loop controller C1 with the same bandwidth as the single loop system.
C1 =
1 1
Kp * (1 + ---- * ---)
Ti s
Performance Comparison
First, plot the step reference tracking responses for both control systems.
11-11
11 PID Controller Design
Secondly, plot the step disturbance rejection responses of d2 for both control systems.
11-12
Designing Cascade Control System with PI Controllers
11-13
11 PID Controller Design
From the two response plots you can conclude that the cascade control system performs
much better in rejecting disturbance d2 while the set-point tracking performances are
almost identical.
See Also
pidstd | pidtune
More About
• “Choosing a PID Controller Design Tool”
• “PID Controller Design at the Command Line” on page 11-2
• “Tune PID Controller to Favor Reference Tracking or Disturbance Rejection
(Command Line)”
11-14
Tune 2-DOF PID Controller (Command Line)
2-DOF PID controllers include setpoint weighting on the proportional and derivative
terms. Compared to a 1-DOF PID controller, a 2-DOF PID controller can achieve better
disturbance rejection without significant increase of overshoot in setpoint tracking. A
typical control architecture using a 2-DOF PID controller is shown in the following
diagram.
For this example, design a 2-DOF controller for the plant given by:
Suppose that your target bandwidth for the system is 1.5 rad/s.
wc = 1.5;
G = tf(1,[1 0.5 0.1]);
C2 = pidtune(G,'PID2',wc)
C2 =
1
u = Kp (b*r-y) + Ki --- (r-y) + Kd*s (c*r-y)
s
11-15
11 PID Controller Design
Using the type 'PID2' causes pidtune to generate a 2-DOF controller, represented as a
pid2 object. The display confirms this result. pidtune tunes all controller coefficients,
including the setpoint weights b and c, to balance performance and robustness.
To compute the closed-loop response, note that a 2-DOF PID controller is a 2-input, 1-
output dynamic system. You can resolve the controller into two channels, one for the
reference signal and one for the feedback signal, as shown in the diagram. (See
“Continuous-Time 2-DOF PID Controller Representations” on page 2-16 for more
information.)
Decompose the controller into the components Cr and Cy, and use them to compute the
closed-loop response from r to y.
C2tf = tf(C2);
Cr = C2tf(1);
Cy = C2tf(2);
T2 = Cr*feedback(G,Cy,+1);
S2 = feedback(G,Cy,+1);
11-16
Tune 2-DOF PID Controller (Command Line)
For comparison, design a 1-DOF PID controller with the same bandwidth and compute the
corresponding transfer functions. Then compare the step responses.
C1 = pidtune(G,'PID',wc);
T1 = feedback(G*C1,1);
S1 = feedback(G,C1);
subplot(2,1,1)
stepplot(T1,T2)
title('Reference Tracking')
subplot(2,1,2)
stepplot(S1,S2)
title('Disturbance Rejection')
legend('1-DOF','2-DOF')
11-17
11 PID Controller Design
The plots show that adding the second degree of freedom eliminates the overshoot in the
reference-tracking response without any cost to disturbance rejection. You can improve
disturbance rejection too using the DesignFocus option. This option causes pidtune to
favor disturbance rejection over setpoint tracking.
opt = pidtuneOptions('DesignFocus','disturbance-rejection');
C2dr = pidtune(G,'PID2',wc,opt)
C2dr =
1
u = Kp (b*r-y) + Ki --- (r-y) + Kd*s (c*r-y)
s
With the default balanced design focus, pidtune selects a b value between 0 and 1. For
this plant, when you change design focus to favor disturbance rejection, pidtune sets b
= 0 and c = 0. Thus, pidtune automatically generates an I-PD controller to optimize for
disturbance rejection. (Explicitly specifying an I-PD controller without setting the design
focus yields a similar controller.)
C2dr_tf = tf(C2dr);
Cdr_r = C2dr_tf(1);
Cdr_y = C2dr_tf(2);
T2dr = Cdr_r*feedback(G,Cdr_y,+1);
S2dr = feedback(G,Cdr_y,+1);
subplot(2,1,1)
stepplot(T1,T2,T2dr)
title('Reference Tracking')
subplot(2,1,2)
stepplot(S1,S2,S2dr);
title('Disturbance Rejection')
legend('1-DOF','2-DOF','2-DOF rejection focus')
11-18
Tune 2-DOF PID Controller (Command Line)
The plots show that the disturbance rejection is further improved compared to the
balanced 2-DOF controller. This improvement comes with some sacrifice of reference-
tracking performance, which is slightly slower. However, the reference-tracking response
still has no overshoot.
Thus, using 2-DOF control can improve disturbance rejection without sacrificing as much
reference tracking performance as 1-DOF control. These effects on system performance
depend strongly on the properties of your plant. For some plants and some control
11-19
11 PID Controller Design
bandwidths, using 2-DOF control or changing the design focus has less or no impact on
the tuned result.
See Also
pid2 | pidtune
More About
• “Designing PID Controllers with PID Tuner”
• “Two-Degree-of-Freedom PID Controllers” on page 2-16
• “Tune 2-DOF PID Controller (PID Tuner)” on page 11-21
• “Analyze Design in PID Tuner”
11-20
Tune 2-DOF PID Controller (PID Tuner)
In this example, you represent the plant as an LTI model on page 1-13. For information
about using PID Tuner to tune a PID Controller (2DOF) block in a Simulink model, see
“Design Two-Degree-of-Freedom PID Controllers” (Simulink Control Design).
2-DOF PID controllers include setpoint weighting on the proportional and derivative
terms. Compared to a 1-DOF PID controller, a 2-DOF PID controller can achieve better
disturbance rejection without significant increase of overshoot in setpoint tracking. A
typical control architecture using a 2-DOF PID controller is shown in the following
diagram.
For this example, first design a 1-DOF controller for the plant given by:
1
G ( s) = .
2
s + 0 .5 s + 0 .1
11-21
11 PID Controller Design
Suppose for this example that your application requires a faster response than the PID
Tuner initial design. In the text box next to the Response Time slider, enter 2.
11-22
Tune 2-DOF PID Controller (PID Tuner)
The resulting response is fast, but has a considerable amount of overshoot. Design a 2-
DOF controller to improve the overshoot. First, set the 1-DOF controller as the baseline
controller for comparison. Click the Export arrow and select Save as Baseline.
11-23
11 PID Controller Design
11-24
Tune 2-DOF PID Controller (PID Tuner)
PID Tuner generates a 2-DOF controller with the same target response time. The
controller parameters displayed at the bottom right show that PID Tuner tunes all
11-25
11 PID Controller Design
Adding the second degree of freedom eliminates the overshoot in the reference tracking
response. Next, add a step response plot to compare the disturbance rejection
performance of the two controllers. Select Add Plot > Input Disturbance Rejection.
11-26
Tune 2-DOF PID Controller (PID Tuner)
PID Tuner tiles the disturbance-rejection plot side by side with the reference-tracking
plot.
11-27
11 PID Controller Design
You can improve disturbance rejection too by changing the PID Tuner design focus. First,
click the Export arrow and select Save as Baseline again to set the 2-DOF
controller as the baseline for comparison.
Change the PID Tuner design focus to favor reference tracking without changing the
11-28
Tune 2-DOF PID Controller (PID Tuner)
PID Tuner automatically retunes the controller coefficients with a focus on disturbance-
rejection performance.
11-29
11 PID Controller Design
With the default balanced design focus, PID Tuner selects a b value between 0 and 1. For
this plant, when you change design focus to favor disturbance rejection, PID Tuner sets
b = 0 and c = 0. Thus, PID Tuner automatically generates an I-PD controller to optimize
for disturbance rejection. (Explicitly specifying an I-PD controller without setting the
design focus yields a similar controller.)
The response plots show that with the change in design focus, the disturbance rejection is
further improved compared to the balanced 2-DOF controller. This improvement comes
with some sacrifice of reference-tracking performance, which is slightly slower. However,
the reference-tracking response still has no overshoot.
Thus, using 2-DOF control can improve disturbance rejection without sacrificing as much
reference tracking performance as 1-DOF control. These effects on system performance
depend strongly on the properties of your plant and the speed of your controller. For some
plants and some control bandwidths, using 2-DOF control or changing the design focus
has less or no impact on the tuned result.
See Also
pidTuner
More About
• “Designing PID Controllers with PID Tuner”
• “Two-Degree-of-Freedom PID Controllers” on page 2-16
• “Tune 2-DOF PID Controller (Command Line)” on page 11-15
• “Analyze Design in PID Tuner”
11-30
PID Controller Types for Tuning
• For command-line tuning, provide the type argument to the pidtune command. For
example, C = pidtune(G,'PI') tunes a PI controller for plant G.
• For tuning in PID Tuner:
• Provide the type argument to the pidTuner command when you open PID Tuner.
For example, pidTuner(G,'PIDF2') opens PID Tuner with an initial design that
is a 2-DOF PID controller with a filter on the derivative term.
• Provide the baseline-controller Cbase argument to the pidTuner command when
you open PID Tuner. PID Tuner designs a controller of the same type as Cbase.
For example, suppose C0 is a pid controller object that has proportional and
derivative action only (PD controller). Then, pidTuner(G,C0) opens PID Tuner
with an initial design that is a PD controller.
• In PID Tuner, use the Type menu to change controller types.
11-31
11 PID Controller Design
11-32
PID Controller Types for Tuning
1-DOF Controllers
The following table summarizes the available 1-DOF PID controller types and provides
representative controller formulas for parallel form. The standard-form and discrete-time
formulas are analogous.
2-DOF Controllers
PID Tuner can automatically design 2-DOF PID controller types with free setpoint
weights. The following table summarizes the 2-DOF controller types in PID Tuner. The
standard-form and discrete-time formulas are analogous. For more information about 2-
11-33
11 PID Controller Design
Ki
u = K p ( br - y ) + ( r - y) + K d s ( cr - y)
s
11-34
See Also
If you set b = 0 and c = 0, then changes in the setpoint r do not feed through directly to
either the proportional or the derivative terms in u. The b = 0, c = 0 controller is called
an I-PD type controller. I-PD controllers are also useful for improving disturbance
rejection.
Use PID Tuner to design the fixed-setpoint-weight controller types summarized in the
following table. The standard-form and discrete-time formulas are analogous.
See Also
pidTuner | pidtune
11-35
11 PID Controller Design
More About
• “Designing PID Controllers with PID Tuner”
• “Proportional-Integral-Derivative (PID) Controllers” on page 2-13
• “Two-Degree-of-Freedom PID Controllers” on page 2-16
• “PID Controller Design at the Command Line” on page 11-2
• “PID Controller Design for Fast Reference Tracking”
• “Tune 2-DOF PID Controller (Command Line)” on page 11-15
• “Tune 2-DOF PID Controller (PID Tuner)” on page 11-21
11-36
12
12-2
See Also
See Also
More About
• “PID Controller Tuning”
• “Classical Control Design”
• “Tuning with Control System Tuner”
• “Programmatic Tuning”
12-3
12 Classical Control Design
When using graphical tuning, you can modify the compensator either directly from the
editor plots or using the compensator editor. A common design approach is to roughly
tune your compensator using the editor plots, and then use the compensator editor to
fine-tune the compensator parameters. For more information, see “Edit Compensator
Dynamics” on page 12-93
The graphical tuning methods are not mutually exclusive. For example, you can tune your
compensator using both the Bode editor and root locus editor simultaneously. This option
is useful when designing to both time-domain and frequency-domain specifications.
12-4
Control System Designer Tuning Methods
12-5
12 Classical Control Design
A common design approach is to generate an initial compensator using PID tuning, LQG
synthesis, loop shaping, or IMC tuning. You can then improve the compensator
performance using either optimization-based tuning or graphical tuning.
For more information on automated tuning methods, see “Design Compensator Using
Automated Tuning Methods” on page 12-100.
Knowing the properties of the effective plant seen by your compensator can help you
understand which tuning methods work for your system. For example, some automated
Ÿ
tuning methods apply only to compensators whose open loops ( L = C P ) have stable
12-6
Control System Designer Tuning Methods
Ÿ
effective plants ( P ). Also, for tuning methods such as IMC and loop shaping, the
maximum controller order depends on the dynamics of the effective plant.
12-7
12 Classical Control Design
See Also
Control System Designer
Related Examples
• “Bode Diagram Design” on page 12-49
• “Root Locus Design” on page 12-64
• “Nichols Plot Design” on page 12-80
• “Design Compensator Using Automated Tuning Methods” on page 12-100
12-8
Design Requirements
Design Requirements
This topic describes time-domain and frequency-domain design requirements available in
Control System Designer. Each requirement defines an exclusion region, indicated by a
yellow shaded area. To satisfy a requirement, a response plot must remain outside of the
associated exclusion region.
12-9
12 Classical Control Design
If you have Simulink Design Optimization software installed, you can use response
optimization techniques to find a compensator that meets your specified design
requirements. For examples of optimization-based control design using design
requirements, see “Optimize LTI System to Meet Frequency-Domain Requirements”
(Simulink Design Optimization) and “Design Optimization-Based PID Controller for
Linearized Simulink Model (GUI)” (Simulink Design Optimization).
For other Control System Designer tuning methods, you can use the specified design
requirements as visual guidelines during the tuning process.
To add a design requirement to a plot, in Control System Designer, right-click the plot,
and select Design Requirements > New.
12-10
Design Requirements
In the New Design Requirement dialog box, in the Design requirement type drop-down
list, select the type of requirement to add. You can select any valid requirement for the
associated plot type.
To create the specified requirement and add it to the plot, click OK.
When using optimization-based tuning, you can add design requirements from the
Response Optimization dialog box.
To do so, on the Design Requirements tab, click Add new design requirement.
12-11
12 Classical Control Design
In the New Design Requirement dialog box, select a Design requirement type from the
drop-down list.
In the Requirement for response drop-down list, specify the response to which to apply
the design requirement. You can select any response in Data Browser.
To create the specified design requirement, click OK. In the Response Optimization dialog
box, on the Design Requirements tab, the new requirement is added to the table.
The app also adds the design requirement to a corresponding editor or analysis plot. The
plot type used depends on the selected design requirement type.
Otherwise, if the requirement is for a different plot type, the requirement is added to an
appropriate analysis plot. For example, a Step requirement bound is added to a new
step analysis plot.
12-12
Design Requirements
In the Edit Design Requirement dialog box, in the Design requirement drop-down list,
select a design requirement to edit. You can select any existing design requirement from
the current plot.
You can also interactively adjust design requirements by dragging the edges or vertices of
the shaded exclusion region in the associated plot.
12-13
12 Classical Control Design
Specifying a settling time for a continuous-time system adds a vertical boundary line to
the root locus or pole-zero plot. This line represents pole locations associated with the
specified settling time. This boundary is exact for a second-order system with no zeros.
For higher order systems, the boundary is an approximation based on second-order
dominant systems.
To satisfy this requirement, your system poles must be to the left of the boundary line.
For a discrete-time system, the design requirement boundary is a curved line centered on
the origin. In this case, your system poles must be within the boundary line to satisfy the
requirement.
Percent Overshoot
Specifying percent overshoot for a continuous-time system adds two rays to the plot that
start at the origin. These rays are the locus of poles associated with the specified
overshoot value. In the discrete-time case, the design requirement adds two curves
originating at (1,0) and meeting on the real axis in the left-hand plane.
12-14
Design Requirements
Note The percent overshoot (p.o.) design requirement can be expressed in terms of the
damping ratio, ζ:
Ê pz ˆ
p.o. = 100 exp Á - ˜
Á 1- z 2 ˜
Ë ¯
Damping Ratio
Specifying a damping ratio for a continuous-time system adds two rays to the plot that
start at the origin. These rays are the locus of poles associated with the specified
overshoot value. This boundary is exact for a second-order system and, for higher order
systems, is an approximation based on second-order dominant systems.
To meet this requirement, your system poles must be to the left of the boundary lines.
For discrete-time systems, the design requirement adds two curves originating at (1,0)
and meeting on the real axis in the left-hand plane. In this case, your system poles must
be within the boundary curves.
Natural Frequency
Specifying a natural frequency bound adds a semicircle to the plot that is centered
around the origin. The radius of the semicircle equals the natural frequency.
If you specify a natural frequency lower bound, the system poles must remain outside this
semicircle. If you specify a natural frequency upper bound, the system poles must remain
within this semicircle.
Region Constraint
To specify a region constraint, define two or more vertices of a piece-wise linear boundary
line. For each vertex, specify Real and Imaginary components. This requirement adds a
shaded exclusion region on one side of the boundary line. To switch the exclusion region
to the opposite side of the boundary, in the response plot, right-click the requirement, and
select Flip.
To satisfy this requirement, your system poles must be outside of the exclusion region.
12-15
12 Classical Control Design
You can specify upper gain limits for both open-loop and closed-loop Bode responses.
A gain limit consists of one or more line segments. For the start and end points of each
segment, specify a frequency, Freq, and magnitude, Mag. You can also specify the slope
of the line segment in dB/decade. When you change the slope, the magnitude for the end
point updates.
If you are using optimization-based tuning, you can assign a tuning Weight to each
segment to indicate their relative importance.
In the Type drop-down list you can select whether to constrain the magnitude to be above
or below the specified boundary.
You can specify lower gain limits in the same way as upper gain limits.
You can specify a lower bound for the gain margin, the phase margin, or both. The
specified bounds appear in text on the Bode magnitude plot.
Note Gain and phase margin requirements are only applicable to open-loop Bode
diagrams.
12-16
Design Requirements
Gain Margin
Specify a minimum gain margin value. Graphically, Control System Designer displays
this requirement as a region of exclusion along the -180 degree open-loop phase axis.
Specify a minimum closed-loop peak gain value. The specified dB value can be positive or
negative. The design requirement follows the curves of the Nichols plot grid. As a best
practice, have the grid on when using a closed-loop peak gain requirement.
Display Location
When editing a phase margin, gain margin, or closed-loop peak gain requirement, you can
specify the display location as -180 ± k360 degrees, where k is an integer value.
12-17
12 Classical Control Design
If you enter an invalid location, the closest valid location is selected. While displayed
graphically at only one location, these requirements apply regardless of actual phase; that
is, they are applied for all values of k.
You can specify upper time response bounds for both step and impulse responses.
A time-response bound consists of one or more line segments. For the start and end
points of each segment, specify a Time and Amplitude value. You can also specify the
slope of the line segment. When you change the slope, the amplitude for the end point
updates.
12-18
Design Requirements
If you are using optimization-based tuning, you can assign a tuning Weight to each
segment to indicate its relative importance.
In the Type drop-down list, you can select whether to constrain the response to be above
or below the specified boundary.
You can specify lower time response bounds for both step and impulse responses in the
same way as upper gain limits.
For a step response plot, you can also specify a step response bound design requirement.
To define a step response bound requirement, specify the following step response
parameters:
In Control System Designer, step response plots always use an Initial value and a
Step time of 0
12-19
12 Classical Control Design
See Also
More About
• “Optimize LTI System to Meet Frequency-Domain Requirements” (Simulink Design
Optimization)
• “Design Optimization-Based PID Controller for Linearized Simulink Model (GUI)”
(Simulink Design Optimization)
12-20
Feedback Control Architectures
12-21
12 Classical Control Design
If your control application does not match one of the supported control architectures, you
can use block diagram algebra to convert your system to match an architecture. For an
example of such an application, see “Design Multiloop Control System” on page 12-24.
Note If you are unable to match your application to one of the supported control
architectures, consider using the Control System Tuner app to design your control
system.
12-22
See Also
See Also
Control System Designer | sisoinit
More About
• “Design Multiloop Control System” on page 12-24
12-23
12 Classical Control Design
The typical workflow is to tune the compensator for the inner loop first, by isolating the
inner loop from the rest of the control system. Once the inner loop is satisfactorily tuned,
tune the outer loop to achieve your desired closed-loop response.
System Model
For this example develop a position control system for a DC motor. A single-loop angular
velocity controller is designed in “Bode Diagram Design” on page 12-49. To design an
angular position controller, add an outer loop that contains an integrator.
12-24
Design Multiloop Control System
B = [1/L; 0];
C = [0 1];
D = [0];
sys_dc = ss(A,B,C,D);
Design Objectives
The design objective is to minimize the closed-loop step response settling time, while
maintaining an inner-loop phase margin of at least 65 degrees with maximum bandwidth:
Control System Designer has six possible control architectures from which you can
choose. For more information on these architectures, see “Feedback Control
Architectures” on page 12-21.
For this example use Configuration 4, which has an inner and outer control loop.
Currently, the control system structure does not match Configuration 4. However, using
block diagram algebra, you can modify the system model by adding:
12-25
12 Classical Control Design
At the MATLAB command line, add the integrator to the motor plant model.
plant = sys_dc*tf(1,[1,0]);
Create an initial model of the inner-loop compensator that contains the feedback
differentiator.
Cdiff = tf('s');
controlSystemDesigner
In Control System Designer, on the Control System tab, click Edit Architecture.
In the Edit Architecture dialog box, under Select Control Architecture, click the fourth
architecture.
12-26
Design Multiloop Control System
Import the plant and controller models from the MATLAB workspace.
Click OK.
The app updates the control architecture and imports the specified models for the motor
plant and the inner-loop controller.
12-27
12 Classical Control Design
• Bode Editor for LoopTransfer_C1 — Open-loop Bode Editor for the outer loop
• Root Locus Editor for LoopTransfer_C1 — Open-loop Root Locus Editor for the
outer loop
• Bode Editor for LoopTransfer_C2 — Open-loop Bode Editor for the inner loop
• Root Locus Editor for LoopTransfer_C2 — Open-loop root Locus Editor for the
inner loop
• IOTransfer_r2y: step — Overall closed-loop step response from input r to output y
For this example, close the Bode Editor for LoopTransfer_C1 and Root Locus Editor
for LoopTransfer_C2 plots.
Since the inner loop is tuned first, configure the plots to view just the inner-loop Bode
editor plot. On the View tab, click Single, and click Bode Editor for LoopTransfer_C2.
To isolate the inner loop from the rest of the control system architecture, add a loop
opening to the open-loop response of the inner loop. In the Data Browser, right-click
LoopTransfer_C2, and select Open Selection.
To add a loop opening at the output of outer-loop compensator, C1, in the Open-Loop
Transfer Function dialog box, click Add loop opening location to list. Then, select
uC1.
12-28
Design Multiloop Control System
Click OK.
The app adds a loop opening at the selected location. This opening removes the effect of
the outer control loop on the open-loop transfer function of the inner loop.
The Bode Editor response plot updates to reflect the new open-loop transfer function.
12-29
12 Classical Control Design
To increase the bandwidth of the inner loop, increase the gain of compensator C2.
In the Bode Editor plot, drag the magnitude response upward until the phase margin is
65 degrees. This corresponds to a compensator gain of 107. Increasing the gain further
reduces the phase margin below 65 degrees.
12-30
Design Multiloop Control System
Alternatively, you can adjust the gain value using the compensator editor. For more
information, see “Edit Compensator Dynamics” on page 12-93.
With the inner loop tuned, you can now tune the outer loop to reduce the closed-loop
settling time.
12-31
12 Classical Control Design
In Control System Designer, on the View tab, select Left/Right. Arrange the plots to
display the Root Locus for LoopTransfer_C1 and IOTransfer_r2y_step plots
simultaneously.
To view the current settling time, right-click in the step response plot and select
Characteristics > Settling Time.
In the Root Locus Editor, increase the gain of compensator C1. As the gain increases,
the complex pole pair moves toward a slower time constant and the real pole moves
12-32
See Also
toward a faster time constant. A gain of 600 produces a good compromise between rise
time and settling time.
With a closed-loop settling time below 0.8 seconds and an inner-loop phase margin of 65
degrees, the design satisfies the design requirements.
See Also
Control System Designer
12-33
12 Classical Control Design
More About
• “Feedback Control Architectures” on page 12-21
12-34
Multimodel Control Design
Any controller you design for such a system must satisfy the design requirements for all
potential system dynamics.
Model Arrays
In Control System Designer, you can specify multiple models for any plant or sensor in
the current control architecture using an array of LTI models (see “Model Arrays” on
page 2-100). If you specify model arrays for more than one plant or sensor, the lengths of
the arrays must match.
• Create multiple LTI models using the tf, ss, zpk, or frd commands.
12-35
12 Classical Control Design
To import models as arrays, you can pass them as input arguments when opening Control
System Designer from the MATLAB command line. For more information, see Control
System Designer.
You can also import model arrays into Control System Designer when configuring the
control architecture. In the Edit Architecture dialog box:
• In the Value text box, specify the name of an LTI model from the MATLAB workspace.
• To import block data from the MATLAB workspace or from a MAT-file in your current
12-36
Multimodel Control Design
Nominal Model
What Is a Nominal Model?
The nominal model is a representative model in the array of LTI models that you use to
design the controller in Control System Designer. Use the editor and analysis plots to
visualize and analyze the effect of the controller on the remaining plants in the array.
You can select any model in the array as your nominal model. For example, you can
choose a model that:
12-37
12 Classical Control Design
Tip You can plot and analyze the open-loop dynamics of the system on a Bode plot to
determine which model to choose as nominal.
To select a nominal model from the array of LTI models, in Control System Designer,
click Multimodel Configuration. Then, in the Multimodel Configuration dialog box,
select a Nominal model index. The default index is 1.
For each plant or sensor that is defined as a model array, the app selects the model at the
specified index as the nominal model. Otherwise, the app uses scalar expansion to apply
the single LTI model for all model indices.
if G and H are both three-element arrays and the nominal model index is 2, the software
uses the second element in both the arrays to compute the nominal model:
Nominal Model
r y
2
12-38
Multimodel Control Design
CG2
T=
1 + CG2 H2
The app also computes and plots the responses showing the effect of C on the remaining
pairs of plant and sensor models — G1H1 and G3H3.
If only G is an array of LTI models, and the specified nominal model is 2, then the control
architecture for nominal response is:
Nominal Model
r y
2
CG2
T=
1 + CG2 H
The app also computes and plots the responses showing the effect of C on the remaining
pairs of plant and sensor model — G1H and G3H.
Frequency Grid
The frequency response of a system is computed at a series of frequency values, called a
frequency grid. By default, Control System Designer computes a logarithmically equally
spaced grid based on the dynamic range of each model in the array.
• The automatic grid has more points than you require. To improve computational
efficiency, specify a less dense grid spacing.
• The automatic grid is not sufficiently dense within a particular frequency range. For
example, if the response does not capture the resonant peak dynamics of an
underdamped system, specify a more dense grid around the corner frequency.
12-39
12 Classical Control Design
• You are only interested in the response within specific frequency ranges. To improve
computational efficiency, specify a grid that covers only the frequency ranges of
interest.
Note Modifying the frequency grid does not affect the frequency response computation
for the nominal model. The app always uses the Auto select option to compute the
nominal model frequency response.
H1 = tf(1,[1/0.1,1]);
H2 = tf(1,[1/0.15,1]);
H3 = tf(1,[1/0.2,1]);
H = stack(1,H1,H2,H3);
3 Open Control System Designer
Open Control System Designer, and import the plant and sensor model arrays.
controlSystemDesigner(G,1,H)
12-40
Multimodel Control Design
The app opens and imports the plant and sensor model arrays.
4 Configure Analysis Plot
To view the closed-loop step response in a larger plot, in Control System Designer,
on the View tab, click Single. Then, click IOTransfer_r2y: step.
12-41
12 Classical Control Design
By default the step response shows only the nominal response. To display the
individual responses for the other model indices, right-click the plot area, and select
Multimodel Configuration > Individual Responses.
12-42
Multimodel Control Design
Note To view an envelope of all model responses, right-click the plot area, and select
Multimodel Configuration > Bounds
The plot updates to display the responses for the other models.
12-43
12 Classical Control Design
Click Close.
12-44
Multimodel Control Design
To design a compensator using the nominal model, you can use any of the supported
“Control System Designer Tuning Methods” on page 12-4.
12-45
12 Classical Control Design
For this example, use the Compensator Editor to manually specify the compensator
dynamics. Add an integrator to the compensator and set the compensator gain to
0.4. For more information, see “Edit Compensator Dynamics” on page 12-93.
7 Analyze Results
The tuned controller produces a step response with minimal overshoot for the
nominal models and a worst-case overshoot less than 10%.
12-46
See Also
See Also
Control System Designer
Related Examples
• “Model Arrays” on page 2-100
12-47
12 Classical Control Design
12-48
Bode Diagram Design
To adjust the loop shape, you can add poles and zeros to your compensator and adjust
their values directly in the Bode Editor, or you can use the Compensator Editor. For
more information, see “Edit Compensator Dynamics” on page 12-93.
For information on all of the tuning methods available in Control System Designer, see
“Control System Designer Tuning Methods” on page 12-4.
The transfer function of the DC motor plant, as described in “SISO Example: The DC
Motor”, is:
1.5
G=
2
s + 14 s + 40 .02
12-49
12 Classical Control Design
At the MATLAB command line, create a transfer function model of the plant, and open
Control System Designer in the Bode Editor configuration.
G = tf(1.5,[1 14 40.02]);
controlSystemDesigner('bode',G);
The app opens and imports G as the plant model for the default control architecture,
Configuration 1.
• Open-loop Bode Editor for the LoopTransfer_C response. This response is the
open-loop transfer function GC, where C is the compensator and G is the plant.
• Step Response for the IOTransfer_r2y response. This response is the input-output
transfer function for the overall closed-loop system.
Tip To open the open-loop Bode Editor when Control System Designer is already
open, on the Control System tab, in the Tuning Methods drop-down list, select Bode
Editor. In the Select Response to Edit dialog box, select an existing response to plot, or
create a New Open-Loop Response.
To view the open-loop frequency response and closed-loop step response simultaneously,
on the Views tab, click Left/Right.
The app displays the Bode Editor and Step Response plots side-by-side.
12-50
Bode Diagram Design
Adjust Bandwidth
Since the design requires a rise time less than 0.5 seconds, set the open-loop DC
crossover frequency to about 3 rad/s. To a first-order approximation, this crossover
frequency corresponds to a time constant of 0.33 seconds.
To make the crossover easier to see, turn on the plot grid. Right-click the Bode Editor
plot area, and select Grid. The app adds a grid to the Bode response plots.
To adjust the crossover frequency increase the compensator gain. In the Bode Editor
plot, in the Magnitude response plot, drag the response upward. Doing so increases the
gain of the compensator.
12-51
12 Classical Control Design
As you drag the magnitude plot, the app computes the compensator gain and updates the
response plots.
Drag the magnitude response upward until the crossover frequency is about 3 rad/s.
12-52
Bode Diagram Design
To add the rise time to the Step Response plot, right-click the plot area, and select
Characteristics > Rise Time.
To view the rise time, move the cursor over the rise time indicator.
12-53
12 Classical Control Design
The rise time is around 0.23 seconds, which satisfies the design requirements.
Similarly, to add the peak response to the Step Response plot, right-click the plot area,
and select Characteristics > Peak Response.
12-54
Bode Diagram Design
To meet the 5% steady-state error requirement, eliminate steady-state error from the
closed-loop step response by adding an integrator to your compensator. In the Bode
Editor right-click in the plot area, and select Add Pole/Zero > Integrator.
12-55
12 Classical Control Design
To return the crossover frequency to around 3 rad/s, increase the compensator gain
further. Right-click the Bode Editor plot area, and select Edit Compensator.
In the Compensator Editor dialog box, in the Compensator section, specify a gain of 99,
and press Enter.
12-56
Bode Diagram Design
The rise time is around 0.4 seconds, which satisfies the design requirements. However,
the peak overshoot is around 32%. A compensator consisting of a gain and an integrator
is not sufficient to meet the design requirements. Therefore, the compensator requires
additional dynamics.
In the Bode Editor, review the gain margin and phase margin for the current
compensator design. The design requires a gain margin greater than 20 dB and phase
12-57
12 Classical Control Design
margin greater than 40 degrees. The current design does not meet either of these
requirements.
In the Bode Editor, right-click and select Add Pole/Zero > Lead.
To specify the location of the lead network pole, click on the magnitude response. The app
adds a real pole (red X) and real zero (red O) to the compensator and to the Bode Editor
plot.
In the Bode Editor, drag the pole and zero to change their locations. As you drag them,
the app updates the pole/zero values and updates the response plots.
To decrease the magnitude of a pole or zero, drag it towards the left. Since the pole and
zero are on the negative real axis, dragging them to the left moves them closer to the
origin in the complex plane.
12-58
Bode Diagram Design
Tip As you drag a pole or zero, the app displays the new value in the status bar, on the
right side.
As an initial estimate, drag the zero to a location around -7 and the pole to a location
around -11.
12-59
12 Classical Control Design
The phase margin meets the design requirements; however, the gain margin is still too
low.
In the Compensator Editor dialog box, in the Dynamics section, click the Lead row.
12-60
Bode Diagram Design
In the Edit Selected Dynamics section, in the Real Zero text box, specify a location of
-4.3, and press Enter. This value is near the slowest (left-most) pole of the DC motor
plant.
In the Real Pole text box, specify a value of -28, and press Enter.
When you modify a lead network parameters, the Compensator and response plots
update automatically.
In the app, in the Bode Editor, the gain margin of 20.5 just meets the design
requirement.
12-61
12 Classical Control Design
To add robustness to the system, in the Compensator Editor dialog box, decrease the
compensator gain to 84.5, and press Enter. The gain margin increases to 21.8, and the
response plots update.
In Control System Designer, in the response plots, compare the system performance to
the design requirements. The system performance characteristics are:
12-62
See Also
• Overshoot is 3.39%.
• Gain margin is 21.8 dB.
• Phase margin is 65.6 degrees.
See Also
Control System Designer | bodeplot
More About
• “Edit Compensator Dynamics” on page 12-93
• “Control System Designer Tuning Methods” on page 12-4
• “Root Locus Design” on page 12-64
• “Nichols Plot Design” on page 12-80
12-63
12 Classical Control Design
As the open-loop gain, k, of a control system varies over a continuous range of values, the
root locus diagram shows the trajectories of the closed-loop poles of the feedback system.
For example, in the following tracking system:
P(s) is the plant, H(s) is the sensor dynamics, and k is an adjustable scalar gain The
closed-loop poles are the roots of
q ( s) = 1 + kP ( s) H ( s )
The root locus technique consists of plotting the closed-loop pole trajectories in the
complex plane as k varies. You can use this plot to identify the gain value associated with
a desired set of closed-loop poles.
Plant Model
12-64
Root Locus Design
The force on the spool is proportional to the current in the electromagnet coil. As the
spool moves, the valve opens, allowing the high-pressure hydraulic fluid to flow through
the chamber. The moving fluid forces the piston to move in the opposite direction of the
spool. For more information on this model, including the derivation of a linearized model,
see [1].
You can use the input voltage to the electromagnet to control the ram position. When
measurements of the ram position are available, you can use feedback for the ram
position control, as shown in the following, where Gservo represents the
servomechanism:
12-65
12 Classical Control Design
Design Requirements
For this example, tune the compensator, C(s) to meet the following closed-loop step
response requirements:
At the MATLAB command line, load a linearized model of the servomechanism, and open
Control System Designer in the root locus editor configuration.
The app opens and imports Gservo as the plant model for the default control
architecture, Configuration 1.
In Control System Designer, a Root Locus Editor plot and input-output Step
Response open.
To view the open-loop frequency response and closed-loop step response simultaneously,
on the Views tab, click Left/Right.
12-66
Root Locus Design
The app displays Bode Editor and Step Response plots side-by-side.
12-67
12 Classical Control Design
In the closed-loop step response plot, the rise time is around two seconds, which does not
satisfy the design requirements.
To make the root locus diagram easier to read, zoom in. In the Root Locus Editor, right-
click the plot area and select Properties.
In the Property Editor dialog box, on the Limits tab, specify Real Axis and Imaginary
Axis limits from -500 to 500.
12-68
Root Locus Design
Click Close.
To create a faster response, increase the compensator gain. In the Root Locus Editor,
right-click the plot area and select Edit Compensator.
12-69
12 Classical Control Design
In the Root Locus Editor plot, the closed-loop pole locations move to reflect the new
gain value. Also, the Step Response plot updates.
12-70
Root Locus Design
The closed-loop response does not satisfy the settling time requirement and exhibits
unwanted ringing.
Increasing the gain makes the system underdamped and further increases lead to
instability. Therefore, to meet the design requirements, you must specify additional
compensator dynamics. For more information on adding and editing compensator
dynamics, see “Edit Compensator Dynamics” on page 12-93.
12-71
12 Classical Control Design
To add a complex pole pair to the compensator, in the Root Locus Editor, right-click the
plot area and select Add Pole/Zero > Complex Pole. Click the plot area where you want
to add one of the complex poles.
The app adds the complex pole pair to the root locus plot as red X’s, and updates the step
response plot.
In the Root Locus Editor, drag the new poles to locations near –140 ± 260i. As you drag
one pole, the other pole updates automatically.
12-72
Root Locus Design
Tip As you drag a pole or zero, the app displays the new value in the status bar, on the
right side.
12-73
12 Classical Control Design
To add a complex zero pair to your compensator, in the Compensator Editor dialog box,
right-click the Dynamics table, and select Add Pole/Zero > Complex Zero
12-74
Root Locus Design
In the Dynamics table, click the Complex Zero row. Then in the Edit Selected
Dynamics section, specify a Real Part of -170 and an Imaginary Part of 430.
12-75
12 Classical Control Design
The compensator and response plots automatically update to reflect the new zero
locations.
12-76
Root Locus Design
In the Step Response plot, the settling time is around 0.1 seconds, which does not
satisfy the design requirements.
The compensator design process can involve some trial and error. Adjust the compensator
gain, pole locations, and zero locations until you meet the design criteria.
One possible compensator design that satisfies the design requirements is:
12-77
12 Classical Control Design
• Compensator gain of 10
• Complex poles at –110 ± 140i
• Complex zeros at –70 ± 270i
In the Compensator Editor dialog box, configure your compensator using these values. In
the Step Response plot, the settling time is around 0.05 seconds.
To verify the exact settling time, right-click the Step Response plot area and select
Characteristics > Settling Time. A settling time indicator appears on the response plot.
12-78
See Also
To view the settling time, move the cursor over the settling time indicator.
The settling time is about 0.043 seconds, which satisfies the design requirements.
References
[1] Clark, R. N. Control System Dynamics, Cambridge University Press, 1996.
See Also
Control System Designer | rlocusplot
More About
• “Edit Compensator Dynamics” on page 12-93
• “Control System Designer Tuning Methods” on page 12-4
• “Bode Diagram Design” on page 12-49
• “Nichols Plot Design” on page 12-80
12-79
12 Classical Control Design
The transfer function of the DC motor plant, as described in “SISO Example: The DC
Motor”, is:
1.5
G=
2
s + 14 s + 40 .02
At the MATLAB command line, create a transfer function model of the plant, and open
Control System Designer in the Nichols Editor configuration.
G = tf(1.5,[1 14 40.02]);
controlSystemDesigner('nichols',G);
12-80
Nichols Plot Design
The app opens and imports G as the plant model for the default control architecture,
Configuration 1.
• Open-loop Nichols Editor for the LoopTransfer_C response. This response is the
open-loop transfer function GC, where C is the compensator and G is the plant.
• Step Response for the IOTransfer_r2y response. This response is the input-output
transfer function for the overall closed-loop system.
Tip To open the open-loop Nichols Editor when Control System Designer is already
open, on the Control System tab, in the Tuning Methods drop-down list, select Nichols
Editor. In the Select Response to Edit dialog box, select an existing response to plot, or
create a New Open-Loop Response.
To view the open-loop frequency response and closed-loop step response simultaneously,
on the Views tab, click Left/Right.
The app displays the Nichols Editor and Step Response plots side-by-side.
Adjust Bandwidth
Since the design requires a rise time less than 0.5 seconds, set the open-loop DC
crossover frequency to about 3 rad/s. To a first-order approximation, this crossover
frequency corresponds to a time constant of 0.33 seconds.
12-81
12 Classical Control Design
To adjust the crossover frequency increase the compensator gain. In the Nichols Editor,
drag the response upward. Doing so increases the gain of the compensator.
As you drag the Nichols plot, the app computes the compensator gain and updates the
response plots.
Drag the Nichols plot upward until the crossover frequency is about 3 rad/s.
12-82
Nichols Plot Design
To add the rise time to the Step Response plot, right-click the plot area, and select
Characteristics > Rise Time.
To view the rise time, move the cursor over the rise time indicator.
12-83
12 Classical Control Design
The rise time is around 0.23 seconds, which satisfies the design requirements.
Similarly, to add the peak response to the Step Response plot, right-click the plot area,
and select Characteristics > Peak Response.
12-84
Nichols Plot Design
To meet the 5% steady-state error requirement, eliminate steady-state error from the
closed-loop step response by adding an integrator to your compensator. In the Nichols
Editor right-click in the plot area, and select Add Pole/Zero > Integrator.
12-85
12 Classical Control Design
To return the crossover frequency to around 3 rad/s, increase the compensator gain
further. Right-click the Nichols Editor plot area, and select Edit Compensator.
In the Compensator Editor dialog box, in the Compensator section, specify a gain of 99,
and press Enter.
12-86
Nichols Plot Design
The rise time is around 0.4 seconds, which satisfies the design requirements. However,
the peak overshoot is around 32%. A compensator consisting of a gain and an integrator
is not sufficient to meet the design requirements. Therefore, the compensator requires
additional dynamics.
In the Nichols Editor, review the gain margin and phase margin for the current
compensator design. The design requires a gain margin greater than 20 dB and phase
12-87
12 Classical Control Design
margin greater than 40 degrees. The current design does not meet either of these
requirements.
In the Nichols Editor, right-click and select Add Pole/Zero > Lead.
To specify the location of the lead network pole, click on the magnitude response. The app
adds a real pole (red X) and real zero (red O) to the compensator and to the Nichols
Editor plot.
In the Nichols Editor, drag the pole and zero to change their locations. As you drag
them, the app updates the pole/zero values and updates the response plots.
To decrease the magnitude of a pole or zero, drag it towards the left. Since the pole and
zero are on the negative real axis, dragging them to the left moves them closer to the
origin in the complex plane.
Tip As you drag a pole or zero, the app displays the new value in the status bar, on the
right side.
12-88
Nichols Plot Design
As an initial estimate, drag the zero to a location around -7 and the pole to a location
around -11.
The phase margin meets the design requirements; however, the gain margin is still too
low.
In the Compensator Editor dialog box, in the Dynamics section, click the Lead row.
12-89
12 Classical Control Design
In the Edit Selected Dynamics section, in the Real Zero text box, specify a location of
-4.3, and press Enter. This value is near the slowest (left-most) pole of the DC motor
plant.
In the Real Pole text box, specify a value of -28, and press Enter.
When you modify a lead network parameters, the Compensator and response plots
update automatically.
In the app, in the Nichols Editor, the gain margin of 20.5 just meets the design
requirement.
12-90
Nichols Plot Design
To add robustness to the system, in the Compensator Editor dialog box, decrease the
compensator gain to 84.5, and press Enter. The gain margin increases to 21.8, and the
response plots update.
In Control System Designer, in the response plots, compare the system performance to
the design requirements. The system performance characteristics are:
12-91
12 Classical Control Design
• Overshoot is 3.39%.
• Gain margin is 21.8 dB.
• Phase margin is 65.6 degrees.
See Also
Control System Designer | nicholsplot
More About
• “Edit Compensator Dynamics” on page 12-93
• “Control System Designer Tuning Methods” on page 12-4
• “Bode Diagram Design” on page 12-49
• “Root Locus Design” on page 12-64
12-92
Edit Compensator Dynamics
You can add dynamics and modify compensator parameters using the Compensator Editor
or using the graphical Bode Editor, Root Locus Editor, or Nichols Editor plots.
Compensator Editor
To open the Compensator Editor dialog box, in Control System Designer, in an editor
plot area, right-click and select Edit Compensator. Alternatively, in the Data Browser,
in the Controllers section, right-click the compensator you want to edit and click Open
Selection.
12-93
12 Classical Control Design
The Compensator Editor displays the transfer function for the currently selected
compensator. You can select a different compensator to edit using the drop-down list. By
default, the compensator transfer function displays in the time constant format. You can
select a different format by changing the corresponding Control System Designer
preference.
In Control System Designer, on the Control System tab, click Preferences. In the
Control System Designer Preferences dialog box, on the Options tab, select a
Compensator Format.
To add poles and zeros to your compensator, in the Compensator Editor, right-click in the
Dynamics table and, under Add Pole/Zero, select the type of pole/zero you want to add.
12-94
Edit Compensator Dynamics
The app adds a pole or zero of the selected type with default parameters.
To edit a pole or zero, in the Dynamics table, click on the pole/zero type you want to edit.
Then, in the Edit Selected Dynamics section, in the text boxes, specify the pole and zero
locations.
To delete poles and zeros, in the Dynamics table, click on the pole/zero type you want to
delete. Then, right-click and select Delete Pole/Zero.
12-95
12 Classical Control Design
To add poles and zeros directly from an editor plot, right-click the plot area and, under
Add Pole/Zero, select the type of pole/zero you want to add. In the editor plot, the app
displays the editable compensator poles and zeros as red X’s and O’s respectively.
In the editor plots, you can drag poles and zeros to adjust their locations. As you drag a
pole or zero, the app displays the new value in the status bar, on the right side.
To delete a pole or zero, right-click the plot area and select Delete Pole/Zero. Then, in
the editor plot, click the pole or zero you want to delete.
12-96
Edit Compensator Dynamics
To configure a lead or lag network for your compensator, use one of the following options:
• Specify the pole and zero locations. Placing the pole and zero further apart increases
the amount of phase angle change.
12-97
12 Classical Control Design
• Specify the maximum amount of phase angle change and the frequency at which this
change occurs. The app automatically computes the pole and zero locations.
When graphically changing pole and zero locations for a lead or lag compensator, in the
editor plot, you can drag the pole and zeros independently.
Notch Filters
If you know that your system has disturbances at a particular frequency, you can add a
notch filter to attenuate the gain of the system at that frequency. The notch filter transfer
function is:
s2 + 2x1wn s + wn2
s2 + 2x2wn s + wn2
where
To configure a notch filter for your compensator, in the Compensator Editor dialog box,
you can specify the:
When graphically editing a notch filter, in the Bode Editor, you can drag the bottom of the
notch to adjust ωn and the notch depth. To adjust the width of the notch without changing
ωn or the notch depth, you can drag the edges of the notch.
12-98
See Also
See Also
Control System Designer
More About
• “Bode Diagram Design” on page 12-49
• “Root Locus Design” on page 12-64
• “Nichols Plot Design” on page 12-80
12-99
12 Classical Control Design
12-100
Design Compensator Using Automated Tuning Methods
• PID Tuning — Tune PID gains to balance performance and robustness or use
classical tuning formulas.
• Optimization Based Tuning — Optimize compensator parameters using design
requirements implemented in graphical tuning and analysis plots (requires Simulink
Design Optimization software).
• LQG Synthesis — Design a full-order stabilizing feedback controller as a linear-
quadratic-Gaussian (LQG) tracker.
• Loop Shaping — Find a full-order stabilizing feedback controller with a specified
open-loop bandwidth or shape (requires Robust Control Toolbox software).
• Internal Model Control (IMC) Tuning — Obtain a full-order stabilizing
feedback controller using the IMC design method.
• Compensator — Select a compensator to tune from the drop-down list. The app
displays the current compensator transfer function.
• Select Loop to Tune — Select an existing open-loop transfer function to tune from
the drop-down list. You can select any open-loop transfer function from the Data
Browser that includes the selected compensator in series
• Add New Loop — Create a new loop to tune. In the Open-Loop Transfer Function
dialog box, select signals and loop openings to configure the loop transfer function.
12-101
12 Classical Control Design
Note For optimization-based tuning, you do not specify the compensator and loop to tune
in this way. Instead, you define the compensator structure and select compensator and
prefilter parameters to optimize. For more information, see “Select Tunable Compensator
Elements” (Simulink Design Optimization).
PID Tuning
Using Control System Designer, you can automatically tune any of the following PID
controller types:
• P — Proportional-only control
• I — Integral-only control
• PI — Proportional-integral control
• PD — Proportional-derivative control
• PDF — Proportional-derivative control with a low-pass filter on the derivative term
• PID — Proportional-integral-derivative control
• PIDF — Proportional-integral-derivative control with a low-pass filter on the derivative
term
To open the PID Tuning dialog box, in Control System Designer, click Tuning
Methods, and select PID Tuning.
12-102
Design Compensator Using Automated Tuning Methods
The robust response time algorithm automatically tunes PID parameters to balance
performance and robustness. Using the robust response time method, you can:
12-103
12 Classical Control Design
2 Select a Controller type. If you choose PD or PID, check Design with first order
derivative filter to design a PDF or PIDF controller, respectively.
Tip Adding derivative action to the controller gives the algorithm more freedom to
achieve both adequate phase margin and faster response time.
3 In the Design mode drop-down list, select one of the following:
12-104
Design Compensator Using Automated Tuning Methods
12-105
12 Classical Control Design
You can use classical PID design formulas to tune P, PI, PID, and PIDF controllers. These
design formulas:
• Require a stable or integrating plant. For more information about the effective plant
seen by the compensator, see “Effective Plant for Tuning” on page 12-6.
12-106
Design Compensator Using Automated Tuning Methods
• Cannot tune the derivative filter. If you select a PIDF controller, the classical design
methods set the filter time constant to Td/10, where Td is the tuned derivative time.
1 In the PID Tuning dialog box, in the Specifications section, in the Tuning method
drop-down list, select Classical design formulas.
Tip Adding derivative action to the compensator gives the algorithm more freedom
to achieve both adequate phase margin and faster response time.
3 In the Formula drop-down list, select a classical design formula.
12-107
12 Classical Control Design
Note This method is different from selecting “Internal Model Control Tuning” on
page 12-113 as the full-order compensator tuning method.
• Ziegler-Nichols frequency response — Compute controller parameters
from a Ziegler-Nichols lookup table, based on the ultimate gain and frequency of
the system (see [2]).
• Ziegler-Nichols step response — Approximate the plant as a first-order
model with a time delay, and compute PID parameters using the Ziegler-Nichols
design method (see [2]).
4 Apply the specified controller design to the selected compensator. Click Update
Compensator.
Optimization-Based Tuning
Optimization-based tuning is available only if you have Simulink Design Optimization
software installed. You can use this method to design control systems for LTI models by
optimizing controller parameters.
Note Optimization-based tuning only changes the values of controller parameters and
not the controller structure itself. For information on adding or removing compensator
elements, see “Edit Compensator Dynamics” on page 12-93.
12-108
Design Compensator Using Automated Tuning Methods
1 Define the structure of the compensators you want to tune. Typically, you design an
initial controller either manually or using a different automated tuning method.
2 Open the Response Optimization dialog box. In Control System Designer, click
Tuning Methods, and select Optimization-Based Tuning.
3 Select compensator parameters to optimize. On the Compensators tab, in the
Optimize column, select the compensator elements to tune.
You can optimize elements for any compensator listed in the Data Browser. To select
all elements for a given compensator, select the check box that corresponds to that
compensator.
Any elements that you do not select in the Optimize column remain at their current
values during optimization.
4 For each compensator element, specify:
• Initial guess — Starting point for the optimization algorithm. To use the current
element Value as the Initial guess, click a row in the table, and click Use Value
as Initial guess.
• Minimum and Maximum bounds on the element value. The optimization
constrains the search results to the specified range.
• Typical value scaling factor for normalizing the compensator elements.
12-109
12 Classical Control Design
5 On the Design Requirements tab, in the Optimize column, select the design
requirements to satisfy during optimization.
Each design requirement is associated with a plot of a specific response in the Data
Browser. To select all requirements for a given response, select the corresponding
check box.
For examples of optimization-based tuning, see “Optimize LTI System to Meet Frequency-
Domain Requirements” (Simulink Design Optimization) and “Design Optimization-Based
PID Controller for Linearized Simulink Model (GUI)” (Simulink Design Optimization).
LQG Synthesis
Linear-quadratic-Gaussian (LQG) control is a technique for designing optimal dynamic
regulators and setpoint trackers. This technique allows you to trade off performance and
control effort, and to take into account process disturbances and measurement noise.
12-110
Design Compensator Using Automated Tuning Methods
1 Open the LQG Synthesis dialog box. In Control System Designer, click Tuning
Methods, and select LQG Synthesis.
2 Specify the transient behavior of the controller using the Controller response slider.
You can make the controller more aggressive at disturbance rejection or more robust
against plant uncertainty. If you believe your model is accurate and that the
manipulated variable has a large enough range, an aggressive controller is
preferable.
3 Specify an estimate of the level of output measurement noise for your application
using the Measurement noise slider. To produce a more robust controller, specify a
larger noise estimate.
4 Specify your controller order preference using the Desired controller order slider.
The maximum controller order is dependent on the effective plant dynamics.
5 Apply the specified controller design to the selected compensator. Click Update
Compensator.
12-111
12 Classical Control Design
For an example of LQG synthesis using Control System Designer, see “Design LQG
Tracker Using Control System Designer” on page 12-176.
Loop Shaping
If you have Robust Control Toolbox software installed, you can use loop shaping to design
SISO compensators in Control System Designer. Loop shaping generates a stabilizing
feedback controller to match, as closely as possible, a target loop shape. You can specify
this loop shape as a bandwidth or an open-loop frequency response.
1 Open the Loop Shaping dialog box. In Control System Designer, click Tuning
Methods, and select Loop Shaping.
2 Select one of the following tuning preferences:
•
Target bandwidth — Specify a Target open-loop bandwidth, wb , to produce a
wb
loop shape of the specified bandwidth over an integrator, .
s
• Target loop shape — Specify the Target open-loop shape as a tf, ss, or zpk
object. To limit the frequencies over which to match the target loop shape, specify
the Frequency range for loop shaping as a two-element row vector.
3 Specify your controller order preference using the Desired controller order slider.
The maximum controller order is dependent on the effective plant dynamics.
4 Apply the specified controller design to the selected compensator. Click Update
Compensator.
12-112
Design Compensator Using Automated Tuning Methods
1 Select and configure the IMC control architecture. In Control System Designer,
click Edit Architecture.
In the Edit Architecture dialog box, select the fifth control architecture, and import
the plant model, G1, predictive model, G2, and disturbance model Gd.
12-113
12 Classical Control Design
Click OK.
2 Open the Internal Model Control (IMC) Tuning dialog box. In Control System
Designer, click Tuning Methods, and select Internal Model Control (IMC)
Tuning.
12-114
Design Compensator Using Automated Tuning Methods
For an example of IMC tuning, see “Design Internal Model Controller for Chemical
Reactor Plant” on page 12-161.
12-115
12 Classical Control Design
References
[1] Åström, K. J. and Hägglund, T. “Replacing the Ziegler-Nichols Tuning Rules.” Chapter
7 in Advanced PID Control, Research Triangle Park, NC: Instrumentation,
Systems, and Automation Society, 2006, pp. 233–270.
[2] Åström, K. J. and Hägglund, T. “Ziegler-Nichols' and Related Methods.” Section 6.2 in
Advanced PID Control, Research Triangle Park, NC: Instrumentation, Systems,
and Automation Society, 2006, pp. 167–176.
[3] Skogestad, S., “Simple analytic rules for model reduction and PID controller tuning.”
Journal of Process Control, Vol. 13, No. 4, 2003, pp. 291–309.
See Also
Control System Designer
More About
• “Control System Designer Tuning Methods” on page 12-4
• “Design Internal Model Controller for Chemical Reactor Plant” on page 12-161
• “Design LQG Tracker Using Control System Designer” on page 12-176
12-116
Analyze Designs Using Response Plots
• Analysis plots — Use these plots to visualize your system performance and display
response characteristics.
• Editor plots — Use these plots to visualize your system performance and interactively
tune your compensator dynamics using graphical tuning methods.
Analysis Plots
Use analysis plots to visualize your system performance and display response
characteristics. You can also use these plots to compare multiple control system designs.
For more information, see “Compare Performance of Multiple Designs” on page 12-127.
To create a new analysis plot, in Control System Designer, on the Control System tab,
click New Plot, and select the type of plot to add.
12-117
12 Classical Control Design
In the new plot dialog box, specify an existing or new response to plot.
12-118
Analyze Designs Using Response Plots
Note Using analysis plots, you can compare the performance of multiple designs stored
in the Data Browser. For more information, see “Compare Performance of Multiple
Designs” on page 12-127.
To plot an existing response, in the Select Response to Plot drop-down list, select an
existing response from the Data Browser. The details for the selected response are
displayed in the text box.
• MATLAB — Select a signal using the Architecture block diagram for reference.
• Simulink — Select an existing signal from the current control system architecture,
or add a signal from the Simulink model.
To add the specified response to the Data Browser and create the selected plot, click
Plot.
12-119
12 Classical Control Design
Editor Plots
Use editor plots to visualize your system performance and interactively tune your
compensator dynamics using graphical tuning methods.
To create a new editor plot, in Control System Designer, on the Control System tab,
click Tuning Methods, and select one of the Graphical Tuning methods.
12-120
Analyze Designs Using Response Plots
Plot Characteristics
On any analysis plot in Control System Designer:
• To see response information and data values, click a line on the plot.
12-121
12 Classical Control Design
Plot Tools
Mouse over any analysis plot to access plot tools at the upper right corner of the plot.
12-122
Analyze Designs Using Response Plots
•
and — Zoom in and zoom out. Click to activate, and drag the cursor over the
region to zoom. The zoom icon turns dark when zoom is active. Right-click while zoom
is active to access additional zoom options. Click the icon again to deactivate.
•
— Pan. Click to activate, and drag the cursor across the plot area to pan. The pan
icon turns dark when pan is active. Right-click while pan is active to access additional
pan options. Click the icon again to deactivate.
12-123
12 Classical Control Design
•
— Legend. By default, the plot legend is inactive. To toggle the legend on and off,
click this icon. To move the legend, drag it to a new location on the plot.
To change the way plots are tiled or sorted, use the options on the View tab.
Design Requirements
You can add graphical representations of design requirements to any editor or analysis
plots. These requirements define shaded exclusion regions in the plot area.
12-124
Analyze Designs Using Response Plots
Use these regions as guidelines when analyzing and tuning your compensator designs. To
meet a design requirement, your response plots must remain outside of the
corresponding shaded area.
To add design requirements to a plot, right-click anywhere on the plot and select Design
Requirements > New.
12-125
12 Classical Control Design
In the New Design Requirement dialog box, specify the Design requirement type, and
define the Design requirement parameters. Each type of design requirement has a
different set of parameters to configure. For more information on adding design
requirements to analysis and editor plots, see “Design Requirements” on page 12-9.
See Also
More About
• “Control System Designer Tuning Methods” on page 12-4
• “Compare Performance of Multiple Designs” on page 12-127
• “Design Requirements” on page 12-9
12-126
Compare Performance of Multiple Designs
In this example, the first design is the compensator tuned graphically in “Bode Diagram
Design” on page 12-49.
After tuning the compensator with this first tuning method, store the design in Control
System Designer.
On the Control System tab, in the Designs section, click Store. The stored design
appears in the Data Browser in the Designs area.
12-127
12 Classical Control Design
The stored design contains the tuned values of the controller and filter blocks. The app
does not store the values of any fixed blocks.
To rename the stored design, in the Data Browser, double-click the design, and specify a
new name.
On the Control System tab, tune the compensator using a different tuning method.
12-128
Compare Performance of Multiple Designs
To design a controller with the default Robust response time specifications, in the
PID Tuning dialog box, click Update Compensator.
Update all plots to reflect both the new design and the stored design.
In the Compare Designs dialog box, the current design is checked by default. To
compare a design with the current design, check the corresponding box. All analysis plots
update to reflect the checked designs. The blue trace corresponds to the current design.
Refer to the plot legend to identify the responses for other designs.
12-129
12 Classical Control Design
To compare a stored design with the current design, the sample times of the current
design and stored design must be the same. To modify the sample time of the current
design to match that of a stored design, on the Control System tab, select Edit
Architecture > Sample Time Conversion. Then, in the Sample Time Conversion dialog
box, specify the sample time and a rate conversion methods for each block in the
architecture.
12-130
Compare Performance of Multiple Designs
Under some conditions, it is useful to restore a previously stored design. For example,
when designing a compensator for a Simulink model, you can write the current
compensator values to the model (see “Update Simulink Model and Validate Design”
(Simulink Control Design)). To test a stored compensator in your model, first restore the
stored design as the current design.
To do so, in Control System Designer, click Retrieve. Select the stored design that
you want to make current.
As with design comparison, to retrieve a stored design, the sample times of the current
design and stored design must be the same.
12-131
12 Classical Control Design
Note The retrieved design overwrites the current design. If necessary, store the current
design before retrieving a previously stored design.
See Also
More About
• “Analyze Designs Using Response Plots” on page 12-117
• “Control System Designer Tuning Methods” on page 12-4
12-132
Design Hard-Disk Read/Write Head Controller
Using Newton's laws, model the read/write head using the following differential equation:
Here,
12-133
12 Classical Control Design
J = 0.01;
C = 0.004;
K = 10;
Ki = 0.05;
num = Ki;
den = [J C K];
H = tf(num,den)
H =
0.05
-----------------------
0.01 s^2 + 0.004 s + 10
To design a digital controller that provides accurate positioning of the read/write head,
first discretize the continuous-time plant.
Ts = 0.005;
12-134
Design Hard-Disk Read/Write Head Controller
Discretize the model. Since the controller will have a digital-to-analog converter (with a
zero-order hold) connected to its input, use the c2d command with the 'zoh'
discretization method.
Hd = c2d(H,Ts,'zoh')
Hd =
6.233e-05 z + 6.229e-05
-----------------------
z^2 - 1.973 z + 0.998
bodeplot(H,'-',Hd,'--')
legend('Continuous-time','Discrete-time')
12-135
12 Classical Control Design
stepplot(Hd)
12-136
Design Hard-Disk Read/Write Head Controller
The step response has significant oscillation, which is most likely due to light damping.
Check the damping for the open-loop poles of the system.
damp(Hd)
As expected, the poles have light equivalent damping and are near the unit circle.
Therefore, you must design a compensator that increases the damping in the system.
12-137
12 Classical Control Design
The simplest compensator is a gain factor with no poles or zeros. Try to select an
appropriate feedback gain using the root locus technique. The root locus plots the closed-
loop pole trajectories as a function of the feedback gain.
rlocus(Hd)
The poles quickly leave the unit circle and go unstable. Therefore, you must introduce
some lead to the system.
12-138
Design Hard-Disk Read/Write Head Controller
D = zpk(0.85,0,1,Ts);
The corresponding open-loop model is the series connection of the compensator and
plant.
oloop = Hd*D
oloop =
To see how the lead compensator affects the open-loop frequency response, compare the
Bode plots of Hd and oloop.
bodeplot(Hd,'--',oloop,'-')
legend('Plant','Plant plus lead compensator')
12-139
12 Classical Control Design
The compensator adds lead to the system, which shifts the phase response upward in the
frequency range .
Examine the behavior of the closed-loop system poles using a root locus plot. Set the
limits of both the x-axis and y-axis from -1 to 1.
rlocus(oloop)
zgrid
xlim([-1 1])
ylim([-1 1])
12-140
Design Hard-Disk Read/Write Head Controller
The closed-loop poles now remain within the unit circle for some time.
To create a data marker for the plot, click the root locus curve. Find the point on the
curve where the damping is greatest by dragging the marker. The maximum damping of
0.782 corresponds to a feedback gain of 4.07e+03.
12-141
12 Classical Control Design
Analyze Design
To analyze this design, first define the closed-loop system, which consists of the open-loop
system with a feedback gain of 4.07e+03.
12-142
Design Hard-Disk Read/Write Head Controller
k = 4.07e+03;
cloop = feedback(oloop,k);
stepplot(cloop)
12-143
12 Classical Control Design
This response depends on your closed-loop setpoint. The one shown here is relatively fast
and settles in about 0.06 seconds. Therefore, the closed-loop disk drive system has a seek
time of 0.06 seconds. While this seek time is relatively slow by modern standards, you
also started with a lightly-damped system.
It is good practice to examine the robustness of your design. To do so, compute the gain
and phase margins for your system. First, form the unity feedback open-loop system by
connecting the compensator, plant, and feedback gain in series.
olk = k*oloop;
12-144
Design Hard-Disk Read/Write Head Controller
Gm =
3.8360
Pm =
43.3068
Wcg =
296.7978
Wcp =
105.4680
This command returns the gain margin, Gm, the phase margin Pm, and their respective
cross-over frequencies, Wcg and Wcp.
20*log10(Gm)
ans =
11.6775
margin(olk)
12-145
12 Classical Control Design
This design is robust and can tolerate an 11-dB gain increase or a 40-degree phase lag in
the open-loop system without going unstable. By continuing this design process, you may
be able to find a compensator that stabilizes the open-loop system and reduces the seek
time further.
See Also
bodeplot | feedback | margin | rlocus
12-146
Design Compensator for Plant Model with Time Delays
When working with time delay systems it is advantageous to work with analysis and
design tools that directly support time delays so that performance and stability can be
evaluated exactly. However, many control design techniques and algorithms cannot
directly handle time delays. A common workaround consists of replacing delays by their
Pade approximations (all-pass filters). Because this approximation is only valid at low
frequencies, it is important to choose the right approximation order and check the
approximation validity.
Control System Designer provides a variety of design and analysis tools. Some of these
tools support time delays exactly while others support time delays indirectly through
approximations. Use these tools to design compensators for your control system and
visualize the compromises made when using approximations.
Plant Model
For this example, which uses a unity feedback configuration, the plant model has a time
delay:
G = tf(1,[1,1],'InputDelay',0.5);
12-147
12 Classical Control Design
Open Control System Designer, importing the plant model and using a Bode editor
configuration.
controlSystemDesigner({'bode'},G)
12-148
Design Compensator for Plant Model with Time Delays
The phase response of the Bode plot shows the roll-off effect from the exact
representation of the delay. The beginning of the step response shows an exact
representation of the 0.5 second delay.
Open a Nyquist plot of the open-loop response. In the Data Browser, right-click
LoopTransfer_C, and select Plot > nyquist.
The Nyquist response wrapping around the origin in a spiral fashion is the result of the
exact representation of the time delay.
12-149
12 Classical Control Design
When using approximations, the results are not exact and depend on the validity of the
approximation. Each tool in Control System Designer provides a warning pane to indicate
when time-delays are approximated.
Open a root locus editor plot for the open-loop response. Click Tuning Methods, and
select Root Locus Editor. In the Select Response to Edit dialog box, click Plot.
12-150
Design Compensator for Plant Model with Time Delays
The Root Locus Editor shows a notification that the plot is using a time delay
approximation. This notification can be minimized by clicking on the arrow icon to the
left.
12-151
12 Classical Control Design
To change the approximation settings, click the hyperlink in the notification. In the
Control System Designer Preferences dialog box, on the Time Delays tab, specify a Pade
order of 4. Alternatively, you can set the bandwidth over which you want the
approximation to be accurate.
12-152
Design Compensator for Plant Model with Time Delays
The higher-order Pade approximation adds poles and zeros to the root locus plot.
12-153
12 Classical Control Design
See Also
Control System Designer
12-154
Design Compensator for Systems Represented by Frequency Response Data
2) Non-parametric estimation techniques using the systems time response data. You can
use the following products to estimate FRD models:
• Function: frestimate
• Example: “Frequency Response Estimation Using Simulation-Based Techniques”
(Simulink Control Design).
• Function: tfestimate.
In this example, design an engine speed controller that actuates the engine throttle angle:
12-155
12 Classical Control Design
The frequency response of the engine is already estimated. Load and view the data.
load FRDPlantDemoData.mat
AnalyzerData
AnalyzerData =
FRDPlant = frd(AnalyzerData.Response,AnalyzerData.Frequency,...
'Unit',AnalyzerData.FrequencyUnits);
Design Compensator
controlSystemDesigner({'bode','nichols'},FRDPlant)|
The Control System Designer opens with both Bode and Nichols open-loop editors.
12-156
Design Compensator for Systems Represented by Frequency Response Data
You can design the compensator by shaping the open-loop frequency response in either
the Bode editor or Nichols editor. In these editors, interactively modify the gain, poles,
and zeros of the compensator.
To satisfy the tracking requirement of zero steady-state error, add an integrator to the
compensator. Right-click the Bode editor plot area, and select Add Pole/Zero >
Integrator.
To meet the gain and phase margin requirements, add a zero to the compensator. Right-
click the Bode editor plot area, and select Add Pole/Zero > Real Zero. Modify the
12-157
12 Classical Control Design
location of the zero and the gain of the compensator until you satisfy the margin
requirements.
This compensator design, which is a PI controller, achieves a 20.7 dB gain margin and a
70.8 degree phase margin.
12-158
Design Compensator for Systems Represented by Frequency Response Data
Validate the controller performance by simulating the engine response using a nonlinear
model in Simulink®. For this example, the validation simulation results are in
EngineStepResponse.
Plot the response of the engine to a reference speed change from 2000 to 2500 RPM:
plot(EngineStepResponse.Time,EngineStepResponse.Speed)
title('Engine Step Response')
xlabel('Time (s)')
ylabel('Engine Speed (RPM)')
12-159
12 Classical Control Design
The response shows zero steady-state error and well-behaved transients with the
following metrics.
stepinfo(EngineStepResponse.Speed,EngineStepResponse.Time)
ans =
RiseTime: 1.1048
SettlingTime: 1.7194
SettlingMin: 2.4501e+03
SettlingMax: 2.5078e+03
Overshoot: 0.3127
Undershoot: 0
Peak: 2.5078e+03
PeakTime: 2.3853
See Also
Control System Designer
12-160
Design Internal Model Controller for Chemical Reactor Plant
Plant Model
The plant for this example is a chemical reactor system, comprised of two well-mixed
tanks.
The reactors are isothermal and the reaction in each reactor is first order on component
A:
12-161
12 Classical Control Design
Material balance is applied to the system to generate a dynamic model of the system. The
tank levels are assumed to stay constant because of the overflow nozzle and hence there
is no level control involved.
For details about this plant, see Example 3.3 in Chapter 3 of "Process Control: Design
Processes and Control Systems for Dynamic Performance" by Thomas E. Marlin.
At steady state,
12-162
Design Internal Model Controller for Chemical Reactor Plant
where
For this example, design a controller to maintain the outlet concentration of reactant from
the second reactor, , in the presence of any disturbance in feed concentration, .
The manipulated variable is the molar flowrate of the reactant, F, entering the first
reactor.
This chemical process can be represented using the following block diagram:
12-163
12 Classical Control Design
where
12-164
Design Internal Model Controller for Chemical Reactor Plant
Based on the block diagram, obtain the plant and disturbance models as follows:
s = tf('s');
G1 = (13.3259*s+3.2239)/(8.2677*s+1)^2;
G2 = G1;
Gd = 0.4480/(8.2677*s+1)^2;
G1 is the real plant used in controller evaluation. G2 is an approximation of the real plant
and it is used as the predictive model in the IMC structure. G2 = G1 means that there is
no model mismatch. Gd is the disturbance model.
controlSystemDesigner
12-165
12 Classical Control Design
Select the IMC control architecture. In Control System Designer, click Edit
Architecture. In the Edit Architecture dialog box, select Configuration 5.
12-166
Design Internal Model Controller for Chemical Reactor Plant
Load the system data. For G1, G2, and Gd, specify a model Value.
12-167
12 Classical Control Design
Tune Compensator
step(G1)
12-168
Design Internal Model Controller for Chemical Reactor Plant
Right-click the plot and select Characteristics > Rise Time submenu. Click the blue rise
time marker.
12-169
12 Classical Control Design
The rise time is about 25 seconds and we want to tune the IMC compensator to achieve a
faster closed-loop response time.
To tune the IMC compensator, in Control System Designer, click Tuning Methods, and
select Internal Model Control (IMC) Tuning.
12-170
Design Internal Model Controller for Chemical Reactor Plant
To view the closed-loop step response, in Control System Designer, double-click the
IOTransfer_r2y:step plot tab.
12-171
12 Classical Control Design
When designing the controller, we assumed G1 was equal to G2. In practice, they are
often different, and the controller needs to be robust enough to track setpoints and reject
disturbances.
Create model mismatches between G1 and G2 and examine the control performance at
the MATLAB command line in the presence of both setpoint change and load disturbance.
Export the IMC Compensator to the MATLAB workspace. Click Export. In the Export
Model dialog box, select compensator model C.
12-172
Design Internal Model Controller for Chemical Reactor Plant
Click Export.
Convert the IMC structure to a classic feedback control structure with the controller in
the feedforward path and unit feedback.
C_new =
2.39 (s+0.121)^4
---------------------------------------------
(s-0.0001594) (s+0.121) (s+0.1213) (s+0.2419)
• No Model Mismatch:
G1p = (13.3259*s+3.2239)/(8.2677*s+1)^2;
12-173
12 Classical Control Design
G1t = (13.3259*s+3.2239)/(8.7*s+1)^2;
G1g = 3*(13.3259*s+3.2239)/(8.2677*s+1)^2;
step(feedback(G1p*C_new,1),feedback(G1t*C_new,1),feedback(G1g*C_new,1))
legend('No Model Mismatch','Mismatch in Time Constant','Mismatch in Gain')
12-174
See Also
step(Gd*feedback(1,G1p*C_new),Gd*feedback(1,G1t*C_new),Gd*feedback(1,G1g*C_new))
legend('No Model Mismatch','Mismatch in Time Constant','Mismatch in Gain')
See Also
Control System Designer
More About
• “Design Compensator Using Automated Tuning Methods” on page 12-100
12-175
12 Classical Control Design
For details about the system and model, see Chapter 14 of "Digital Control of Dynamic
Systems," by Franklin, Powell, and Workman.
12-176
Design LQG Tracker Using Control System Designer
The model input is the current driving the voice coil motor, and the output is the position
error signal (PES, in % of track width). To learn more about the 10th order model, see
“Digital Servo Control of a Hard-Disk Drive”. The plant includes a small time delay. For
the purpose of this example, ignore this delay.
load diskdemo
Gr = tf(1e6,[1 12.5 0]);
Gf1 = tf(w1*[a1 b1*w1],[1 2*z1*w1 w1^2]); % first resonance
Gf2 = tf(w2*[a2 b2*w2],[1 2*z2*w2 w2^2]); % second resonance
Gf3 = tf(w3*[a3 b3*w3],[1 2*z3*w3 w3^2]); % third resonance
Gf4 = tf(w4*[a4 b4*w4],[1 2*z4*w4 w4^2]); % fourth resonance
G = (ss(Gf1)+Gf2+Gf3+Gf4) * Gr; % convert to state space for accuracy
Design Overview
In this example, design a full-ordered LQG tracker, which places the read/write head at
the correct position. Tune the LQG tracker to achieve specific performance requirements
and reduce the controller order as much as possible. For example, turn the LQG tracker
into a PI controller format.
controlSystemDesigner(G)
By default, Control System Designer displays the step response of the closed-loop system
along with Bode and root locus graphical editors for the open-loop response.
Maximize the step response. Double-click the IOTransfer_r2y: step plot tab. Details
about how to use the Control System Designer are described in “Getting Started with the
Control System Designer”.
12-177
12 Classical Control Design
The default unity gain compensator produces a stable closed-loop system with large
oscillations.
12-178
Design LQG Tracker Using Control System Designer
In the LQG Synthesis dialog box, in the Specifications section, set requirements on the
controller performance:
• Controller response - Specify the controller transient behavior. You can make the
controller more aggressive at disturbance rejection or more robust against plant
uncertainty. If you believe your model is accurate and that the manipulated variable
has a large enough range, an aggressive controller is preferable.
• Measurement noise - Specify an estimate of the level of output measurement noise
for your application. To produce a more robust controller, specify a larger noise
estimate.
12-179
12 Classical Control Design
Click Update Compensator. The new Compensator is displayed, and the step response
updates.
12-180
Design LQG Tracker Using Control System Designer
To design a more aggressive controller, move the Controller response slider to the far
left. The more aggressive controller reduces the overshoot by 50% and reduces the
settling time by 70%.
12-181
12 Classical Control Design
To create a PI controller, reset the Controller response slider to the middle default
value, and set the Desired controller order to 1.
12-182
Design LQG Tracker Using Control System Designer
12-183
12 Classical Control Design
This controller produces a heavily oscillating closed-loop system. To make the controller
less aggressive, move the Controller response slider to the right.
12-184
Design LQG Tracker Using Control System Designer
12-185
12 Classical Control Design
The step response shows that the PI controller design provides a good starting point for
optimization-based design. For more information, see “Getting Started with the Control
System Designer”.
See Also
Control System Designer
12-186
See Also
More About
• “Design Compensator Using Automated Tuning Methods” on page 12-100
12-187
12 Classical Control Design
1 In Control System Designer, on the Control System tab, under Export, click
Export tuned blocks.
2 In the Export Model dialog box, in the Select Design drop-down list, choose the
design that you want to export. You can select either the Current Design or one of
the stored designs from the Data Browser.
12-188
See Also
3 In the Export models to MATLAB Workspace table, in the Export column, select
the models you want to export.
For all designs, you can export the controller and prefilter models. Also, for the
Current Design, you can export the fixed block models and any responses from the
Data Browser.
For more information on the prefilter, controller, and fixed blocks in each control
architecture, see “Feedback Control Architectures” on page 12-21.
4 In the Export as column, you can specify an alternate name for the exported model.
Exporting a model with the same name as an existing variable in the MATLAB
Workspace overwrites the variable.
5 To save the selected models to the MATLAB Workspace, click Export.
See Also
Apps
Control System Designer
12-189
12 Classical Control Design
More About
• “Feedback Control Architectures” on page 12-21
• “Generate Simulink Model for Control Architecture” on page 12-191
12-190
Generate Simulink Model for Control Architecture
To do so, on the Control System tab, under Export, click Create Simulink model.
The app exports the controllers and fixed blocks for the current design to the MATLAB
Workspace and generates a Simulink model that matches the current control
architecture. For more information on the controllers and fixed blocks in each control
architecture, see “Feedback Control Architectures” on page 12-21.
For example, if you design a control system using configuration 1, Control System
Designer exports C, F, G, and H to the MATLAB Workspace and generates the following
Simulink model.
12-191
12 Classical Control Design
In the generated model, the Input block is a Signal Generator. Using this block, you
simulate your model with different input waveforms, such as sine waves or random
signals. To generate a step response, replace the Input block with a Step block.
To generate a Simulink model for a stored design, first make that design current. On the
Control System tab, under Retrieve, select the design for which you want to generate a
model.
See Also
Control System Designer
More About
• “Feedback Control Architectures” on page 12-21
• “Export Design to MATLAB Workspace” on page 12-188
12-192
13
• “Extended and Unscented Kalman Filter Algorithms for Online State Estimation”
on page 13-2
• “Generate Code for Online State Estimation in MATLAB” on page 13-11
• “Validate Online State Estimation at the Command Line” on page 13-15
• “Validate Online State Estimation in Simulink” on page 13-18
• “Troubleshoot Online State Estimation” on page 13-22
• “Nonlinear State Estimation Using Unscented Kalman Filter and Particle Filter”
on page 13-24
• “Estimate States of Nonlinear System with Multiple, Multirate Sensors”
on page 13-45
13 State-Space Control Design
At the command line, you use the functions to construct the extendedKalmanFilter or
unscentedKalmanFilter object for desired algorithm, and specify whether the process
and measurement noise terms in the functions are additive or nonadditive. After you
create the object, you use the predict and correct commands to estimate the states
using real-time data. For information about the order in which to execute these
commands, see the predict and correct reference pages.
In Simulink, you specify these function in the Extended Kalman Filter and Unscented
Kalman Filter blocks. You also specify whether the process and measurement noise terms
in the functions are additive or nonadditive. In the blocks, the software decides the order
in which prediction and correction of state estimates is done.
x[ k + 1] = f ( x[ k ], w[ k],us[ k ])
y[ k ] = h( x[ k], v[ k],um [ k])
w[ k] ~ (0, Q[ k ])
v[ k] ~ ( 0, R[ k])
Here f is a nonlinear state transition function that describes the evolution of states x from
one time step to the next. The nonlinear measurement function h relates x to the
measurements y at time step k. These functions can also have additional input arguments
that are denoted by us and um. The process and measurement noise are w and v,
respectively. You provide Q and R.
13-2
Extended and Unscented Kalman Filter Algorithms for Online State Estimation
In the block, the software decides the order of prediction and correction of state
estimates. At the command line, you decide the order. For information about the order in
which to execute these commands, see the predict and correct reference pages.
Assuming that you implement the correct command before predict, the software
implements the algorithm as follows:
1 Initialize the filter object with initial values of the state, x[0], and state estimation
error covariance, P.
xˆ [0 | -1 ] = E( x[ 0])
P[ 0 | -1] = E( x[0 ] - xˆ[ 0 | -1])( x[0 ] - xˆ [0 | -1])T
Here x̂ is the state estimate and xˆ [ ka | kb ] denotes the state estimate at time step ka
using measurements at time steps 0,1,...,kb. So xˆ [0 | -1 ] is the best guess of the
state value before you make any measurements. You specify this value when you
construct the filter.
2 For time steps k = 0,1,2,3,..., perform the following:
a Compute the Jacobians of the measurement function, and update the state and
state estimation error covariance using the measured data, y[k]. At the
command line, the correct command performs this update.
∂h
C[ k] =
∂x x[ k|k-1]
∂h
S[ k] =
∂v x[ k|k-1]
The software calculates these Jacobian matrices numerically unless you specify
the analytical Jacobian.
13-3
13 State-Space Control Design
b Compute the Jacobians of the state transition function, and predict the state and
state estimation error covariance at the next time step. In the software, the
predict command performs this prediction.
∂f
A[ k ] =
∂x x[ k|k]
∂f
G[ k] =
∂ w x[ k|k]
The software calculates these Jacobian matrices numerically unless you specify
the analytical Jacobian. This numerical computation may increase processing
time and numerical inaccuracy of the state estimation.
These values are used by the correct command in the next time step.
The Extended Kalman Filter block supports multiple measurement functions. These
measurements can have different sample times as long as their sample time is an integer
multiple of the state transition sample time. In this case, a separate correction step is
performed corresponding to measurements from each measurement function.
The algorithm steps described previously assume that you have nonadditive noise terms
in the state transition and measurement functions. If you have additive noise terms in the
functions, the changes in the algorithm are:
• If the process noise w is additive, that is the state transition equation has the form
x[ k] = f ( x[ k - 1], us[ k - 1 ]) + w[ k - 1 ] , then the Jacobian matrix G[k] is an identity
matrix.
• If the measurement noise v is additive, that is the measurement equation has the form
y[ k ] = h( x[ k], um [ k]) + v[ k ] , then the Jacobian matrix S[k] is an identity matrix.
Additive noise terms in the state and transition functions reduce the processing time.
The first-order extended Kalman filter uses linear approximations to nonlinear state
transition and measurement functions. As a result, the algorithm may not be reliable if
13-4
Extended and Unscented Kalman Filter Algorithms for Online State Estimation
the nonlinearities in your system are severe. The unscented Kalman filter algorithm may
yield better results in this case.
Assume that the state transition and measurement equations for an M-state discrete-time
nonlinear system have additive process and measurement noise terms with zero mean
and covariances Q and R, respectively:
x[ k + 1] = f ( x[ k ], us[ k]) + w[ k]
y[ k ] = h( x[ k], um [ k]) + v[ k ]
w[ k] ~ (0, Q[ k ])
v[ k] ~ ( 0, R[ k])
You provide the initial values of Q and R in the ProcessNoise and MeasurementNoise
properties of the unscented Kalman filter object.
In the block, the software decides the order of prediction and correction of state
estimates. At the command line, you decide the order. For information about the order in
which to execute these commands, see the predict and correct reference pages.
Assuming that you implement the correct command before predict, the software
implements the algorithm as follows:
1 Initialize the filter object with initial values of the state, x[0], and state estimation
error covariance, P.
xˆ [0 | -1 ] = E( x[ 0])
P[ 0 | -1] = E( x[0 ] - xˆ[ 0 | -1])( x[0 ] - xˆ [0 | -1])T
13-5
13 State-Space Control Design
Here x̂ is the state estimate and xˆ [ ka | kb ] denotes the state estimate at time step ka
using measurements at time steps 0,1,...,kb. So xˆ [0 | -1 ] is the best guess of the
state value before you make any measurements. You specify this value when you
construct the filter.
2 For each time step k, update the state and state estimation error covariance using the
measured data, y[k]. In the software, the correct command performs this update.
a
Choose the sigma points xˆ ( i) [ k |k - 1] at time step k.
xˆ (0) [ k | k - 1] = xˆ[ k |k - 1]
xˆ ( i) [ k |k - 1] = xˆ [ k| k - 1 ] + Dx( i) i = 1,..., 2 M
Dx ( i)
= ( )i
cP[ k| k - 1 ] i = 1,..., M
D x( M +i ) = - ( cP[ k| k - 1 ] ) i = 1,..., M
i
T
root of cP such that cP ( cP ) = cP and ( cP )i is the ith column of cP .
b Use the nonlinear measurement function to compute the predicted
measurements for each of the sigma points.
yˆ ( i) [ k | k - 1] = h( xˆ ( i) [ k | k - 1] , um [k]) i = 0,1,..., 2 M
13-6
Extended and Unscented Kalman Filter Algorithms for Online State Estimation
2M
yˆ[ k ] = Â WM(i) yˆ(i) [k| k - 1]
i =0
( 0) M
WM =1-
2
a (M + k )
i 1
WM = i = 1, 2,..., 2 M
2a 2 ( M + k )
d Estimate the covariance of the predicted measurement. Add R[k] to account for
the additive measurement noise.
2M
Py = Â Wc(i) ( y(i)[k|k - 1] - y[k])( y(i)[k| k - 1] - y[k])T + R[k]
i =0
M
Wc( 0) = (2 - a 2 + b ) -
2
a (M +k)
2
Wci = 1 / (2a ( M + k )) i = 1, 2,..., 2M
For information about β parameter, see “Effect of Alpha, Beta, and Kappa
Parameters” on page 13-9.
e
Estimate the cross-covariance between xˆ [ k| k - 1 ] and yˆ[ k ] .
2M
1
Pxy = Â (x(i)[k| k - 1] - x[k| k - 1])( y(i)[k| k - 1] - y[k])T
2a 2 ( m + k ) i =1
K = Pxy Py-1
xˆ [ k| k ] = xˆ[ k | k - 1] + K ( y[ k ] - yˆ [ k])
P[ k | k] = P[ k| k - 1] - KPy K T
k
13-7
13 State-Space Control Design
3 Predict the state and state estimation error covariance at the next time step. In the
software, the predict command performs this prediction.
a
Choose the sigma points xˆ ( i) [ k |k ] at time step k.
xˆ (0) [ k | k] = xˆ [ k| k ]
xˆ ( i) [ k |k ] = xˆ[ k | k] + Dx(i ) i = 1,..., 2 M
D x( i) = ( )i
cP[ k| k ] i = 1,..., M
D x( M +i ) = - ( cP[ k| k ] ) i = 1,..., M
i
b Use the nonlinear state transition function to compute the predicted states for
each of the sigma points.
xˆ ( i) [ k + 1 | k] = f ( xˆ ( i) [ k | k] ,us[k])
c Combine the predicted states to obtain the predicted states at time k+1. These
values are used by the correct command in the next time step.
2M
xˆ [ k + 1| k ] = Â WM(i) xˆ(i)[k + 1| k]
i=0
( 0) M
WM =1-
2
a (M + k )
i 1
WM = i = 1, 2,..., 2 M
2a 2 ( M + k )
d Compute the covariance of the predicted state. Add Q[k] to account for the
additive process noise. These values are used by the correct command in the
next time step.
2M
P[ k + 1| k] = Â Wc(i) (x(i)[k + 1| k] - x[k + 1| k])(x(i)[k + 1| k] - x[k + 1| k])T + Q[k]
i =0
M
Wc( 0) = (2 - a 2 + b ) -
2
a (M +k)
2
Wci = 1 / (2a ( M + k )) i = 1, 2,..., 2 M
13-8
Extended and Unscented Kalman Filter Algorithms for Online State Estimation
The Unscented Kalman Filter block supports multiple measurement functions. These
measurements can have different sample times as long as their sample time is an integer
multiple of the state transition sample time. In this case, a separate correction step is
performed corresponding to measurements from each measurement function.
The previous algorithm is implemented assuming additive noise terms in the state
transition and measurement equations. If the noise terms are nonadditive, the main
changes to the algorithm are:
• The correct command generates 2*(M+V)+1 sigma points using P[k|k-1] and
R[k], where V is the number of elements in measurement noise v[k]. The R[k] term
is no longer added in the algorithm step 2(d) because the extra sigma points capture
the impact of measurement noise on Py.
• The predict command generates 2*(M+W)+1 sigma points using P[k|k] and Q[k],
where W is the number of elements in process noise w[k]. The Q[k] term is no longer
added in the algorithm step 3(d) because the extra sigma points capture the impact of
process noise on P[k+1|k].
To compute the state and its statistical properties at the next time step, the unscented
Kalman filter algorithm generates a set of state values distributed around the mean state
value. The algorithm uses each sigma points as an input to the state transition and
measurement functions to get a new set of transformed state points. The mean and
covariance of the transformed points is then used to obtain state estimates and state
estimation error covariance.
The spread of the sigma points around the mean state value is controlled by two
parameters α and κ. A third parameter, β, impacts the weights of the transformed points
during state and measurement covariance calculations.
• α — Determines the spread of the sigma points around the mean state value. It is
usually a small positive value. The spread of sigma points is proportional to α. Smaller
values correspond to sigma points closer to the mean state.
• κ — A second scaling parameter that is usually set to 0. Smaller values correspond to
sigma points closer to the mean state. The spread is proportional to the square-root of
κ.
• β — Incorporates prior knowledge of the distribution of the state. For Gaussian
distributions, β = 2 is optimal.
13-9
13 State-Space Control Design
You specify these parameters in the Alpha, Kappa, and Beta properties of the unscented
Kalman filter. If you know the distribution of state and state covariance, you can adjust
these parameters to capture the transformation of higher-order moments of the
distribution. The algorithm can track only a single peak in the probability distribution of
the state. If there are multiple peaks in the state distribution of your system, you can
adjust these parameters so that the sigma points stay around a single peak. For example,
choose a small Alpha to generate sigma points close to the mean state value.
References
[1] Simon, D. Optimal State Estimation: Kalman, H Infinity, and Nonlinear Approaches.
John Wiley and Sons Inc., 2006.
See Also
Functions
extendedKalmanFilter | unscentedKalmanFilter
Blocks
Extended Kalman Filter | Unscented Kalman Filter
13-10
Generate Code for Online State Estimation in MATLAB
1 Create a function to declare your filter object as persistent, and initialize the object.
You define the object as persistent to maintain the object states between calls.
The function creates an unscented Kalman filter object for online state estimation of
a van der Pol oscillator with two states and one output. You use the previously written
and saved state transition and measurement functions, vdpStateFcn.m and
vdpMeasurementFcn.m, and specify the initial state values for the two states as
[2;0]. Here output is the measured output data. Save the ukfcodegen.m function
on the MATLAB path. Alternatively, you can specify the full path name for this
function.
13-11
13 State-Space Control Design
tunable properties. For more information, see “Tunable and Nontunable Object
Properties” on page 13-13.
In the state transition and measurement functions you must use only commands that
are supported for code generation. For a list of these commands, see “Functions and
Objects Supported for C/C++ Code Generation — Category List” (MATLAB Coder).
Include the compilation directive %#codegen in these functions to indicate that you
intend to generate code for the function. Adding this directive instructs the MATLAB
Code Analyzer to help you diagnose and fix violations that would result in errors
during code generation. For an example, type vdpStateFcn.m at the command line.
2 Generate C/C++ code and MEX-files using the codegen command from MATLAB
Coder software.
The syntax -args {1} specifies an example of an argument to your function. The
argument sets the dimensions and data types of the function argument output as a
double-precision scalar.
Note If you want a filter with single-precision floating-point variables, you must
specify the initial value of the states as single-precision during object construction.
obj = unscentedKalmanFilter(@vdpStateFcn,@vdpMeasurementFcn,single([2;0]))
• Use the generated C/C++ code to deploy online state estimation to an embedded
target.
• Use the generated MEX-file for testing the compiled C/C++ code in MATLAB. The
generated MEX-file is also useful for accelerating simulations of state estimation
algorithms in MATLAB.
Load the estimation data. Suppose that your output data is stored in the
measured_data.mat file.
13-12
See Also
for i = 1:numel(output)
XCorrected = ukfcodegen_mex(output(i));
end
This example generates C/C++ code for compiling a MEX-file. To generate code for
other targets, see codegen in the MATLAB Coder documentation.
See Also
extendedKalmanFilter | particleFilter | unscentedKalmanFilter
13-13
13 State-Space Control Design
More About
• “Nonlinear State Estimation Using Unscented Kalman Filter and Particle Filter” on
page 13-24
• “Validate Online State Estimation at the Command Line” on page 13-15
• “Troubleshoot Online State Estimation” on page 13-22
13-14
Validate Online State Estimation at the Command Line
To validate the performance of your filter, perform state estimation using measured or
simulated output data from different scenarios.
• Obtain output data from your system at different operating conditions and input values
— To ensure that estimation works well under all operating conditions of interest. For
example, suppose that you want to track the position and velocity of a vehicle using
noisy position measurements. Measure the data at different vehicle speeds and slow
and sharp maneuvers.
• For each operating condition of interest, obtain multiple sets of experimental or
simulated data with different noise realizations — To ensure different noise values do
not deteriorate estimation performance.
For each of these scenarios, test the filter performance by examining the output
estimation error and state estimation error. For an example about performing and
validating online state estimation, see “Nonlinear State Estimation Using Unscented
Kalman Filter and Particle Filter” on page 13-24.
yEstimated = vdpMeasurementFcn(obj.State);
estimationError = y-yEstimated;
13-15
13 State-Space Control Design
Here obj.State is the state value xˆ [ k| k - 1 ] after you estimate the states using the
predict command. xˆ [ k| k - 1 ] is the predicted state estimate for time k, estimated using
measured output until a previous time k-1.
• Small magnitude — Small errors relative to the size of the outputs increase confidence
in the estimated values.
• Zero mean
• Low autocorrelation, except at zero time lag — To compute the autocorrelation, you
can use the xcorr command from Signal Processing Toolbox™ software.
• Small magnitude
• Zero mean
• Low autocorrelation, except at zero time lag
You can also compute the covariance of the state estimation error and compare it to the
state estimation error covariance stored in the StateCovariance property of the filter.
Similar values increase confidence in the performance of the filter.
See Also
extendedKalmanFilter | particleFilter | unscentedKalmanFilter
More About
• “Nonlinear State Estimation Using Unscented Kalman Filter and Particle Filter” on
page 13-24
13-16
See Also
• “Extended and Unscented Kalman Filter Algorithms for Online State Estimation” on
page 13-2
• “Troubleshoot Online State Estimation” on page 13-22
• “Generate Code for Online State Estimation in MATLAB” on page 13-11
13-17
13 State-Space Control Design
To validate the performance of your filter, perform state estimation using measured or
simulated output data from these scenarios.
• Obtain output data from your system at different operating conditions and input values
— To ensure that estimation works well under all operating conditions of interest. For
example, suppose that you want to track the position and velocity of a vehicle using
noisy position measurements. Measure the data at different vehicle speeds and slow
and sharp maneuvers.
• For each operating condition of interest, obtain multiple sets of experimental or
simulated data with different noise realizations — To ensure that different noise values
do not deteriorate estimation performance.
For each of these scenarios, test the filter performance by examining the residuals and
state estimation error.
Examine Residuals
The residual, or output estimation error, is the difference between the measured system
output yMeasured[k], and the estimated system output yPredicted[k|k-1] at time
step k. Here, yPredicted[k|k-1] is the estimated output at time step k, which is
predicted using output measurements until time step k-1.
The blocks do not explicitly output yPredicted[k|k-1], however you can compute the
output using the estimated state values and your state transition and measurement
functions. For an example, see “Compute Residuals and State Estimation Errors” on page
13-19.
• Small magnitude — Small errors relative to the size of the outputs increase confidence
in the estimated values.
13-18
Validate Online State Estimation in Simulink
• Zero mean
• Low autocorrelation, except at zero time lag — To compute the autocorrelation, you
can use the Autocorrelation block from DSP System Toolbox™ software.
• Small magnitude
• Zero mean
• Low autocorrelation, except at zero time lag
You can also compute the covariance of the state estimation error, and compare it to the
state estimation error covariance that is output by the blocks in the P port of the blocks.
Similar values increase confidence in the performance of the filter.
In the Simulink™ model, the Van der Pol Oscillator block implements the oscillator with
nonlinearity parameter, mu, equal to 1. The oscillator has two states. A noisy
measurement of the first state x1 is available.
The model uses the Unscented Kalman Filter block to estimate the states of the oscillator.
Since the block requires discrete-time inputs, the Rate Transition block samples x1 to
give the discretized output measurement yMeasured[k] at time step k. The Unscented
Kalman Filter block outputs the estimated state values xhat[k|k] at time step k, using
yMeasured until time k. The filter block uses the previously written and saved state
transition and measurement functions, vdpStateFcn.m and vdpMeasurementFcn.m.
For information about these functions, see “Nonlinear State Estimation Using Unscented
Kalman Filter and Particle Filter” on page 13-24.
13-19
13 State-Space Control Design
To validate the state estimation, the model computes the residuals in the Generate
Residual block. In addition, since the true state values are known, the model also
computes the state estimation errors.
To compute the residuals, the Generate Residual block first computes the estimated
output yPredicted[k|k-1] using the estimated states and state transition and
measurement functions. Here, yPredicted[k|k-1] is the estimated output at time step
k, predicted using output measurements until time step k-1. The block then computes
the residual at time step k as yMeasured[k] - yPredicted[k|k-1].
Examine the residuals and state estimation errors, and ensure that they have a small
magnitude, zero mean, and low autocorrelation.
In this example, the Unscented Kalman Filter block outputs xhat[k|k] because the Use
the current measurements to improve state estimates parameter of the block is
13-20
See Also
selected. If you clear this parameter, the block instead outputs xhat[k|k-1], the
predicted state value at time step k, using yMeasured until time k-1. In this case,
compute yPredicted[k|k-1] = MeasurementFcn(xhat[k|k-1]), where
MeasurementFcn is the measurement function for your system.
See Also
Extended Kalman Filter | Kalman Filter | Particle Filter | Unscented Kalman Filter
More About
• “Extended and Unscented Kalman Filter Algorithms for Online State Estimation” on
page 13-2
• “Troubleshoot Online State Estimation” on page 13-22
13-21
13 State-Space Control Design
• Initial state and state covariance values — If you find that the measured and estimated
outputs of your system are diverging at the beginning of state estimation, check the
initial values that you specified.
• State transition and measurement functions — Verify that the functions you specify are
a good representation of the nonlinear system. If the true system is continuous-time,
to implement the algorithms, you discretize the state transition and measurement
equations and use the discretized versions. If the state estimation results are not
satisfactory, consider decreasing the sample time used for discretization. Alternatively,
try a different discretization method. For an example of how to discretize a continuous-
time state transition function, type edit vdpStateFcn.m at the command line. Also
see, “Nonlinear State Estimation Using Unscented Kalman Filter and Particle Filter”
on page 13-24.
• Process and measurement noise covariance values — If the difference between
estimated and measured outputs of your system is large, try specifying different values
for the process and measurement noise covariance values.
• Choice of algorithm — If you are using the extended Kalman filter algorithm, you can
try the unscented Kalman filter, or the particle filter algorithm instead. The unscented
Kalman filter and particle filter may capture the nonlinearities in the system better.
To troubleshoot state estimation, you can create multiple versions of the filter with
different properties, perform state estimation, and choose the filter that gives the best
validation results.
At the command line, if you want to copy an existing filter object and then modify
properties of the copied object, use the clone command. Do not create additional objects
using syntax obj2 = obj. Any changes made to the properties of the new object created
in this way (obj2) also change the properties of the original object (obj).
See Also
Functions
extendedKalmanFilter | particleFilter | unscentedKalmanFilter
13-22
See Also
Blocks
Extended Kalman Filter | Particle Filter | Unscented Kalman Filter
More About
• “Validate Online State Estimation at the Command Line” on page 13-15
• “Generate Code for Online State Estimation in MATLAB” on page 13-11
• “Validate Online State Estimation in Simulink” on page 13-18
13-23
13 State-Space Control Design
Introduction
Control System Toolbox™ offers three commands for nonlinear state estimation:
The unscented Kalman filter (UKF) algorithm requires a function that describes the
evolution of states from one time step to the next. This is typically called the state
transition function. unscentedKalmanFilter supports the following two function forms:
1
Additive process noise:
2
Non-additive process noise:
13-24
Nonlinear State Estimation Using Unscented Kalman Filter and Particle Filter
Here f(..) is the state transition function, x is the state, w is the process noise. u is
optional and represents additional inputs to f, for instance system inputs or parameters. u
can be specified as zero or more function arguments. Additive noise means that the state
and process noise is related linearly. If the relationship is nonlinear, use the second form.
When you create the unscentedKalmanFilter object, you specify f(..) and also whether the
process noise is additive or non-additive.
The system in this example is the van der Pol oscillator with mu=1. This 2-state system is
described with the following set of nonlinear ordinary differential equations (ODE):
sample time is , and denote the continuous-time dynamics you have as . Euler
The accuracy of this approximation depends on the sample time . Smaller values
provide better approximations. Alternatively, you can use a different discretization
method. For instance, higher order Runge-Kutta family of methods provide a higher
accuracy at the expense of more computational cost, given a fixed sample time .
Create this state-transition function and save it in a file named vdpStateFcn.m. Use the
sample time . You provide this function to the unscentedKalmanFilter
during object construction.
13-25
13 State-Space Control Design
function x = vdpStateFcn(x)
% vdpStateFcn Discrete-time approximation to van der Pol ODEs for mu = 1.
% Sample time is 0.05s.
%
% Example state transition function for discrete-time nonlinear state
% estimators.
%
% xk1 = vdpStateFcn(xk)
%
% Inputs:
% xk - States x[k]
%
% Outputs:
% xk1 - Propagated states x[k+1]
%
% See also extendedKalmanFilter, unscentedKalmanFilter
%#codegen
% The tag %#codegen must be included if you wish to generate code with
% MATLAB Coder.
Sensor Modeling
unscentedKalmanFilter also needs a function that describes how the model states are
related to sensor measurements. unscentedKalmanFilter supports the following two
function forms:
1
Additive measurement noise:
13-26
Nonlinear State Estimation Using Unscented Kalman Filter and Particle Filter
2
Non-additive measurement noise:
For this example assume you have measurements of the first state within some
percentage error:
This falls into the category of non-additive measurement noise because the measurement
noise is not simply added to a function of states. You want to estimate both and
from the noisy measurements.
type vdpMeasurementNonAdditiveNoiseFcn
function yk = vdpMeasurementNonAdditiveNoiseFcn(xk,vk)
% vdpMeasurementNonAdditiveNoiseFcn Example measurement function for discrete
% time nonlinear state estimators with non-additive measurement noise.
%
% yk = vdpNonAdditiveMeasurementFcn(xk,vk)
%
% Inputs:
% xk - x[k], states at time k
% vk - v[k], measurement noise at time k
%
% Outputs:
% yk - y[k], measurements at time k
%
% The measurement is the first state with multiplicative noise
%
% See also extendedKalmanFilter, unscentedKalmanFilter
13-27
13 State-Space Control Design
%#codegen
% The tag %#codegen must be included if you wish to generate code with
% MATLAB Coder.
yk = xk(1)*(1+vk);
end
Construct the filter by providing function handles to the state transition and measurement
functions, followed by your initial state guess. The state transition model has additive
noise. This is the default setting in the filter, hence you do not need to specify it. The
measurement model has non-additive noise, which you must specify through setting the
HasAdditiveMeasurementNoise property of the object as false. This must be done
during object construction. If your application has non-additive process noise in the state
transition function, specify the HasAdditiveProcessNoise property as false.
% Your initial state guess at time k, utilizing measurements up to time k-1: xhat[k|k-1
initialStateGuess = [2;0]; % xhat[k|k-1]
% Construct the filter
ukf = unscentedKalmanFilter(...
@vdpStateFcn,... % State transition function
@vdpMeasurementNonAdditiveNoiseFcn,... % Measurement function
initialStateGuess,...
'HasAdditiveMeasurementNoise',false);
ProcessNoise property stores the process noise covariance. It is set to account for model
inaccuracies and the effect of unknown disturbances on the plant. We have the true model
in this example, but discretization introduces errors. This example did not include any
disturbances for simplicity. Set it to a diagonal matrix with less noise on the first state,
and more on the second state to reflect the knowledge that the second state is more
impacted by modeling errors.
13-28
Nonlinear State Estimation Using Unscented Kalman Filter and Particle Filter
In your application, the measurement data arriving from your hardware in real-time are
processed by the filters as they arrive. This operation is demonstrated in this example by
generating a set of measurement data first, and then feeding it to the filter one step at a
time.
Simulate the van der Pol oscillator for 5 seconds with the filter sample time 0.05 [s] to
generate the true states of the system.
Generate the measurements assuming that a sensor measures the first state, with a
standard deviation of 45% error in each measurement.
Perform online estimation of the states x using the correct and predict commands.
Provide generated data to the filter one time step at a time.
for k=1:Nsteps
% Let k denote the current time.
%
% Residuals (or innovations): Measured output - Predicted output
e(k) = yMeas(k) - vdpMeasurementFcn(ukf.State); % ukf.State is x[k|k-1] at this poi
% Incorporate the measurements at time k into the state estimates by
% using the "correct" command. This updates the State and StateCovariance
% properties of the filter to contain x[k|k] and P[k|k]. These values
% are also produced as the output of the "correct" command.
[xCorrectedUKF(k,:), PCorrected(k,:,:)] = correct(ukf,yMeas(k));
% Predict the states at next time step, k+1. This updates the State and
% StateCovariance properties of the filter to contain x[k+1|k] and
% P[k+1|k]. These will be utilized by the filter at the next time step.
13-29
13 State-Space Control Design
predict(ukf);
end
Plot the true and estimated states over time. Also plot the measured value of the first
state.
figure();
subplot(2,1,1);
plot(timeVector,xTrue(:,1),timeVector,xCorrectedUKF(:,1),timeVector,yMeas(:));
legend('True','UKF estimate','Measured')
ylim([-2.6 2.6]);
ylabel('x_1');
subplot(2,1,2);
plot(timeVector,xTrue(:,2),timeVector,xCorrectedUKF(:,2));
ylim([-3 1.5]);
xlabel('Time [s]');
ylabel('x_2');
13-30
Nonlinear State Estimation Using Unscented Kalman Filter and Particle Filter
The top plot shows the true, estimated, and the measured value of the first state. The
filter utilizes the system model and noise covariance information to produce an improved
estimate over the measurements. The bottom plot shows the second state. The filter is
able to produce a good estimate.
The validation of unscented and extended Kalman filter performance is typically done
using extensive Monte Carlo simulations. These simulations should test variations of
process and measurement noise realizations, plant operating under various conditions,
initial state and state covariance guesses. The key signal of interest used for validating
the state estimation is the residuals (or innovations). In this example, you perform
residual analysis for a single simulation. Plot the residuals.
13-31
13 State-Space Control Design
figure();
plot(timeVector, e);
xlabel('Time [s]');
ylabel('Residual (or innovation)');
13-32
Nonlinear State Estimation Using Unscented Kalman Filter and Particle Filter
ans = -0.0012
This is small relative to the magnitude of the residuals. The autocorrelation of the
residuals can be calculated with the xcorr function in the Signal Processing Toolbox.
13-33
13 State-Space Control Design
The correlation is small for all lags except 0. The mean correlation is close to zero, and
the correlation does not show any significant non-random variations. These
characteristics increase confidence in filter performance.
In reality the true states are never available. However, when performing simulations, you
have access to real states and can look at the errors between estimated and true states.
These errors must satisfy similar criteria to the residual:
1 Small magnitude
2 Variance within filter error covariance estimate
3 Zero mean
4 Uncorrelated.
First, look at the error and the uncertainty bounds from the filter error covariance
estimate.
eStates = xTrue-xCorrectedUKF;
figure();
subplot(2,1,1);
plot(timeVector,eStates(:,1),... % Error for the first state
timeVector, sqrt(PCorrected(:,1,1)),'r', ... % 1-sigma upper-bound
timeVector, -sqrt(PCorrected(:,1,1)),'r'); % 1-sigma lower-bound
xlabel('Time [s]');
ylabel('Error for state 1');
title('State estimation errors');
subplot(2,1,2);
plot(timeVector,eStates(:,2),... % Error for the second state
timeVector,sqrt(PCorrected(:,2,2)),'r', ... % 1-sigma upper-bound
timeVector,-sqrt(PCorrected(:,2,2)),'r'); % 1-sigma lower-bound
xlabel('Time [s]');
ylabel('Error for state 2');
legend('State estimate','1-sigma uncertainty bound',...
'Location','Best');
13-34
Nonlinear State Estimation Using Unscented Kalman Filter and Particle Filter
The error bound for state 1 approaches 0 at t=2.15 seconds because of the sensor model
(MeasurementFcn). It has the form . At t=2.15 seconds the true and
estimated states are near zero, which implies the measurement error in absolute terms is
also near zero. This is reflected in the state estimation error covariance of the filter.
Calculate what percentage of the points are beyond the 1-sigma uncertainty bound.
distanceFromBound1 = abs(eStates(:,1))-sqrt(PCorrected(:,1,1));
percentageExceeded1 = nnz(distanceFromBound1>0) / numel(eStates(:,1));
distanceFromBound2 = abs(eStates(:,2))-sqrt(PCorrected(:,2,2));
percentageExceeded2 = nnz(distanceFromBound2>0) / numel(eStates(:,2));
[percentageExceeded1 percentageExceeded2]
13-35
13 State-Space Control Design
ans = 1×2
0.1386 0
The first state estimation errors exceed the uncertainty bound approximately 14% of
the time steps. Less than 30% of the errors exceeding the 1-sigma uncertainty bound
implies good estimation. This criterion is satisfied for both states. The 0% percentage for
the second state means that the filter is conservative: most likely the combined process
and measurement noises are too high. Likely a better performance can be obtained by
tuning these parameters.
Calculate the mean autocorrelation of state estimation errors. Also plot the
autocorrelation.
mean(eStates)
ans = 1×2
-0.0103 0.0200
13-36
Nonlinear State Estimation Using Unscented Kalman Filter and Particle Filter
The mean value of the errors is small relative to the value of the states. The
autocorrelation of state estimation errors shows little non-random variations for small lag
values, but these are much smaller than the normalized peak value 1. Combined with the
fact that the estimated states are accurate, this behavior of the residuals can be
considered as satisfactory results.
Unscented and extended Kalman filters aim to track the mean and covariance of the
posterior distribution of the state estimates by different approximation methods. These
methods may not be sufficient if the nonlinearities in the system are severe. In addition,
for some applications, just tracking the mean and covariance of the posterior distribution
of the state estimates may not be sufficient. Particle filter can address these problems by
13-37
13 State-Space Control Design
tracking the evolution of many state hypotheses (particles) over time, at the expense of
higher computational cost. The computational cost and estimation accuracy increases
with the number of particles.
The state transition function you provide to particleFilter must perform two tasks. One,
sampling the process noise from any distribution appropriate for your system. Two,
calculating the time propagation of all particles (state hypotheses) to the next step,
including the effect of process noise you calculated in step one.
type vdpParticleFilterStateFcn
%#codegen
% The tag %#codegen must be included if you wish to generate code with
% MATLAB Coder.
13-38
Nonlinear State Estimation Using Unscented Kalman Filter and Particle Filter
%
% Euler integration of continuous-time dynamics x'=f(x) with sample time dt
dt = 0.05; % [s] Sample time
for kk=1:numberOfParticles
particles(:,kk) = particles(:,kk) + vdpStateFcnContinuous(particles(:,kk))*dt;
end
There are differences between the state transition function you supply to
unscentedKalmanFilter and particleFilter. The state transition function you used for
unscented Kalman filter just described propagation of one state hypothesis to the next
time step, instead of a set of hypotheses. In addition, the process noise distribution was
defined in ProcessNoise property of the unscentedKalmanFilter, just by its covariance.
Particle filter can consider arbitrary distributions that may require more statistical
properties to be defined. This arbitrary distribution and its parameters are fully defined in
the state transition function you provide to the particleFilter.
The measurement likelihood function you provide to particleFilter must also perform two
tasks. One, calculating measurement hypotheses from particles. Two, calculating the
likelihood of each particle from the sensor measurement and the hypotheses calculated in
step one.
type vdpExamplePFMeasurementLikelihoodFcn
13-39
13 State-Space Control Design
% Outputs:
% likelihood - A vector with NumberOfParticles elements whose n-th
% element is the likelihood of the n-th particle
%
% See also extendedKalmanFilter, unscentedKalmanFilter
%#codegen
% The tag %#codegen must be included if you wish to generate code with
% MATLAB Coder.
% The measurement is first state. Get all measurement hypotheses from particles
predictedMeasurement = particles(1,:);
% Assume the ratio of the error between predicted and actual measurements
% follow a Gaussian distribution with zero mean, variance 0.2
mu = 0; % mean
sigma = 0.2 * eye(numberOfMeasurements); % variance
Now construct the filter, and initialize it with 1000 particles around the mean [2; 0] with
0.01 covariance. The covariance is small because you have high confidence in your guess
[2; 0].
pf = particleFilter(@vdpParticleFilterStateFcn,@vdpExamplePFMeasurementLikelihoodFcn);
initialize(pf, 1000, [2;0], 0.01*eye(2));
13-40
Nonlinear State Estimation Using Unscented Kalman Filter and Particle Filter
Optionally, pick the state estimation method. This is set by the StateEstimationMethod
property of particleFilter, which can take the value 'mean' (default) or 'maxweight'. When
StateEstimationMethod is 'mean', the object extracts a weighted mean of the particles
from the Particles and Weights properties as the state estimate. 'maxweight' corresponds
to choosing the particle (state hypothesis) as the state estimate. Alternatively, you can
access Particles and Weights properties of the object and extract your state estimate via
an arbitrary method of your choice.
pf.StateEstimationMethod
ans =
'mean'
particleFilter lets you specify various resampling options via its ResamplingPolicy and
ResamplingMethod properties. This example uses the default settings in the filter. See the
particleFilter documentation for further details on resampling.
pf.ResamplingMethod
ans =
'multinomial'
pf.ResamplingPolicy
ans =
particleResamplingPolicy with properties:
TriggerMethod: 'ratio'
SamplingInterval: 1
MinEffectiveParticleRatio: 0.5000
Start the estimation loop. This represents measurements arriving over time, step by step.
% Estimate
xCorrectedPF = zeros(size(xTrue));
for k=1:size(xTrue,1)
% Use measurement y[k] to correct the particles for time k
xCorrectedPF(k,:) = correct(pf,yMeas(k)); % Filter updates and stores Particles[k|k
% The result is x[k|k]: Estimate of states at time k, utilizing
% measurements up to time k. This estimate is the mean of all particles
% because StateEstimationMethod was 'mean'.
%
% Now, predict particles at next time step. These are utilized in the
% next correct command
13-41
13 State-Space Control Design
figure();
subplot(2,1,1);
plot(timeVector,xTrue(:,1),timeVector,xCorrectedPF(:,1),timeVector,yMeas(:));
legend('True','Particlte filter estimate','Measured')
ylim([-2.6 2.6]);
ylabel('x_1');
subplot(2,1,2);
plot(timeVector,xTrue(:,2),timeVector,xCorrectedPF(:,2));
ylim([-3 1.5]);
xlabel('Time [s]');
ylabel('x_2');
13-42
Nonlinear State Estimation Using Unscented Kalman Filter and Particle Filter
The top plot shows the true value, particle filter estimate, and the measured value of the
first state. The filter utilizes the system model and noise information to produce an
improved estimate over the measurements. The bottom plot shows the second state. The
filter is able to produce a good estimate.
The validation of the particle filter performance involves performing statistical tests on
residuals, similar to those that were performed earlier in this example for unscented
Kalman filter results.
Summary
This example has shown the steps of constructing and using an unscented Kalman filter
and a particle filter for state estimation of a nonlinear system. You estimated states of a
13-43
13 State-Space Control Design
van der Pol oscillator from noisy measurements, and validated the estimation
performance.
See Also
extendedKalmanFilter | particleFilter | unscentedKalmanFilter
More About
• “Extended and Unscented Kalman Filter Algorithms for Online State Estimation” on
page 13-2
• “Validate Online State Estimation at the Command Line” on page 13-15
• “Troubleshoot Online State Estimation” on page 13-22
• “Generate Code for Online State Estimation in MATLAB” on page 13-11
13-44
Estimate States of Nonlinear System with Multiple, Multirate Sensors
Introduction
The toolbox has three Simulink blocks for nonlinear state estimation:
These blocks support state estimation using multiple sensors operating at different
sample rates. A typical workflow for using these blocks is as follows:
1 Model your plant and sensor behavior using MATLAB or Simulink functions.
2 Configure the parameters of the block.
3 Simulate the filter and analyze results to gain confidence in filter performance.
4 Deploy the filter on your hardware. You can generate code for these filters using
Simulink Coder™ software.
This example uses the Extended Kalman Filter block to demonstrate the first two steps of
this workflow. The last two steps are briefly discussed in the Next Steps section. The goal
in this example is to estimate the states of an object using noisy measurements provided
by a radar and a GPS sensor. The states of the object are its position and velocity, which
are denoted as xTrue in the Simulink model.
If you are interested in the Particle Filter block, please see the example "Parameter and
State Estimation in Simulink Using Particle Filter Block".
13-45
13 State-Space Control Design
Plant Modeling
The extended Kalman filter (EKF) algorithm requires a state transition function that
describes the evolution of states from one time step to the next. The block supports the
following two function forms:
Here f(..) is the state transition function, x is the state, and w is the process noise. u is
optional, and represents additional inputs to f, for instance system inputs or parameters.
Additive noise means that the next state and process noise are related
linearly. If the relationship is nonlinear, use the nonadditive form.
The function f(...) can be a MATLAB Function that comply with the restrictions of
MATLAB Coder™, or a Simulink Function block. After you create f(...), you specify the
function name and whether the process noise is additive or nonadditive in the Extended
Kalman Filter block.
In this example, you are tracking the north and east positions and velocities of an object
on a 2-dimensional plane. The estimated quantities are:
13-46
Estimate States of Nonlinear System with Multiple, Multirate Sensors
Here is the discrete-time index. The state transition equation used is of the nonadditive
form , where is the state vector, and is the process noise.
The filter assumes that is a zero-mean, independent random variable with known
variance . The A and G matrices are:
where is the sample time. The third row of A and G model the east velocity as a random
walk: . In reality, position is a continuous-time variable and is the
integral of velocity over time . The first row of A and G represent a discrete
approximation to this kinematic relationship:
. The second and fourth rows of A and G
represent the same relationship between the north velocity and position. This state
transition model is linear, but the radar measurement model is nonlinear. This
nonlinearity necessitates the use of a nonlinear state estimator such as the extended
Kalman filter.
In this example you implement the state transition function using a Simulink Function
block. To do so,
13-47
13 State-Space Control Design
• Though it is not required in this example, you can use any signals from the rest of your
Simulink model in the Simulink Function. To do so, add Inport blocks from the
Simulink/Sources library. Note that these are different than the ArgIn and ArgOut
blocks that are set through the signature of your function (xNext =
stateTransitionFcn(x, w)).
• In the Simulink Function block, construct your function utilizing Simulink blocks.
• Set the dimensions for the input and output arguments x, w, and xNext in the Signal
Attributes tab of the ArgIn and ArgOut blocks. The data type and port dimensions
must be consistent with the information you provide in the Extended Kalman
Filter block.
Analytical Jacobian of the state transition function is also implemented in this example.
Specifying the Jacobian is optional. However, this reduces the computational burden, and
in most cases increases the state estimation accuracy. Implement the Jacobian function as
a Simulink function because the state transition function is a Simulink function.
open_system('multirateEKFExample/Simulink Function - State Transition Jacobian');
13-48
Estimate States of Nonlinear System with Multiple, Multirate Sensors
The Extended Kalman Filter block also needs a measurement function that describes how
the states are related to measurements. The following two function forms are supported:
Here h(..) is the measurement function, and v is the measurement noise. u is optional, and
represents additional inputs to h, for instance system inputs or parameters. These inputs
can differ from the inputs in the state transition function.
In this example a radar located at the origin measures the range and angle of the object
at 20 Hz. Assume that both of the measurements have about 5% noise. This can be
modeled by the following measurement equation:
Here and are the measurement noise terms, each with variance 0.05^2. That
is, most of the measurements have errors less than 5%. The measurement noise is
nonadditive because and are not simply added to the measurements, but
instead they depend on the states x. In this example, the radar measurement equation is
implemented using a Simulink Function block.
open_system('multirateEKFExample/Simulink Function - Radar Measurements');
13-49
13 State-Space Control Design
A GPS measures the east and north positions of the object at 1 Hz. Hence, the
measurement equation for the GPS sensor is:
Here and are measurement noise terms with the covariance matrix [10^2 0; 0
10^2]. That is, the measurements are accurate up to approximately 10 meters, and the
errors are uncorrelated. The measurement noise is additive because the noise terms
affect the measurements linearly.
Create this function, and save it in a file named gpsMeasurementFcn.m. When the
measurement noise is additive, you must not specify the noise terms in the function. You
provide this function name and measurement noise covariance in the Extended Kalman
Filter block.
type gpsMeasurementFcn
function y = gpsMeasurementFcn(x)
% gpsMeasurementFcn GPS measurement function for state estimation
%
% Assume the states x are:
% [EastPosition; NorthPosition; EastVelocity; NorthVelocity]
13-50
Estimate States of Nonlinear System with Multiple, Multirate Sensors
%#codegen
% The %#codegen tag above is needed is you would like to use MATLAB Coder to
% generate C or C++ code for your filter
Filter Construction
Configure the Extended Kalman Filter block to perform the estimation. You specify the
state transition and measurement function names, initial state and state error covariance,
and process and measurement noise characteristics.
In the System Model tab of the block dialog, specify the following parameters:
State Transition
Initialization
1 Specify your best initial state estimate in Initial state. In this example, specify [100;
100; 0; 0].
2 Specify your confidence in your state estimate guess in Initial covariance. In this
example, specify 10. The software interprets this value as the true state values are
likely to be within of your initial estimate. You can specify a separate value for
each state by setting Initial covariance as a vector. You can specify cross-
correlations in this uncertainty by specifying it as a matrix.
13-51
13 State-Space Control Design
Since there are two sensors, click Add Measurement to specify a second measurement
function.
Measurement 1
Measurement 2
13-52
Estimate States of Nonlinear System with Multiple, Multirate Sensors
13-53
13 State-Space Control Design
In the Multirate tab, since the two sensors are operating at different sample rates,
perform the following configuration:
13-54
Estimate States of Nonlinear System with Multiple, Multirate Sensors
Test the performance of the Extended Kalman filter by simulating a scenario where the
object travels in a square pattern with the following maneuvers:
13-55
13 State-Space Control Design
Simulate the model. For instance, look at the actual and estimated velocities in the east
direction:
sim('multirateEKFExample');
open_system('multirateEKFExample/Scope - East Velocity');
13-56
Estimate States of Nonlinear System with Multiple, Multirate Sensors
The plot shows the true velocity in the east direction, and its extended Kalman filter
estimates. The filter successfully tracks the changes in velocity. The multirate nature of
the filter is most apparent in the time range t = 20 to 30 seconds. The filter makes large
corrections every second (GPS sample rate), while the corrections due to radar
measurements are visible every 0.05 seconds.
13-57
13 State-Space Control Design
Next Steps
1 Validate the state estimation: The validation of unscented and extended Kalman filter
performance is typically done using extensive Monte Carlo simulations. For more
information, see “Validate Online State Estimation in Simulink” on page 13-18.
2 Generate code: The Unscented and Extended Kalman Filter blocks support C and C+
+ code generation using Simulink Coder™ software. The functions you provide to
these blocks must comply with the restrictions of MATLAB Coder™ software (if you
are using MATLAB functions to model your system) and Simulink Coder software (if
you are using Simulink Function blocks to model your system).
Summary
This example has shown how to use the Extended Kalman Filter block in System
Identification Toolbox. You estimated position and velocity of an object from two different
sensors operating at different sampling rates.
close_system('multirateEKFExample', 0);
See Also
Extended Kalman Filter | Particle Filter | Unscented Kalman Filter
More About
• “Extended and Unscented Kalman Filter Algorithms for Online State Estimation” on
page 13-2
• “Validate Online State Estimation in Simulink” on page 13-18
• “Troubleshoot Online State Estimation” on page 13-22
13-58
Control System Tuning
59
14
14-2
Automated Tuning Overview
This control system includes a number of fixed elements, such as the helicopter model
itself and the roll-off filters. The inner control loop provides static output feedback for
decoupling. The outer loop includes PI controllers for setpoint tracking. The tuning tools
jointly optimize the gains in the SOF and PI blocks to meet setpoint tracking, stability
margin, and other requirements that you specify. These tools allow you to specify any
control structure and designate which blocks in your system are tunable.
Control systems are tuned to meet your specific performance and robustness goals
subject to feasibility constraints such as actuator limits, sensor accuracy, computing
power, or energy consumption. The library of tuning goals lets you capture these
objectives in a form suitable for fast automated tuning. This library includes standard
control objectives such as reference tracking, disturbance rejection, loop shapes, closed-
14-3
14 Control System Tuning
loop damping, and stability margins. Using these tools, you can perform multi-objective
tuning of control systems having any structure.
See Also
Control System Designer | systune
More About
• “Choosing an Automated Tuning Approach” on page 14-5
• “Automated Tuning Workflow” on page 14-7
14-4
Choosing an Automated Tuning Approach
Control System Tuner provides an interactive graphical interface for specifying your
tuning goals and validating the performance of the tuned control system.
Use Control System Tuner to tune control systems consisting of any number of feedback
loops, with tunable components having any structure (such as PID, gain block, or state-
space). You can represent your control architecture in MATLAB as a tunable generalized
14-5
14 Control System Tuning
state-space (genss) model. If you have Simulink Control Design software, you can tune a
control system represented by a Simulink model. Use the graphical interface to configure
your tuning goals, examine response plots, and validate your controller design.
The systune command can perform all the same tuning tasks as Control System Tuner.
Tuning at the command line allows you to write scripts for repeated tuning tasks.
systune also provides advanced techniques such as tuning a controller for multiple
plants, or designing gain-scheduled controllers. To use the command-line tuning tools,
you can represent your control architecture in MATLAB as a tunable generalized state-
space (genss) model. If you have Simulink Control Design software, you can tune a
control system represented by a Simulink model using an slTuner interface. Use the
TuningGoal requirement objects to configure your tuning goals. Analysis commands
such as getIOTransfer and viewGoal let you examine and validate the performance of
your tuned system.
See Also
Control System Designer | systune
More About
• “Automated Tuning Workflow” on page 14-7
14-6
Automated Tuning Workflow
1 Define your control architecture, by building a model of your control system from
fixed-value blocks and blocks with tunable parameters. You can do so in one of
several ways:
For more information, see “Specify Control Architecture in Control System Tuner” on
page 14-9.
2 Set up your model for tuning.
• In Control System Tuner, identify which blocks of the model you want to tune. See
Model Setup for Control System Tuner.
• If tuning a Simulink model at the command line, create and configure the
slTuner interface to the model. See Setup for Tuning Simulink Models at the
Command Line.
3 Specify your tuning goals. Use the library of tuning goals to capture requirements
such as reference tracking, disturbance rejection, stability margins, and more.
• In Control System Tuner, use the graphical interface to specify tuning goals. See
Tuning Goals (Control System Tuner).
• At the command-line, use the TuningGoal requirement objects to specify your
tuning goals. See Tuning Goals (programmatic tuning).
4 Tune the model. Use the systune command or Control System Tuner to optimize the
tunable parameters of your control system to best meet your specified tuning goals.
Then, analyze the tuned system responses and validate the design. Whether at the
command line or in Control System Tuner, you can plot system responses to examine
any aspects of system performance you need to validate your design.
• For tuning and validating in Control System Tuner, see Tuning, Analysis, and
Validation (Control System Tuner).
14-7
14 Control System Tuning
• For tuning at the command line, see Tuning, Analysis, and Validation
(programmatic tuning).
14-8
Specify Control Architecture in Control System Tuner
G is the plant model, and H the sensor dynamics. These are usually the fixed components
of the control system. The prefilter F and feedback controller C are the tunable elements.
Because control systems are so conveniently expressed in this block diagram form, these
elements are referred to as fixed blocks and tunable blocks.
Control System Tuner gives you several ways to define your control system architecture:
14-9
14 Control System Tuning
For example, suppose you have a DC motor for which you want to tune a PID controller.
The response of the motor is modeled as G(s) = 1/(s + 1)2. Create a fixed LTI model
representing the plant, and a tunable PID controller model.
Gmot = zpk([],[-1,-1],1);
Cmot = tunablePID('Cmot','PID');
controlSystemTuner
Control System Tuner opens, set to tune this default architecture. Next, specify the values
Enter the values for C and G that you created. Control System Tuner reads these values
from the MATLAB workspace. Click OK.
The default value for the sensor dynamics is a fixed unity-gain transfer function. The
default value for the filter F is a tunable gain block.
You can now select blocks to tune, create tuning goals, and tune the control system.
14-10
Specify Control Architecture in Control System Tuner
+ u1 + u2 y2
r PID PI G2 x2 G1 y1
- -
C1 C2
x1
Create tunable control design blocks for the controllers, and fixed LTI models for the
plant components, G1 and G2. Also include optional loop-opening locations x1 and x2.
These locations indicate where you can open loops or inject signals for the purpose of
specifying requirements for tuning the system.
G2 = zpk([],-2,3);
G1 = zpk([],[-1 -1 -1],10);
C20 = tunablePID('C2','pi');
C10 = tunablePID('C1','pid');
X1 = AnalysisPoint('X1');
X2 = AnalysisPoint('X2');
Connect these components to build a model of the entire closed-loop control system.
InnerLoop = feedback(X2*G2*C20,1);
CL0 = feedback(G1*InnerLoop*C10,X1);
CL0.InputName = 'r';
CL0.OutputName = 'y';
CL0 is a tunable genss model. Specifying names for the input and output channels allows
you to identify them when you specify tuning requirements for the system.
14-11
14 Control System Tuning
controlSystemTuner(CL0)
You can now select blocks to tune, create tuning goals, and tune the control system.
Related Examples
See “Open Control System Tuner for Tuning Simulink Model” on page 14-13.
14-12
Open Control System Tuner for Tuning Simulink Model
Each instance of Control System Tuner is linked to the Simulink model from which it is
opened. The title bar of the Control System Tuner window reflects the name of the
associated Simulink model.
14-13
14 Control System Tuning
Command-Line Equivalents
At the MATLAB command line, use the controlSystemTuner command to open Control
System Tuner for tuning a Simulink model. For example, the following command opens
Control System Tuner for the model rct_helico.slx.
controlSystemTuner('rct_helico')
If SLT0 is an slTuner interface to the Simulink model, the following command opens
Control System Tuner using the information in the interface, such as blocks to tune and
analysis points.
controlSystemTuner(SLT0)
See Also
Related Examples
• “Specify Operating Points for Tuning in Control System Tuner” on page 14-15
• “Specify Blocks to Tune in Control System Tuner” on page 14-24
More About
• “Automated Tuning Workflow” on page 14-7
14-14
Specify Operating Points for Tuning in Control System Tuner
By default, Control System Tuner linearizes at the operating point specified in the model,
which comprises the initial state values in the model (the model initial conditions). You
can specify one or more alternate operating points for tuning the model. Control System
Tuner lets you compute two types of alternate operating points:
• Simulation snapshot time. Control System Tuner simulates the model for the amount
of time you specify, and linearizes using the state values at that time. Simulation
snapshot linearization is useful, for instance, when you know your model reaches an
equilibrium state after a certain simulation time.
• Steady-state operating point. Control System Tuner finds a steady-state operating
point at which some specified condition is met (trimming). For example, if your model
represents an automobile motor, you can compute an operating point at which the
motor operates steadily at 2000 rpm.
For more information on finding steady-state operating points, see “About Operating
Points” (Simulink Control Design) and “Compute Steady-State Operating Points”
(Simulink Control Design).
In the Control System tab, in the Operating Point menu, select Linearize At.
14-15
14 Control System Tuning
In the Enter snapshot times to linearize dialog box, specify one or more simulation
snapshot times. Click OK.
14-16
Specify Operating Points for Tuning in Control System Tuner
When you are ready to analyze system responses or tune your model, Control System
Tuner computes linearizations at the specified snapshot times. If you enter multiple
snapshot times, Control System Tuner computes an array of linearized models, and
displays analysis plots that reflect the multiple linearizations in the array. In this case,
Control System Tuner also takes into account all linearizations when tuning parameters.
This helps to ensure that your tuned controller meets your design requirements at a
variety of operating conditions.
In the Control System tab, in the Operating Point menu, select Take simulation
snapshot.
14-17
14 Control System Tuning
In the Enter snapshot times to linearize dialog box, in the Simulation snapshot
times field, enter one or more simulation snapshot times. Enter multiple snapshot times
as a vector.
14-18
Specify Operating Points for Tuning in Control System Tuner
Click Take Snapshots. Control System Tuner simulates the model and computes the
snapshot operating points.
Compute additional snapshot operating points if desired. Enter additional snapshot times
and click Take Snapshots. Close the dialog box when you are done.
When you are ready to analyze responses or tune your model, select the operating point
at which you want to linearize the model. In the Control System tab, in the Operating
Point menu, stored operating points are available.
14-19
14 Control System Tuning
14-20
Specify Operating Points for Tuning in Control System Tuner
If you entered a vector of snapshot times, all the resulting operating points are stored
together in an operating-point vector. You can use this vector to tune a control system at
several operating points simultaneously.
In the Control System tab, in the Operating Point menu, select Trim model.
14-21
14 Control System Tuning
In the Trim the model dialog box, enter the specifications for the steady-state state
values at which you want to find an operating point.
For examples showing how to use the Trim the model dialog box to specify the
conditions for a steady-state operating point search, see “Compute Steady-State
Operating Point from State Specifications” (Simulink Control Design) and “Compute
Steady-State Operating Point from Output Specifications” (Simulink Control Design).
When you have entered your state specifications, click Start trimming. Control
System Tuner finds an operating point that meets the state specifications and stores it.
When you are ready to analyze responses or tune your model, select the operating point
at which you want to linearize the model. In the Control System tab, in the Operating
Point menu, stored operating points are available.
14-22
See Also
See Also
Related Examples
• “Specify Blocks to Tune in Control System Tuner” on page 14-24
• “Robust Tuning Approaches” (Robust Control Toolbox)
14-23
14 Control System Tuning
1
In the Tuning tab, click Select Blocks. The Select tuned Blocks dialog opens.
2 Click Add Blocks. Control System Tuner analyzes your model to find blocks that can
be tuned.
3 In the Select Blocks to Tune dialog box, use the nodes in the left panel to navigate
through your model structure to the subsystem that contains blocks you want to tune.
Check Tune? for the blocks you want to tune. The parameters of blocks you do not
check remain constant when you tune the model.
Tip To find a block in your model, select the block in the Block Name list and click
Highlight Selected Block.
4 Click OK. The Select tuned blocks dialog box now reflects the blocks you added.
14-24
See Also
To import the current value of a block from your model into the current design in Control
System Tuner, select the block in the Blocks list and click Sync from Model. Doing so is
useful when you have tuned a block in Control System Tuner, but wish to restore that
block to its original value. To store the current design before restoring a block value, in
the Control System tab, click Store.
See Also
Related Examples
• “View and Change Block Parameterization in Control System Tuner” on page 14-26
More About
• “How Tuned Simulink Blocks Are Parameterized” on page 14-36
14-25
14 Control System Tuning
• When you tune a Simulink model, Control System Tuner automatically assigns a
default parameterization to tunable blocks in the model. The default parameterization
depends on the type of block. For example, a PID Controller block configured for PI
structure is parameterized by proportional gain and integral gain as follows:
1
u = K p + Ki .
s
Kp and Ki are the tunable parameters whose values are optimized to satisfy your
specified tuning goals.
• When you tune a predefined control architecture or a MATLAB (generalized state-
space) model, you define the parameterization of each tunable block when you create
it at the MATLAB command line. For example, you can use tunablePID to create a
tunable PID block.
Control System Tuner lets you view and change the parameterization of any block to be
tuned. Changing the parameterization can include changing the structure or current
parameter values. You can also designate individual block parameters fixed (non-tunable)
or limit their tuning range.
14-26
View and Change Block Parameterization in Control System Tuner
14-27
14 Control System Tuning
The fields of the Tuned Block Editor display the type of parameterization, such as PID,
State-Space, or Gain. For more specific information about the fields, click .
Note To find a tuned block in the Simulink model, right-click the block name in the Data
Browser and select Highlight.
To change a current parameter value, type a new value in its text box. Alternatively, click
to use a variable editor to change the current value. If you attempt to enter an invalid
value, the parameter returns to its previous value.
14-28
View and Change Block Parameterization in Control System Tuner
• Minimum — Minimum value that the parameter can take when the control system is
tuned.
• Maximum — Maximum value that the parameter can take when the control system is
tuned.
• Free — When the value is true, Control System Toolbox tunes the parameter. To fix
the value of the parameter, set Free to false.
For array-valued parameters, you can set these properties independently for each entry in
the array. For example, for a vector-valued gain of length 3, enter [1 10 100] to set the
current value of the three gains to 1, 10, and 100 respectively. Alternatively, click to
use a variable editor to specify such values.
14-29
14 Control System Tuning
For vector or matrix-valued parameters, you can use the Free parameter to constrain the
structure of the parameter. For example, to restrict a matrix-valued parameter to be a
diagonal matrix, set the current values of the off-diagonal elements to 0, and set the
corresponding entries in Free to false.
Custom Parameterization
When tuning a control system represented by a Simulink model or by a “Predefined
Feedback Architecture” on page 14-9, you can specify a custom parameterization for any
tuned block using a generalized state-space (genss) model. To do so, create and
configure a genss model in the MATLAB workspace that has the desired
parameterization, initial parameter values, and parameter properties. In the Change
parameterization dialog box, select Custom. In the Parameterization area, the
variable name of the genss model.
For example, suppose you want to specify a tunable low-pass filter, F = a/(s +a), where a
is the tunable parameter. First, at the MATLAB command line, create a tunable genss
model that represents the low-pass filter structure.
a = realp('a',1);
F = tf(a,[1 a]);
F =
Type "ss(F)" to see the current value, "get(F)" to see all properties, and
"F.Blocks" to interact with the blocks.
14-30
View and Change Block Parameterization in Control System Tuner
When you specify a custom parameterization for a Simulink block, you might not be able
to write the tuned block value back to the Simulink model. When writing values to
Simulink blocks, Control System Tuner skips blocks that cannot represent the tuned value
in a straightforward and lossless manner. For example, if you reparameterize a PID
Controller Simulink block as a third-order state-space model, Control System Tuner will
not write the tuned value back to the block.
14-31
14 Control System Tuning
By default, Control System Tuner performs linearization and tuning in continuous time
(sample time = 0). You can specify discrete-time linearization and tuning and change the
sample time. To do so, on the Control System tab, click Linearization Options. Sample
time for tuning reflects the sample time specified in the Linearization Options dialog
box.
14-32
View and Change Block Parameterization in Control System Tuner
For more information about PID discretization formulas, see “Discrete-Time Proportional-
Integral-Derivative (PID) Controllers” on page 2-24.
For discrete-time PID Controller and PID Controller (2-DOF) blocks, you set the integrator
and derivative filter methods in the block dialog box. You cannot change them in the
Tuned Block Editor.
For blocks other than PID Controller blocks, the following rate-conversion methods are
available:
• Zero-order hold — Zero-order hold on the inputs. For most dynamic blocks this is
the default rate-conversion method.
• Tustin — Bilinear (Tustin) approximation.
• Tustin with prewarping — Tustin approximation with better matching between
the original and rate-converted dynamics at the prewarp frequency. Enter the
frequency in the Prewarping frequency field.
• First-order hold — Linear interpolation of inputs.
• Matched (SISO only) — Zero-pole matching equivalents.
For more detailed information about these rate-conversion methods, see “Continuous-
Discrete Conversion Methods” on page 5-26.
For the following blocks, you cannot set the rate-conversion method in the Tuned Block
Editor.
14-33
14 Control System Tuning
• Discrete-time PID Controller and PID Controller (2-DOF) block. Set the integrator and
derivative filter methods in the block dialog box.
• Gain block, because it is static.
• Transfer Fcn Real Zero block. This block can only be tuned at the sample time
specified in the block.
• Block that has been discretized using the Model Discretizer. Sample time for this block
is specified in the Model Discretizer itself.
See Also
Related Examples
• “Specify Blocks to Tune in Control System Tuner” on page 14-24
More About
• “How Tuned Simulink Blocks Are Parameterized” on page 14-36
14-34
Setup for Tuning Control System Modeled in MATLAB
Building a tunable genss model for Control System Tuner is the same as building such a
model for tuning at the command line. For information about building such models,
“Setup for Tuning MATLAB Models”.
When you have a tunable genss model of your control system, use the
controlSystemTuner command to open Control System Tuner. For example, if T0 is the
genss model, the following command opens Control System Tuner for tuning T0:
controlSystemTuner(T0)
See Also
Related Examples
• “Specify Goals for Interactive Tuning” on page 14-39
14-35
14 Control System Tuning
14-36
How Tuned Simulink Blocks Are Parameterized
Scalar Expansion
• Discrete Filter
• Gain
• 1-D Lookup Table, 2-D Lookup Table, n-D Lookup Table
• PID Controller, PID Controller (2DOF)
Scalar expansion means that the block parameters can be scalar values even when the
input and output signals are vectors. For example, you can use a Gain block to implement
y = k*u with scalar k and vector u and y. To do so, you set the Multiplication mode of
the block to Element-wise(K.*u), and set the gain value to the scalar k.
When a tunable block uses scalar expansion, its default parameterization uses tunable
scalars. For example, in the y = k*u Gain block, the software parameterizes the scalar k
as a tunable real scalar (realp of size [1 1]). If instead you want to tune different gain
values for each channel, replace the scalar gain k by a N-by-1 gain vector in the block
dialog, where N is the number of channels, the length of the vectors u and y. The software
then parameterizes the gain as a realp of size [N 1].
14-37
14 Control System Tuning
between the tuned parameters and the block. To validate a tuned control system that
contains such blocks, you can specify a block linearization in your model using the value
of the tuned parameterization. (See “Specify Linear System for Block Linearization Using
MATLAB Expression” (Simulink Control Design) for more information about specifying
block linearization.)
• In Control System Tuner, see “View and Change Block Parameterization in Control
System Tuner” on page 14-26.
• At the command line, use getBlockParam to view the current block
parameterization. Use setBlockParam to change the block parameterization.
14-38
Specify Goals for Interactive Tuning
Use the New Goal menu to create a tuning goal such as a tracking requirement,
disturbance rejection specification, or minimum stability margins. Then, when you are
ready to tune your control system, use Manage Goals to designate which goals to
enforce.
This example creates tuning goals for tuning the sample model rct_helico.
In Control System Tuner, in the Tuning tab, click New Goal. Select the type of goal
you want to create. A tuning goal dialog box opens in which you can provide the detailed
specifications of your goal. For example, select Tracking of step commands to make a
particular step response of your control system match a desired response.
14-39
14 Control System Tuning
Specify the signal locations in your control system at which the tuning goal is evaluated.
For example, the step response goal specifies that a step signal applied at a particular
input location yields a desired response at a particular output location. Use the Step
Response Selection section of the dialog box to specify these input and output locations.
14-40
Specify Goals for Interactive Tuning
(Other tuning goal types, such as loop-shape or stability margins, require you to specify
only one location for evaluation. The procedure for specifying the location is the same as
illustrated here.)
Under Specify step-response inputs, click Add signal to list. A list of available
input locations appears.
If the signal you want to designate as a step-response input is in the list, click the signal
to add it to the step-response inputs. If the signal you want to designate does not appear,
and you are tuning a Simulink model, click Select signal from model.
In the Select signals dialog box, build a list of the signals you want. To do so, click
signals in the Simulink model editor. The signals that you click appear in the Select
signals dialog box. Click one signal to create a SISO tuning goal, and click multiple
signals to create a MIMO tuning goal.
Click Add signal(s). The Select signals dialog box closes, returning you to the new
tuning-goal specification dialog box.
14-41
14 Control System Tuning
The signals you selected now appear in the list of step-response inputs in the tuning goal
dialog box.
Similarly, specify the locations at which the step response is measured to the step-
response outputs list. For example, the following configuration constrains the response to
a step input applied at theta-ref and measured at theta in the Simulink model
rct_helico.
14-42
Specify Goals for Interactive Tuning
Tip To highlight any selected signal in the Simulink model, click . To remove a signal
from the input or output list, click . When you have selected multiple signals, you can
Most tuning goals can be enforced with loops open at one or more locations in the control
system. Click Add loop opening location to list to specify such locations for the
tuning goal.
14-43
14 Control System Tuning
The tuning goal dialog box prompts you to specify other details about the tuning goal. For
example, to create a step response requirement, you provide details of the desired step
response in the Desired Response area of the Step Response Goal dialog box. Some
tuning goals have additional options in an Options section of the dialog box.
For information about the fields for specifying a particular tuning goal, click in the
tuning goal dialog box.
When you have finished specifying the tuning goal, click OK in the tuning goal dialog box.
The new tuning goal appears in the Tuning Goals section of the Data Browser. A new
figure opens displaying a graphical representation of the tuning goal. When you tune your
control system, you can refer to this figure to evaluate graphically how closely the tuned
system satisfies the tuning goal.
14-44
Specify Goals for Interactive Tuning
Tip To edit the specifications of the tuning goal, double-click the tuning goal in the Data
Browser.
When you have saved your tuning goal, click New Goal to create additional tuning
goals.
When you are ready to tune your control system, click Manage Goals to select
which tuning goals are active for tuning. In the Manage Tuning Goals dialog box,
14-45
14 Control System Tuning
Active is checked by default for any new goals. Uncheck Active for any tuning goal that
you do not want enforced.
You can also designate one or more tuning goals as Hard goals. Control System Tuner
attempts to satisfy hard requirements, and comes as close as possible to satisfying
remaining (soft) requirements subject to the hard constraints. By default, new goals are
designated soft goals. Check Hard for any goal to designate it a hard goal.
For example, if you tune with the following configuration, Control System Tuner optimizes
StepRespGoal1, subject to MarginsGoal1. The tuning goal PolesGoal1 is ignored.
Deactivating tuning goals or designating some goals as soft requirements can be useful
when investigating the tradeoffs between different tuning requirements. For example, if
you do not obtain satisfactory performance with all your tuning goals active and hard, you
might try another design in which less crucial goals are designated as soft or deactivated
entirely.
See Also
Related Examples
• “Manage Tuning Goals” on page 14-179
14-46
See Also
• “Quick Loop Tuning of Feedback Loops in Control System Tuner” on page 14-48
• “Create Response Plots in Control System Tuner” on page 14-198
14-47
14 Control System Tuning
This example demonstrates how the Quick Loop Tuning option of Control System Tuner
generates tuning goals from your crossover frequency and gain and phase margin
specifications. This option lets you quickly set up SISO or MIMO feedback loops for
tuning using a loop-shaping approach. The example also shows how to add further tuning
requirements to the control system after using the Quick Loop Tuning option.
Quick Loop Tuning is the Control System Tuner equivalent of the looptune command.
open_system('rct_distillation')
This model represents a distillation column, captured in the two-input, two-output plant G.
The tunable elements are the decoupling gain matrix DM, and the two PI controllers, PI_L
and PI_V. (For more information about this model, see “Decoupling Controller for a
Distillation Column” on page 17-331.)
14-48
Quick Loop Tuning of Feedback Loops in Control System Tuner
Suppose your goal is to tune the MIMO feedback loop between r and y to a bandwidth
between 0.1 and 0.5 rad/s. Suppose you also require a gain margin of 7 dB and a phase
margin of 45 degrees. You can use the Quick Loop Tuning option to quickly configure
Control System Tuner for these goals.
In the Simulink model editor, open Control System Tuner by selecting Analysis >
Control Design > Control System Tuner.
Designate the blocks you want to tune. In the Tuning tab of Control System Tuner, click
Select Blocks. In the Select tuned blocks dialog box, click Add blocks. Then, select
DM, PI_L, and PI_V for tuning. (For more information about selecting tuned blocks, see
“Specify Blocks to Tune in Control System Tuner” on page 14-24.)
The model is now ready to tune to the target bandwidth and stability margins.
In the Tuning tab, select New Goal > Quick Loop Tuning.
For Quick Loop Tuning, you need to identify the actuator signals and sensor signals that
separate the plant portion of the control system from the controller, which for the purpose
of Quick Loop Tuning is the rest of the control system. The actuator signals are the
controller outputs that drive the plant, or the plant inputs. The sensor signals are the
measurements of plant output that feed back into the controller. In this control system,
14-49
14 Control System Tuning
the actuator signals are represented by the vector signal u, and the sensor signals by the
vector signal y.
In the Quick Loop Tuning dialog box, under Specify actuator signals (controls), add
the actuator signal, u. Similarly, under Specify sensor signals (measurements), add
the sensor signal, y (For more information about specifying signals for tuning, see
“Specify Goals for Interactive Tuning” on page 14-39.)
Under Desired Goals, in the Target gain crossover region field, enter the target
bandwidth range, [0.1 0.5]. Enter the desired gain margin and phase margin in the
corresponding fields.
14-50
Quick Loop Tuning of Feedback Loops in Control System Tuner
14-51
14 Control System Tuning
Click OK. Control System Tuner automatically generates tuning goals that capture the
desired goals you entered in the dialog box.
In this example, Control System Tuner creates a Loop Shape Goal and a Margins Goal. If
you had changed the pole-location settings in the Quick Loop Tuning dialog box, a Poles
goal would also have been created.
14-52
Quick Loop Tuning of Feedback Loops in Control System Tuner
You can double-click the tuning goals to examine their parameters, which are
automatically computed and populated. You can also examine the graphical
representations of the tuning goals. In the Tuning tab, examine the
LoopTuning1_LoopShapeGoal plot.
14-53
14 Control System Tuning
The target crossover range is expressed as a Loop Shape goal with an integrator open-
loop gain profile. The shaded areas of the graph show that the permitted crossover range
is [0.1 0.5] rad/s, as you specified in the Quick Loop Tuning dialog box.
Click Tune to tune the model to meet the automatically-created tuning goals. In the
tuning goal plots, you can see that the requirements are satisfied.
14-54
Quick Loop Tuning of Feedback Loops in Control System Tuner
To create additional plots for examining other system responses, see “Create Response
Plots in Control System Tuner” on page 14-198.
If you want to change your design requirements after using Quick Loop Tuning, you can
edit the automatically-created tuning goals and tune the model again. You can also create
additional tuning goals.
For example, add a requirement that limits the response to a disturbance applied at the
plant inputs. Limit the response to a step command at dL and dV at the outputs, y, to be
well damped, to settle in less than 20 seconds, and not exceed 4 in amplitude. Select New
Goal > Rejection of step disturbances and enter appropriate values in the Step
Rejection Goal dialog box. (For more information about creating tuning goals, see
“Specify Goals for Interactive Tuning” on page 14-39.)
14-55
14 Control System Tuning
14-56
See Also
You can now retune the model to meet all these tuning goals.
See Also
looptune (for slTuner)
Related Examples
• “Specify Operating Points for Tuning in Control System Tuner” on page 14-15
• “Manage Tuning Goals” on page 14-179
• “Setup for Tuning Control System Modeled in MATLAB” on page 14-35
14-57
14 Control System Tuning
Purpose
Tune SISO or MIMO feedback loops using a loop-shaping approach in Control System
Tuner.
Description
Quick Loop Tuning lets you tune your system to meet open-loop gain crossover and
stability margin requirements without explicitly creating tuning goals that capture these
requirements. You specify the feedback loop whose open-loop gain you want to shape by
designating the actuator signals (controls) and sensor signals (measurements) that form
the loop. Actuator signals are the signals that drive the plant. The sensor signals are the
plant outputs that feed back into the controller.
You enter the target loop bandwidth and desired gain and phase margins. You can also
specify constraints on pole locations of the tuned system, to eliminate fast dynamics.
Control System Tuner automatically creates Tuning Goals that capture your specifications
and ensure integral action at frequencies below the target loop bandwidth.
Creation
In the Tuning tab of Control System Tuner, select New Goal > Quick Loop Tuning to
specify loop-shaping requirements.
Command-Line Equivalent
When tuning control systems at the command line, use looptune (for slTuner) or
looptune for tuning feedback loops using a loop-shaping approach.
14-58
Quick Loop Tuning
Designate one or more signals in your model as actuator signals. These are the input
signals that drive the plant. To tune a SISO feedback loop, select a single-valued input
signal. To tune MIMO loop, select multiple signals or a vector-valued signal.
• Specify sensor signals (measurements)
Designate one or more signals in your model as sensor signals. These are the plant
outputs that provide feedback into the controller. To tune a SISO feedback loop, select
a single-valued input signal. To tune MIMO loop, select multiple signals or a vector-
valued signal.
• Compute the response with the following loops open
Designate additional locations at which to open feedback loops for the purpose of
tuning the loop defined by the control and measurement signals.
Quick Loop Tuning tunes the open-loop response of the loop defined by the control and
measurement signals. If you want your specifications for that loop to apply with other
feedback loops in the system opened, specify loop-opening locations in this section of
the dialog box. For example, if you are tuning a cascaded-loop control system with an
inner loop and an outer loop, you might want to tune the inner loop with the outer loop
open.
Tip To highlight any selected signal in the Simulink model, click . To remove a signal
from the input or output list, click . When you have selected multiple signals, you can
reorder them using and . For more information on how to specify signal locations
for a tuning goal, see “Specify Goals for Interactive Tuning” on page 14-39.
Desired Goals
Use this section of the dialog box to specify desired characteristics of the tuned system.
Control System Tuner converts these into Loop Shape, Margin, and Poles goals.
Specify a frequency range in which the open-loop gain should cross 0 dB. Specify the
frequency range as a row vector of the form [min,max], expressed in frequency units
of your model. Alternatively, if you specify a single target frequency, wc, the target
range is taken as [wc/10^0.1,wc*10^0.1], or wc ± 0.1 decade.
14-59
14 Control System Tuning
Specify the desired gain margin in decibels. For MIMO control system, the gain
margin is the multiloop disk margin. See loopmargin for information about multiloop
disk margins.
• Phase margin (degrees)
Specify the desired phase margin in degrees. For MIMO control system, the phase
margin is the multiloop disk margin. See loopmargin for information about multiloop
disk margins.
• Keep poles inside the following region
Specify minimum decay rate and maximum natural frequency for the closed-loop poles
of the tuned system. While the other Quick Loop Tuning options specify characteristics
of the open-loop response, these specifications apply to the closed-loop dynamics.
The minimum decay rate you enter constrains the closed-loop pole locations to:
The maximum frequency you enter constrains the closed-loop poles to satisfy |s|
< maxfreq for continuous time, or |log(z)| < maxfreq*Ts for discrete-time
systems with sample time Ts. This constraint prevents fast dynamics in the closed-loop
system.
Options
Use this section of the dialog box to specify additional characteristics.
• Apply goal to
Use this option when tuning multiple models at once, such as an array of models
obtained by linearizing a Simulink model at different operating points or block-
parameter values. By default, active tuning goals are enforced for all models. To
enforce a tuning requirement for a subset of models in an array, select Only Models.
Then, enter the array indices of the models for which the goal is enforced. For
example, suppose you want to apply the tuning goal to the second, third, and fourth
models in a model array. To restrict enforcement of the requirement, enter 2:4 in the
Only Models text box.
14-60
See Also
For more information about tuning for multiple models, see “Robust Tuning
Approaches” (Robust Control Toolbox).
Algorithms
Control System Tuner uses looptuneSetup (for slTuner) or looptuneSetup to
convert Quick Loop Tuning specifications into tuning goals.
See Also
Related Examples
• “Quick Loop Tuning of Feedback Loops in Control System Tuner” on page 14-48
• “Specify Goals for Interactive Tuning” on page 14-39
• “Visualize Tuning Goals” on page 14-189
• “Manage Tuning Goals” on page 14-179
14-61
14 Control System Tuning
Purpose
Make the step response from specified inputs to specified outputs closely match a target
response, when using Control System Tuner.
Description
Step Tracking Goal constrains the step response between the specified signal locations to
match the step response of a stable reference system. The constraint is satisfied when the
relative difference between the tuned and target responses falls within the tolerance you
specify. You can use this goal to constrain a SISO or MIMO response of your control
system.
You can specify the reference system for the target step response in terms of first-order
system characteristics (time constant) or second-order system characteristics (natural
frequency and percent overshoot). Alternatively, you can specify a custom reference
system as a numeric LTI model.
14-62
Step Tracking Goal
Creation
In the Tuning tab of Control System Tuner, select New Goal > Tracking of step
commands to create a Step Tracking Goal.
Command-Line Equivalent
Select one or more signal locations in your model at which to apply the step input. To
constrain a SISO response, select a single-valued input signal. For example, to
constrain the step response from a location named 'u' to a location named 'y', click
Add signal to list and select 'u'. To constrain a MIMO response, select multiple
signals or a vector-valued signal.
• Specify step-response outputs
Select one or more signal locations in your model at which to measure the response to
the step input. To constrain a SISO response, select a single-valued output signal. For
example, to constrain the step response from a location named 'u' to a location
named 'y', click Add signal to list and select 'y'. To constrain a MIMO
response, select multiple signals or a vector-valued signal. For MIMO systems, the
number of outputs must equal the number of outputs.
• Compute step response with the following loops open
Select one or more signal locations in your model at which to open a feedback loop for
the purpose of evaluating this tuning goal. The tuning goal is evaluated against the
open-loop configuration created by opening feedback loops at the locations you
identify. For example, to evaluate the tuning goal with an opening at a location named
'x', click Add signal to list and select 'x'.
14-63
14 Control System Tuning
Tip To highlight any selected signal in the Simulink model, click . To remove a signal
from the input or output list, click . When you have selected multiple signals, you can
reorder them using and . For more information on how to specify signal locations
for a tuning goal, see “Specify Goals for Interactive Tuning” on page 14-39.
Desired Response
Use this section of the dialog box to specify the shape of the desired step response.
• First-order characteristics
Specify the desired step response (the reference model Href) as a first-order response
with time constant τ:
1 /t
H ref = .
s +1 / t
Enter the desired value for τ in the Time Constant text box. Specify τ in the time
units of your model.
• Second-order characteristics
Specify the desired step response as a second-order response with time constant τ,
and natural frequency 1/τ.
Enter the desired value for τ in the Time Constant text box. Specify τ in the time
units of your model.
(1 / t ) 2
H ref = .
2
s2 + 2 ( z / t ) s + (1 / t )
14-64
Step Tracking Goal
Specify the reference system for the desired step response as a dynamic system
model, such as a tf, zpk, or ss model.
Enter the name of the reference model in the MATLAB workspace in the LTI model to
match text field. Alternatively, enter a command to create a suitable reference model,
such as tf(1,[1 1.414 1]).
The reference model must be stable and must have DC gain of 1 (zero steady-state
error). The model can be continuous or discrete. If the model is discrete, it can include
time delays which are treated as poles at z = 0.
The reference model can be MIMO, provided that it is square and that its DC singular
value (sigma) is 1. Then number of inputs and outputs of the reference model must
match the dimensions of the inputs and outputs specified for the step response goal.
For best results, the reference model should also include intrinsic system
characteristics such as non-minimum-phase zeros (undershoot).
If your selected inputs and outputs define a MIMO system and you apply a SISO reference
system, the software attempts to match the diagonal channels of the MIMO system. In
that case, cross-couplings tend to be minimized.
Options
Use this section of the dialog box to specify additional characteristics of the step response
goal.
Specify the relative matching error between the actual (tuned) step response and the
target step response. Increase this value to loosen the matching tolerance. The
relative matching error, erel, is defined as:
y ( t ) - yref ( t )
erel = 2.
1 - yref ( t )
2
y(t) – yref(t) is the response mismatch, and 1 – yref(t) is the step-tracking error of the
target model. ◊ 2
denotes the signal energy (2-norm).
14-65
14 Control System Tuning
For a MIMO tuning goal, when the choice of units results in a mix of small and large
signals in different channels of the response, this option allows you to specify the
relative amplitude of each entry in the vector-valued step input. This information is
used to scale the off-diagonal terms in the transfer function from reference to tracking
error. This scaling ensures that cross-couplings are measured relative to the amplitude
of each reference signal.
For example, suppose that tuning goal is that outputs 'y1' and 'y2' track
reference signals 'r1'and 'r2'. Suppose further that you require the outputs to
track the references with less than 10% cross-coupling. If r1 and r2 have comparable
amplitudes, then it is sufficient to keep the gains from r1 to y2 and r2 and y1 below
0.1. However, if r1 is 100 times larger than r2, the gain from r1 to y2 must be less
than 0.001 to ensure that r1 changes y2 by less than 10% of the r2 target. To ensure
this result, set Adjust for step amplitude to Yes. Then, enter [100,1] in the
Amplitudes of step commands text box. This tells Control System Tuner to take into
account that the first reference signal is 100 times greater than the second reference
signal.
Use this option when tuning multiple models at once, such as an array of models
obtained by linearizing a Simulink model at different operating points or block-
parameter values. By default, active tuning goals are enforced for all models. To
enforce a tuning requirement for a subset of models in an array, select Only Models.
Then, enter the array indices of the models for which the goal is enforced. For
example, suppose you want to apply the tuning goal to the second, third, and fourth
models in a model array. To restrict enforcement of the requirement, enter 2:4 in the
Only Models text box.
For more information about tuning for multiple models, see “Robust Tuning
Approaches” (Robust Control Toolbox).
Algorithms
When you tune a control system, the software converts each tuning goal into a normalized
scalar value f(x). Here, x is the vector of free (tunable) parameters in the control system.
The software then adjusts the parameter values to minimize f(x) or to drive f(x) below 1 if
the tuning goal is a hard constraint.
14-66
See Also
1
s
(
T ( s, x) - H ref ( s ) )
f (x) = 2.
1
erel
s
(Href ( s) - I )
2
T(s,x) is the closed-loop transfer function between the specified inputs and outputs,
evaluated with parameter values x. Href(s) is the reference model. erel is the relative error
This tuning goal also imposes an implicit stability constraint on the closed-loop transfer
function between the specified inputs to outputs, evaluated with loops opened at the
specified loop-opening locations. The dynamics affected by this implicit constraint are the
stabilized dynamics for this tuning goal. The Minimum decay rate and Maximum
natural frequency tuning options control the lower and upper bounds on these implicitly
constrained dynamics. If the optimization fails to meet the default bounds, or if the
default bounds conflict with other requirements, on the Tuning tab, use Tuning Options
to change the defaults.
See Also
Related Examples
• “Specify Goals for Interactive Tuning” on page 14-39
• “Manage Tuning Goals” on page 14-179
• “Visualize Tuning Goals” on page 14-189
14-67
14 Control System Tuning
Description
Use Step Rejection Goal to specify how a step disturbance injected at a specified
location in your control system affects the signal at a specified output location.
You can specify the desired response in time-domain terms of peak value, settling time,
and damping ratio. Control System Tuner attempts to make the actual rejection at least as
good as the desired response. Alternatively, you can specify the response as a stable
reference model having DC-gain. In that case, the tuning goal is to reject the disturbance
as well as or better than the reference model.
14-68
Step Rejection Goal
When you create a tuning goal in Control System Tuner, a tuning-goal plot is generated.
The dotted line shows the target step response you specify. The solid line is the current
corresponding response of your system.
Creation
In the Tuning tab of Control System Tuner, select New Goal > Rejection of step
disturbance to create a Step Rejection Goal.
Command-Line Equivalent
Select one or more signal locations in your model at which to apply the input. To
constrain a SISO response, select a single-valued input signal. For example, to
constrain the step-disturbance response from a location named 'u' to a location
named 'y', click Add signal to list and select 'u'. To constrain a MIMO
response, select multiple signals or a vector-valued signal.
• Specify step response outputs
Select one or more signal locations in your model at which to measure the response to
the step disturbance. To constrain a SISO response, select a single-valued output
signal. For example, to constrain the transient response from a location named 'u' to
a location named 'y', click Add signal to list and select 'y'. To constrain a
MIMO response, select multiple signals or a vector-valued signal. For MIMO systems,
the number of outputs must equal the number of outputs.
• Compute the response with the following loops open
Select one or more signal locations in your model at which to open a feedback loop for
the purpose of evaluating this tuning goal. The tuning goal is evaluated against the
open-loop configuration created by opening feedback loops at the locations you
14-69
14 Control System Tuning
identify. For example, to evaluate the tuning goal with an opening at a location named
'x', click Add signal to list and select 'x'.
Tip To highlight any selected signal in the Simulink model, click . To remove a signal
from the input or output list, click . When you have selected multiple signals, you can
reorder them using and . For more information on how to specify signal locations
for a tuning goal, see “Specify Goals for Interactive Tuning” on page 14-39.
• Response Characteristics
Enter the name of the reference model in the MATLAB workspace in the Reference
Model text field. Alternatively, enter a command to create a suitable reference model,
such as tf([1 0],[1 1.414 1]).
The reference model must be stable and must have zero DC gain. The model can be
continuous or discrete. If the model is discrete, it can include time delays which are
treated as poles at z = 0.
For best results, the reference model and the open-loop response from the disturbance
to the output should have similar gains at the frequency where the reference model
gain peaks.
14-70
Step Rejection Goal
Options
Use this section of the dialog box to specify additional characteristics of the step rejection
goal.
• Adjust for amplitude of input signals and Adjust for amplitude of output
signals
For a MIMO tuning goal, when the choice of units results in a mix of small and large
signals in different channels of the response, this option allows you to specify the
relative amplitude of each entry in the vector-valued signals. This information is used
to scale the off-diagonal terms in the transfer function from the tuning goal inputs to
outputs. This scaling ensures that cross-couplings are measured relative to the
amplitude of each reference signal.
When these options are set to No, the closed-loop transfer function being constrained
is not scaled for relative signal amplitudes. When the choice of units results in a mix of
small and large signals, using an unscaled transfer function can lead to poor tuning
results. Set the option to Yes to provide the relative amplitudes of the input signals
and output signals of your transfer function.
For example, suppose the tuning goal constrains a 2-input, 2-output transfer function.
Suppose further that second input signal to the transfer function tends to be about
100 times greater than the first signal. In that case, select Yes and enter [1,100] in
the Amplitudes of input signals text box.
Adjusting signal amplitude causes the tuning goal to be evaluated on the scaled
transfer function Do–1T(s)Di, where T(s) is the unscaled transfer function. Do and Di are
diagonal matrices with the Amplitudes of output signals and Amplitudes of input
signals values on the diagonal, respectively.
Use this option when tuning multiple models at once, such as an array of models
obtained by linearizing a Simulink model at different operating points or block-
parameter values. By default, active tuning goals are enforced for all models. To
enforce a tuning requirement for a subset of models in an array, select Only Models.
Then, enter the array indices of the models for which the goal is enforced. For
example, suppose you want to apply the tuning goal to the second, third, and fourth
14-71
14 Control System Tuning
models in a model array. To restrict enforcement of the requirement, enter 2:4 in the
Only Models text box.
For more information about tuning for multiple models, see “Robust Tuning
Approaches” (Robust Control Toolbox).
Algorithms
Evaluating Tuning Goals
When you tune a control system, the software converts each tuning goal into a normalized
scalar value f(x). Here, x is the vector of free (tunable) parameters in the control system.
The software then adjusts the parameter values to minimize f(x) or to drive f(x) below 1 if
the tuning requirement is a hard constraint.
Step Rejection Goal aims to keep the gain from disturbance to output below the gain of
the reference model. The scalar value of the requirement f(x) is given by:
f ( x ) = WF ( s ) Tdy ( s, x ) ,
•
or its discrete-time equivalent. Here, Tdy(s,x) is the closed-loop transfer function of the
Implicit Constraints
This tuning goal also imposes an implicit stability constraint on the closed-loop transfer
function between the specified inputs to outputs, evaluated with loops opened at the
specified loop-opening locations. The dynamics affected by this implicit constraint are the
stabilized dynamics for this tuning goal. The Minimum decay rate and Maximum
natural frequency tuning options control the lower and upper bounds on these implicitly
14-72
See Also
constrained dynamics. If the optimization fails to meet the default bounds, or if the
default bounds conflict with other requirements, on the Tuning tab, use Tuning Options
to change the defaults.
See Also
Related Examples
• “Specify Goals for Interactive Tuning” on page 14-39
• “Manage Tuning Goals” on page 14-179
• “Visualize Tuning Goals” on page 14-189
14-73
14 Control System Tuning
Transient Goal
Purpose
Shape how the closed-loop system responds to a specific input signal when using Control
System Tuner. Use a reference model to specify the desired transient response.
Description
Transient Goal constrains the transient response from specified input locations to
specified output locations. This requirement specifies that the transient response closely
match the response of a reference model. The constraint is satisfied when the relative
difference between the tuned and target responses falls within the tolerance you specify.
You can constrain the response to an impulse, step, or ramp input signal. You can also
constrain the response to an input signal that is given by the impulse response of an input
filter you specify.
14-74
Transient Goal
Creation
In the Tuning tab of Control System Tuner, select New Goal > Transient response
matching to create a Transient Goal.
Command-Line Equivalent
Response Selection
Use this section of the dialog box to specify input, output, and loop-opening locations for
evaluating the tuning goal.
Select one or more signal locations in your model at which to apply the input. To
constrain a SISO response, select a single-valued input signal. For example, to
constrain the transient response from a location named 'u' to a location named 'y',
click Add signal to list and select 'u'. To constrain a MIMO response, select
multiple signals or a vector-valued signal.
• Specify response outputs
Select one or more signal locations in your model at which to measure the transient
response. To constrain a SISO response, select a single-valued output signal. For
example, to constrain the transient response from a location named 'u' to a location
named 'y', click Add signal to list and select 'y'. To constrain a MIMO
response, select multiple signals or a vector-valued signal. For MIMO systems, the
number of outputs must equal the number of outputs.
• Compute the response with the following loops open
Select one or more signal locations in your model at which to open a feedback loop for
the purpose of evaluating this tuning goal. The tuning goal is evaluated against the
open-loop configuration created by opening feedback loops at the locations you
identify. For example, to evaluate the tuning goal with an opening at a location named
'x', click Add signal to list and select 'x'.
14-75
14 Control System Tuning
Tip To highlight any selected signal in the Simulink model, click . To remove a signal
from the input or output list, click . When you have selected multiple signals, you can
reorder them using and . For more information on how to specify signal locations
for a tuning goal, see “Specify Goals for Interactive Tuning” on page 14-39.
This transfer function represents the Laplace transform of the desired custom input
signal. For example, to constrain the transient response to a unit-amplitude sine wave
of frequency w, enter tf(w,[1,0,w^2]). This transfer function is the Laplace
transform of sin(wt).
The transfer function you enter must be continuous, and can have no poles in the open
right-half plane. The series connection of this transfer function with the reference
system for the desired transient response must have no feedthrough term.
Enter the name of the reference model in the MATLAB workspace in the Reference
Model field. Alternatively, enter a command to create a suitable reference model, such as
14-76
Transient Goal
tf(1,[1 1.414 1]). The reference model must be stable, and the series connection of
the reference model with the input shaping filter must have no feedthrough term.
Options
Use this section of the dialog box to specify additional characteristics of the transient
response goal.
Specify the relative matching error between the actual (tuned) transient response and
the target response. Increase this value to loosen the matching tolerance. The relative
matching error, erel, is defined as:
y ( t ) - yref ( t )
gap = 2 .
yref ( tr) ( t)
2
y(t) – yref(t) is the response mismatch, and 1 – yref(tr)(t) is the transient portion of yref
(deviation from steady-state value or trajectory). ◊ 2 denotes the signal energy (2-
norm). The gap can be understood as the ratio of the root-mean-square (RMS) of the
mismatch to the RMS of the reference transient.
• Adjust for amplitude of input signals and Adjust for amplitude of output
signals
For a MIMO tuning goal, when the choice of units results in a mix of small and large
signals in different channels of the response, this option allows you to specify the
relative amplitude of each entry in the vector-valued signals. This information is used
to scale the off-diagonal terms in the transfer function from the tuning goal inputs to
outputs. This scaling ensures that cross-couplings are measured relative to the
amplitude of each reference signal.
When these options are set to No, the closed-loop transfer function being constrained
is not scaled for relative signal amplitudes. When the choice of units results in a mix of
small and large signals, using an unscaled transfer function can lead to poor tuning
results. Set the option to Yes to provide the relative amplitudes of the input signals
and output signals of your transfer function.
For example, suppose the tuning goal constrains a 2-input, 2-output transfer function.
Suppose further that second input signal to the transfer function tends to be about
14-77
14 Control System Tuning
100 times greater than the first signal. In that case, select Yes and enter [1,100] in
the Amplitudes of input signals text box.
Adjusting signal amplitude causes the tuning goal to be evaluated on the scaled
transfer function Do–1T(s)Di, where T(s) is the unscaled transfer function. Do and Di are
diagonal matrices with the Amplitudes of output signals and Amplitudes of input
signals values on the diagonal, respectively.
Use this option when tuning multiple models at once, such as an array of models
obtained by linearizing a Simulink model at different operating points or block-
parameter values. By default, active tuning goals are enforced for all models. To
enforce a tuning requirement for a subset of models in an array, select Only Models.
Then, enter the array indices of the models for which the goal is enforced. For
example, suppose you want to apply the tuning goal to the second, third, and fourth
models in a model array. To restrict enforcement of the requirement, enter 2:4 in the
Only Models text box.
For more information about tuning for multiple models, see “Robust Tuning
Approaches” (Robust Control Toolbox).
Tips
• When you use this requirement to tune a control system, Control System Tuner
attempts to enforce zero feedthrough (D = 0) on the transfer that the requirement
constrains. Zero feedthrough is imposed because the H2 norm, and therefore the value
of the tuning goal (see “Algorithms” on page 14-79), is infinite for continuous-time
systems with nonzero feedthrough.
Control System Tuner enforces zero feedthrough by fixing to zero all tunable
parameters that contribute to the feedthrough term. Control System Tuner returns an
error when fixing these tunable parameters is insufficient to enforce zero feedthrough.
In such cases, you must modify the requirement or the control structure, or manually
fix some tunable parameters of your system to values that eliminate the feedthrough
term.
When the constrained transfer function has several tunable blocks in series, the
software’s approach of zeroing all parameters that contribute to the overall
feedthrough might be conservative. In that case, it is sufficient to zero the feedthrough
14-78
Transient Goal
term of one of the blocks. If you want to control which block has feedthrough fixed to
zero, you can manually fix the feedthrough of the tuned block of your choice.
To fix parameters of tunable blocks to specified values, see “View and Change Block
Parameterization in Control System Tuner” on page 14-26.
• This tuning goal also imposes an implicit stability constraint on the closed-loop
transfer function between the specified inputs to outputs, evaluated with loops opened
at the specified loop-opening locations. The dynamics affected by this implicit
constraint are the stabilized dynamics for this tuning goal. The Minimum decay rate
and Maximum natural frequency tuning options control the lower and upper
bounds on these implicitly constrained dynamics. If the optimization fails to meet the
default bounds, or if the default bounds conflict with other requirements, on the
Tuning tab, use Tuning Options to change the defaults.
Algorithms
When you tune a control system, the software converts each tuning goal into a normalized
scalar value f(x). Here, x is the vector of free (tunable) parameters in the control system.
The software then adjusts the parameter values to minimize f(x) or to drive f(x) below 1 if
the tuning requirement is a hard constraint.
For Transient Goal, f(x) is based upon the relative gap between the tuned response and
the target response:
y ( t ) - yref ( t )
gap = 2 .
yref ( tr) ( t)
2
y(t) – yref(t) is the response mismatch, and 1 – yref(tr)(t) is the transient portion of yref
(deviation from steady-state value or trajectory). ◊ 2 denotes the signal energy (2-norm).
The gap can be understood as the ratio of the root-mean-square (RMS) of the mismatch to
the RMS of the reference transient.
14-79
14 Control System Tuning
See Also
Related Examples
• “Specify Goals for Interactive Tuning” on page 14-39
• “Manage Tuning Goals” on page 14-179
• “Visualize Tuning Goals” on page 14-189
14-80
LQR/LQG Goal
LQR/LQG Goal
Purpose
Minimize or limit Linear-Quadratic-Gaussian (LQG) cost in response to white-noise inputs,
when using Control System Tuner.
Description
LQR/LQG Goal specifies a tuning requirement for quantifying control performance as an
LQG cost. It is applicable to any control structure, not just the classical observer
structure of optimal LQG control.
J = E(z(t)′ QZ z(t)).
z(t) is the system response to a white noise input vector w(t). The covariance of w(t) is
given by:
E(w(t)w(t)′) = QW.
The vector w(t) typically consists of external inputs to the system such as noise,
disturbances, or command. The vector z(t) includes all the system variables that
characterize performance, such as control signals, system states, and outputs. E(x)
denotes the expected value of the stochastic variable x.
Ê1 T ˆ
J = lim E Á
T Æ• Ë T
Ú0 z (t )’ QZ z (t ) dt ˜¯ .
Creation
In the Tuning tab of Control System Tuner, select New Goal > LQR/LQG objective to
create an LQR/LQG Goal.
14-81
14 Control System Tuning
Command-Line Equivalent
When tuning control systems at the command line, use TuningGoal.LQG to specify an
LQR/LQG goal.
Signal Selection
Use this section of the dialog box to specify noise input locations and performance output
locations. Also specify any locations at which to open loops for evaluating the tuning goal.
Select one or more signal locations in your model as noise inputs. To constrain a SISO
response, select a single-valued input signal. For example, to constrain the LQG cost
for a noise input 'u' and performance output 'y', click Add signal to list and
select 'u'. To constrain the LQG cost for a MIMO response, select multiple signals or
a vector-valued signal.
• Specify performance outputs (z)
Select one or more signal locations in your model at which to open a feedback loop for
the purpose of evaluating this tuning goal. The tuning goal is evaluated against the
open-loop configuration created by opening feedback loops at the locations you
identify. For example, to evaluate the tuning goal with an opening at a location named
'x', click Add signal to list and select 'x'.
Tip To highlight any selected signal in the Simulink model, click . To remove a signal
from the input or output list, click . When you have selected multiple signals, you can
reorder them using and . For more information on how to specify signal locations
for a tuning goal, see “Specify Goals for Interactive Tuning” on page 14-39.
14-82
LQR/LQG Goal
LQG Objective
Use this section of the dialog box to specify the noise covariance and performance
weights for the LQG goal.
• Performance weight Qz
J = E(z(t)′ Qz z(t)).
When you use the LQG goal as a hard goal, the software tries to drive the cost function
J < 1. When you use it as a soft goal, the cost function J is minimized subject to any
hard goals and its value is contributed to the overall objective function. Therefore,
select Qz values to properly scale the cost function so that driving it below 1 or
minimizing it yields the performance you require.
• Noise Covariance Qw
Covariance of the white noise input vector w(t), specified as a scalar or a matrix. Use a
scalar value to specify a multiple of the identity matrix. Otherwise specify a symmetric
nonnegative definite matrix with as many rows as there are entries in the vector w(t).
A diagonal matrix means the entries of w(t) are uncorrelated.
E(w(t)w(t)′) = QW.
When you are tuning a control system in discrete time, the LQG goal assumes:
E(w[k]w[k]′) = QW/Ts.
Ts is the model sample time. This assumption ensures consistent results with tuning in
the continuous-time domain. In this assumption, w[k] is discrete-time noise obtained
by sampling continuous white noise w(t) with covariance QW. If in your system w[k] is
a truly discrete process with known covariance QWd, use the value Ts*QWd for the
QW value.
14-83
14 Control System Tuning
Options
Use this section of the dialog box to specify additional characteristics of the LQG goal.
• Apply goal to
Use this option when tuning multiple models at once, such as an array of models
obtained by linearizing a Simulink model at different operating points or block-
parameter values. By default, active tuning goals are enforced for all models. To
enforce a tuning requirement for a subset of models in an array, select Only Models.
Then, enter the array indices of the models for which the goal is enforced. For
example, suppose you want to apply the tuning goal to the second, third, and fourth
models in a model array. To restrict enforcement of the requirement, enter 2:4 in the
Only Models text box.
For more information about tuning for multiple models, see “Robust Tuning
Approaches” (Robust Control Toolbox).
Tips
When you use this requirement to tune a control system, Control System Tuner attempts
to enforce zero feedthrough (D = 0) on the transfer that the requirement constrains. Zero
feedthrough is imposed because the H2 norm, and therefore the value of the tuning goal,
is infinite for continuous-time systems with nonzero feedthrough.
Control System Tuner enforces zero feedthrough by fixing to zero all tunable parameters
that contribute to the feedthrough term. Control System Tuner returns an error when
fixing these tunable parameters is insufficient to enforce zero feedthrough. In such cases,
you must modify the requirement or the control structure, or manually fix some tunable
parameters of your system to values that eliminate the feedthrough term.
When the constrained transfer function has several tunable blocks in series, the
software’s approach of zeroing all parameters that contribute to the overall feedthrough
might be conservative. In that case, it is sufficient to zero the feedthrough term of one of
the blocks. If you want to control which block has feedthrough fixed to zero, you can
manually fix the feedthrough of the tuned block of your choice.
To fix parameters of tunable blocks to specified values, see “View and Change Block
Parameterization in Control System Tuner” on page 14-26.
14-84
See Also
Algorithms
When you tune a control system, the software converts each tuning goal into a normalized
scalar value f(x). Here, x is the vector of free (tunable) parameters in the control system.
The software then adjusts the parameter values to minimize f(x) or to drive f(x) below 1 if
the tuning goal is a hard constraint.
J = E(z(t)′ Qz z(t)).
When you use the LQG requirement as a hard goal, the software tries to drive the cost
function J < 1. When you use it as a soft goal, the cost function J is minimized subject to
any hard goals and its value is contributed to the overall objective function. Therefore,
select Qz values to properly scale the cost function so that driving it below 1 or
minimizing it yields the performance you require.
See Also
Related Examples
• “Specify Goals for Interactive Tuning” on page 14-39
• “Manage Tuning Goals” on page 14-179
14-85
14 Control System Tuning
Gain Goal
Purpose
Limit gain of a specified input/output transfer function, when using Control System Tuner.
Description
Gain Goal limits the gain from specified inputs to specified outputs. If you specify multiple
inputs and outputs, Gain Goal limits the largest singular value of the transfer matrix. (See
sigma for more information about singular values.) You can specify a constant maximum
gain at all frequencies. Alternatively, you can specify a frequency-dependent gain profile.
Use Gain Goal, for example, to enforce a custom roll-off rate in a particular frequency
band. To do so, specify a maximum gain profile in that band. You can also use Gain Goal to
enforce disturbance rejection across a particular input/output pair by constraining the
gain to be less than 1.
14-86
Gain Goal
When you create a tuning goal in Control System Tuner, a tuning-goal plot is generated.
The dotted line shows the gain profile you specify. The shaded area on the plot represents
the region in the frequency domain where the gain goal is not satisfied.
By default, Gain Goal constrains a closed-loop gain. To constrain a gain computed with
one or more loops open, specify loop-opening locations in the I/O Transfer Selection
section of the dialog box.
Creation
In the Tuning tab of Control System Tuner, select New Goal > Gain limits to create a
Gain Goal.
Command-Line Equivalent
When tuning control systems at the command line, use TuningGoal.Gain to specify a
maximum gain goal.
Select one or more signal locations in your model as inputs to the transfer function
that the tuning goal constrains. To constrain a SISO response, select a single-valued
input signal. For example, to constrain the gain from a location named 'u' to a
location named 'y', click Add signal to list and select 'u'. To constrain the
largest singular value of a MIMO response, select multiple signals or a vector-valued
signal.
• Specify output signals
Select one or more signal locations in your model as outputs of the transfer function
that the tuning goal constrains. To constrain a SISO response, select a single-valued
output signal. For example, to constrain the gain from a location named 'u' to a
location named 'y', click Add signal to list and select 'y'. To constrain the
largest singular value of a MIMO response, select multiple signals or a vector-valued
signal.
14-87
14 Control System Tuning
Select one or more signal locations in your model at which to open a feedback loop for
the purpose of evaluating this tuning goal. The tuning goal is evaluated against the
open-loop configuration created by opening feedback loops at the locations you
identify. For example, to evaluate the tuning goal with an opening at a location named
'x', click Add signal to list and select 'x'.
Tip To highlight any selected signal in the Simulink model, click . To remove a signal
from the input or output list, click . When you have selected multiple signals, you can
reorder them using and . For more information on how to specify signal locations
for a tuning goal, see “Specify Goals for Interactive Tuning” on page 14-39.
Options
Use this section of the dialog box to specify additional characteristics of the gain goal.
• Limit gain to
Enter the maximum gain in the text box. You can specify a scalar value or a frequency-
dependent gain profile. To specify a frequency-dependent gain profile, enter a SISO
numeric LTI model. For example, you can specify a smooth transfer function (tf, zpk,
or ss model). Alternatively, you can sketch a piecewise maximum gain using an frd
model. When you do so, the software automatically maps the profile to a smooth
transfer function that approximates the desired minimum disturbance rejection. For
example, to specify a gain profile that rolls off at –40dB/decade in the frequency band
from 8 to 800 rad/s, enter frd([0.8 8 800],[10 1 1e-4]).
You must specify a SISO transfer function. If you specify multiple input signals or
output signals, the gain profile applies to all I/O pairs between these signals.
If you are tuning in discrete time, you can specify the maximum gain profile as a
discrete-time model with the same sampling time as you use for tuning. If you specify
the gain profile in continuous time, the tuning software discretizes it. Specifying the
gain profile in discrete time gives you more control over the gain profile near the
Nyquist frequency.
14-88
Gain Goal
By default, the tuning goal imposes a stability requirement on the closed-loop transfer
function from the specified inputs to outputs, in addition to the gain constraint. If
stability is not required or cannot be achieved, select No to remove the stability
requirement. For example, if the gain constraint applies to an unstable open-loop
transfer function, select No.
• Enforce goal in frequency range
Limit the enforcement of the tuning goal to a particular frequency band. Specify the
frequency band as a row vector of the form [min,max], expressed in frequency units
of your model. For example, to create a tuning goal that applies only between 1 and
100 rad/s, enter [1,100]. By default, the tuning goal applies at all frequencies for
continuous time, and up to the Nyquist frequency for discrete time.
• Adjust for signal amplitude
When this option is set to No, the closed-loop transfer function being constrained is
not scaled for relative signal amplitudes. When the choice of units results in a mix of
small and large signals, using an unscaled transfer function can lead to poor tuning
results. Set the option to Yes to provide the relative amplitudes of the input signals
and output signals of your transfer function.
For example, suppose the tuning goal constrains a 2-input, 2-output transfer function.
Suppose further that second input signal to the transfer function tends to be about
100 times greater than the first signal. In that case, select Yes and enter [1,100] in
the Amplitude of input signals text box.
Adjusting signal amplitude causes the tuning goal to be evaluated on the scaled
transfer function Do–1T(s)Di, where T(s) is the unscaled transfer function. Do and Di are
diagonal matrices with the Amplitude of output signals and Amplitude of input
signals values on the diagonal, respectively.
• Apply goal to
Use this option when tuning multiple models at once, such as an array of models
obtained by linearizing a Simulink model at different operating points or block-
parameter values. By default, active tuning goals are enforced for all models. To
enforce a tuning requirement for a subset of models in an array, select Only Models.
Then, enter the array indices of the models for which the goal is enforced. For
example, suppose you want to apply the tuning goal to the second, third, and fourth
models in a model array. To restrict enforcement of the requirement, enter 2:4 in the
Only Models text box.
14-89
14 Control System Tuning
For more information about tuning for multiple models, see “Robust Tuning
Approaches” (Robust Control Toolbox).
Algorithms
Evaluating Tuning Goals
When you tune a control system, the software converts each tuning goal into a normalized
scalar value f(x). Here, x is the vector of free (tunable) parameters in the control system.
The software then adjusts the parameter values to minimize f(x) or to drive f(x) below 1 if
the tuning goal is a hard constraint.
f ( x ) = WF ( s ) Do-1 T ( s, x ) Di ,
•
or its discrete-time equivalent. Here, T(s,x) is the closed-loop transfer function between
the specified inputs and outputs, evaluated with parameter values x. Do and Di are the
The frequency weighting function WF is the regularized gain profile, derived from the
maximum gain profile you specify. The gain of WF roughly matches the inverse of the gain
profile you specify, inside the frequency band you set in the Enforce goal in frequency
range field of the tuning goal. WF is always stable and proper. Because poles of WF(s)
close to s = 0 or s = Inf might lead to poor numeric conditioning for tuning, it is not
recommended to specify maximum gain profiles with very low-frequency or very high-
frequency dynamics. For more information about regularization and its effects, see
“Visualize Tuning Goals” on page 14-189.
Implicit Constraints
This tuning goal also imposes an implicit stability constraint on the closed-loop transfer
function between the specified inputs to outputs, evaluated with loops opened at the
specified loop-opening locations. The dynamics affected by this implicit constraint are the
stabilized dynamics for this tuning goal. The Minimum decay rate and Maximum
natural frequency tuning options control the lower and upper bounds on these implicitly
constrained dynamics. If the optimization fails to meet the default bounds, or if the
14-90
See Also
default bounds conflict with other requirements, on the Tuning tab, use Tuning Options
to change the defaults.
See Also
Related Examples
• “Specify Goals for Interactive Tuning” on page 14-39
• “Manage Tuning Goals” on page 14-179
• “Visualize Tuning Goals” on page 14-189
14-91
14 Control System Tuning
Variance Goal
Purpose
Limit white-noise impact on specified output signals, when using Control System Tuner.
Description
Variance Goal imposes a noise attenuation constraint that limits the impact on specified
output signals of white noise applied at specified inputs. The noise attenuation is
measured by the ratio of the noise variance to the output variance.
For stochastic inputs with a nonuniform spectrum (colored noise), use “Weighted Variance
Goal” on page 14-124 instead.
Creation
In the Tuning tab of Control System Tuner, select New Goal > Signal variance
attenuation to create a Variance Goal.
Command-Line Equivalent
Select one or more signal locations in your model as noise inputs. To constrain a SISO
response, select a single-valued input signal. For example, to constrain the gain from a
location named 'u' to a location named 'y', click Add signal to list and select
'u'. To constrain the noise amplification of a MIMO response, select multiple signals
or a vector-valued signal.
• Specify stochastic outputs
14-92
Variance Goal
Select one or more signal locations in your model as outputs for computing response
to the noise inputs. To constrain a SISO response, select a single-valued output signal.
For example, to constrain the gain from a location named 'u' to a location named
'y', click Add signal to list and select 'y'. To constrain the noise amplification
of a MIMO response, select multiple signals or a vector-valued signal.
• Compute output variance with the following loops open
Select one or more signal locations in your model at which to open a feedback loop for
the purpose of evaluating this tuning goal. The tuning goal is evaluated against the
open-loop configuration created by opening feedback loops at the locations you
identify. For example, to evaluate the tuning goal with an opening at a location named
'x', click Add signal to list and select 'x'.
Tip To highlight any selected signal in the Simulink model, click . To remove a signal
from the input or output list, click . When you have selected multiple signals, you can
reorder them using and . For more information on how to specify signal locations
for a tuning goal, see “Specify Goals for Interactive Tuning” on page 14-39.
Options
Use this section of the dialog box to specify additional characteristics of the variance
goal.
Enter the desired noise attenuation from the specified inputs to outputs. This value
specifies the maximum ratio of noise variance to output variance.
When you tune a control system in discrete time, this requirement assumes that the
physical plant and noise process are continuous, and interprets the desired noise
attenuation as a bound on the continuous-time H2 norm. This ensures that continuous-
time and discrete-time tuning give consistent results. If the plant and noise processes
are truly discrete, and you want to bound the discrete-time H2 norm instead, multiple
the desired attenuation value by Ts . Ts is the sample time of the model you are
tuning.
14-93
14 Control System Tuning
When this option is set to No, the closed-loop transfer function being constrained is
not scaled for relative signal amplitudes. When the choice of units results in a mix of
small and large signals, using an unscaled transfer function can lead to poor tuning
results. Set the option to Yes to provide the relative amplitudes of the input signals
and output signals of your transfer function.
For example, suppose the tuning goal constrains a 2-input, 2-output transfer function.
Suppose further that second input signal to the transfer function tends to be about
100 times greater than the first signal. In that case, select Yes and enter [1,100] in
the Amplitude of input signals text box.
Adjusting signal amplitude causes the tuning goal to be evaluated on the scaled
transfer function Do–1T(s)Di, where T(s) is the unscaled transfer function. Do and Di are
diagonal matrices with the Amplitude of output signals and Amplitude of input
signals values on the diagonal, respectively.
• Apply goal to
Use this option when tuning multiple models at once, such as an array of models
obtained by linearizing a Simulink model at different operating points or block-
parameter values. By default, active tuning goals are enforced for all models. To
enforce a tuning requirement for a subset of models in an array, select Only Models.
Then, enter the array indices of the models for which the goal is enforced. For
example, suppose you want to apply the tuning goal to the second, third, and fourth
models in a model array. To restrict enforcement of the requirement, enter 2:4 in the
Only Models text box.
For more information about tuning for multiple models, see “Robust Tuning
Approaches” (Robust Control Toolbox).
Tips
• When you use this requirement to tune a control system, Control System Tuner
attempts to enforce zero feedthrough (D = 0) on the transfer that the requirement
constrains. Zero feedthrough is imposed because the H2 norm, and therefore the value
of the tuning goal (see “Algorithms” on page 14-95), is infinite for continuous-time
systems with nonzero feedthrough.
Control System Tuner enforces zero feedthrough by fixing to zero all tunable
parameters that contribute to the feedthrough term. Control System Tuner returns an
14-94
Variance Goal
error when fixing these tunable parameters is insufficient to enforce zero feedthrough.
In such cases, you must modify the requirement or the control structure, or manually
fix some tunable parameters of your system to values that eliminate the feedthrough
term.
When the constrained transfer function has several tunable blocks in series, the
software’s approach of zeroing all parameters that contribute to the overall
feedthrough might be conservative. In that case, it is sufficient to zero the feedthrough
term of one of the blocks. If you want to control which block has feedthrough fixed to
zero, you can manually fix the feedthrough of the tuned block of your choice.
To fix parameters of tunable blocks to specified values, see “View and Change Block
Parameterization in Control System Tuner” on page 14-26.
• This tuning goal also imposes an implicit stability constraint on the closed-loop
transfer function between the specified inputs to outputs, evaluated with loops opened
at the specified loop-opening locations. The dynamics affected by this implicit
constraint are the stabilized dynamics for this tuning goal. The Minimum decay rate
and Maximum natural frequency tuning options control the lower and upper
bounds on these implicitly constrained dynamics. If the optimization fails to meet the
default bounds, or if the default bounds conflict with other requirements, on the
Tuning tab, use Tuning Options to change the defaults.
Algorithms
When you tune a control system, the software converts each tuning goal into a normalized
scalar value f(x). Here, x is the vector of free (tunable) parameters in the control system.
The software then adjusts the parameter values to minimize f(x) or to drive f(x) below 1 if
the tuning goal is a hard constraint.
f ( x ) = Attenuation ◊ T ( s, x) .
2
14-95
14 Control System Tuning
Attenuation
f (x) = T ( z, x) .
Ts
2
See Also
Related Examples
• “Specify Goals for Interactive Tuning” on page 14-39
• “Manage Tuning Goals” on page 14-179
• “Visualize Tuning Goals” on page 14-189
14-96
Reference Tracking Goal
Purpose
Make specified outputs track reference inputs with prescribed performance and fidelity,
when using Control System Tuner. Limit cross-coupling in MIMO systems.
Description
Reference Tracking Goal constrains tracking between the specified signal locations. The
constraint is satisfied when the maximum relative tracking error falls below the value you
specify at all frequencies. The relative error is the gain from reference input to tracking
error as a function of frequency.
You can specify the maximum error profile directly as a function of frequency.
Alternatively, you can specify the tracking goal a target DC error, peak error, and
response time. These parameters are converted to the following transfer function that
describes the maximum frequency-domain tracking error:
( PeakError ) s + wc ( DCError )
MaxError = .
s + wc
Here, ωc is 2/(response time). The following plot illustrates these relationships for an
example set of values.
14-97
14 Control System Tuning
When you create a tuning goal in Control System Tuner, a tuning-goal plot is generated.
The dotted line shows the error profile you specify. The shaded area on the plot
represents the region in the frequency domain where the tuning goal is not satisfied.
Creation
In the Tuning tab of Control System Tuner, select New Goal > Reference Tracking to
create a Reference Tracking Goal.
Command-Line Equivalent
Response Selection
Use this section of the dialog box to specify input, output, and loop-opening locations for
evaluating the tuning goal.
Select one or more signal locations in your model as reference signals. To constrain a
SISO response, select a single-valued reference signal. For example, to constrain the
14-98
Reference Tracking Goal
response from a location named 'u' to a location named 'y', click Add signal to
list and select 'u'. To constrain a MIMO response, select multiple signals or a vector-
valued signal.
• Specify reference-tracking outputs
Select one or more signal locations in your model at which to open a feedback loop for
the purpose of evaluating this tuning goal. The tuning goal is evaluated against the
open-loop configuration created by opening feedback loops at the locations you
identify. For example, to evaluate the tuning goal with an opening at a location named
'x', click Add signal to list and select 'x'.
Tip To highlight any selected signal in the Simulink model, click . To remove a signal
from the input or output list, click . When you have selected multiple signals, you can
reorder them using and . For more information on how to specify signal locations
for a tuning goal, see “Specify Goals for Interactive Tuning” on page 14-39.
Tracking Performance
Use this section of the dialog box to specify frequency-domain constraints on the tracking
error.
Select this option to specify the tracking error in terms of response time, percent steady-
state error, and peak error across all frequencies. These parameters are converted to the
following transfer function that describes the maximum frequency-domain tracking error:
14-99
14 Control System Tuning
( PeakError ) s + wc ( DCError )
MaxError = .
s + wc
When you select this option, enter the following parameters in the text boxes:
• Response Time — Enter the target response time. The tracking bandwidth is given
by ωc = 2/Response Time. Express the target response time in the time units of your
model.
• Steady-state error (%) — Enter the maximum steady-state fractional tracking error,
expressed in percent. For MIMO tracking goals, this steady-state error applies to all
I/O pairs. The steady-state error is the DC error expressed as a percentage, DCError/
100.
• Peak error across frequency (%) — Enter the maximum fractional tracking error
across all frequencies, expressed in percent.
Select this option to specify the maximum tracking error profile as a function of
frequency.
Enter a SISO numeric LTI model in the text box. For example, you can specify a smooth
transfer function (tf, zpk, or ss model). Alternatively, you can sketch a piecewise error
profile using an frd model. When you do so, the software automatically maps the error
profile to a smooth transfer function that approximates the desired error profile. For
example, to specify a maximum error of 0.01 below about 1 rad/s, gradually rising to a
peak error of 1 at 100 rad/s, enter frd([0.01 0.01 1],[0 1 100]).
For MIMO tracking goals, this error profile applies to all I/O pairs.
If you are tuning in discrete time, you can specify the maximum error profile as a
discrete-time model with the same sampling time as you use for tuning. If you specify the
attenuation profile in continuous time, the tuning software discretizes it. Specifying the
error profile in discrete time gives you more control over the profile near the Nyquist
frequency.
Options
Use this section of the dialog box to specify additional characteristics of the tracking goal.
14-100
Reference Tracking Goal
Limit the enforcement of the tuning goal to a particular frequency band. Specify the
frequency band as a row vector of the form [min,max], expressed in frequency units
of your model. For example, to create a tuning goal that applies only between 1 and
100 rad/s, enter [1,100]. By default, the tuning goal applies at all frequencies for
continuous time, and up to the Nyquist frequency for discrete time.
• Adjust for step amplitude
For a MIMO tuning goal, when the choice of units results in a mix of small and large
signals in different channels of the response, this option allows you to specify the
relative amplitude of each entry in the vector-valued step input. This information is
used to scale the off-diagonal terms in the transfer function from reference to tracking
error. This scaling ensures that cross-couplings are measured relative to the amplitude
of each reference signal.
For example, suppose that tuning goal is that outputs 'y1' and 'y2' track
reference signals 'r1'and 'r2'. Suppose further that you require the outputs to
track the references with less than 10% cross-coupling. If r1 and r2 have comparable
amplitudes, then it is sufficient to keep the gains from r1 to y2 and r2 and y1 below
0.1. However, if r1 is 100 times larger than r2, the gain from r1 to y2 must be less
than 0.001 to ensure that r1 changes y2 by less than 10% of the r2 target. To ensure
this result, set Adjust for step amplitude to Yes. Then, enter [100,1] in the
Amplitudes of step commands text box. This tells Control System Tuner to take into
account that the first reference signal is 100 times greater than the second reference
signal.
Use this option when tuning multiple models at once, such as an array of models
obtained by linearizing a Simulink model at different operating points or block-
parameter values. By default, active tuning goals are enforced for all models. To
enforce a tuning requirement for a subset of models in an array, select Only Models.
Then, enter the array indices of the models for which the goal is enforced. For
example, suppose you want to apply the tuning goal to the second, third, and fourth
models in a model array. To restrict enforcement of the requirement, enter 2:4 in the
Only Models text box.
For more information about tuning for multiple models, see “Robust Tuning
Approaches” (Robust Control Toolbox).
14-101
14 Control System Tuning
Algorithms
Evaluating Tuning Goals
When you tune a control system, the software converts each tuning goal into a normalized
scalar value f(x). Here, x is the vector of free (tunable) parameters in the control system.
The software then adjusts the parameter values to minimize f(x) or to drive f(x) below 1 if
the tuning goal is a hard constraint.
f ( x ) = WF ( s ) ( T ( s, x ) - I ) ,
•
or its discrete-time equivalent. Here, T(s,x) is the closed-loop transfer function between
the specified inputs and outputs, and ◊ • denotes the H∞ norm (see getPeakGain). WF
is a frequency weighting function derived from the error profile you specify in the tuning
goal. The gain of WF roughly matches the inverse of the error profile for gain values
between –20 dB and 60 dB. For numerical reasons, the weighting function levels off
outside this range, unless you specify a reference model that changes slope outside this
range. This adjustment is called regularization. Because poles of WF close to s = 0 or s =
Inf might lead to poor numeric conditioning of the systune optimization problem, it is
not recommended to specify error profiles with very low-frequency or very high-frequency
dynamics. For more information about regularization and its effects, see “Visualize
Tuning Goals” on page 14-189.
Implicit Constraints
This tuning goal also imposes an implicit stability constraint on the closed-loop transfer
function between the specified inputs to outputs, evaluated with loops opened at the
specified loop-opening locations. The dynamics affected by this implicit constraint are the
stabilized dynamics for this tuning goal. The Minimum decay rate and Maximum
natural frequency tuning options control the lower and upper bounds on these implicitly
constrained dynamics. If the optimization fails to meet the default bounds, or if the
default bounds conflict with other requirements, on the Tuning tab, use Tuning Options
to change the defaults.
14-102
See Also
See Also
Related Examples
• “Specify Goals for Interactive Tuning” on page 14-39
• “Visualize Tuning Goals” on page 14-189
• “Manage Tuning Goals” on page 14-179
14-103
14 Control System Tuning
Overshoot Goal
Purpose
Limit overshoot in the step response from specified inputs to specified outputs, when
using Control System Tuner.
Description
Overshoot Goal limits the overshoot in the step response between the specified signal
locations. The constraint is satisfied when the overshoot in the tuned response is less than
the target overshoot
The software maps the maximum overshoot to a peak gain constraint, assuming second-
order system characteristics. Therefore, for tuning higher-order systems, the overshoot
constraint is only approximate. In addition, the Overshoot Goal cannot reliably reduce the
overshoot below 5%.
When you create a tuning goal in Control System Tuner, a tuning-goal plot is generated.
The shaded area on the plot represents the region in the frequency domain where the
tuning goal is not satisfied.
14-104
Overshoot Goal
Creation
In the Tuning tab of Control System Tuner, select New Goal > Maximum overshoot to
create an Overshoot Goal.
Command-Line Equivalent
Response Selection
Use this section of the dialog box to specify input, output, and loop-opening locations for
evaluating the tuning goal.
Select one or more signal locations in your model at which to apply the step input. To
constrain a SISO response, select a single-valued input signal. For example, to
constrain the step response from a location named 'u' to a location named 'y', click
Add signal to list and select 'u'. To constrain a MIMO response, select multiple
signals or a vector-valued signal.
• Specify step-response outputs
Select one or more signal locations in your model at which to measure the response to
the step input. To constrain a SISO response, select a single-valued output signal. For
example, to constrain the step response from a location named 'u' to a location
named 'y', click Add signal to list and select 'y'. To constrain a MIMO
response, select multiple signals or a vector-valued signal. For MIMO systems, the
number of outputs must equal the number of outputs.
• Evaluate overshoot with the following loops open
Select one or more signal locations in your model at which to open a feedback loop for
the purpose of evaluating this tuning goal. The tuning goal is evaluated against the
open-loop configuration created by opening feedback loops at the locations you
identify. For example, to evaluate the tuning goal with an opening at a location named
'x', click Add signal to list and select 'x'.
14-105
14 Control System Tuning
Tip To highlight any selected signal in the Simulink model, click . To remove a signal
from the input or output list, click . When you have selected multiple signals, you can
reorder them using and . For more information on how to specify signal locations
for a tuning goal, see “Specify Goals for Interactive Tuning” on page 14-39.
Options
Use this section of the dialog box to specify additional characteristics of the overshoot
goal.
• Limit % overshoot to
Enter the maximum percent overshoot. Overshoot Goal cannot reliably reduce the
overshoot below 5%
• Adjust for step amplitude
For a MIMO tuning goal, when the choice of units results in a mix of small and large
signals in different channels of the response, this option allows you to specify the
relative amplitude of each entry in the vector-valued step input. This information is
used to scale the off-diagonal terms in the transfer function from reference to tracking
error. This scaling ensures that cross-couplings are measured relative to the amplitude
of each reference signal.
For example, suppose that tuning goal is that outputs 'y1' and 'y2' track
reference signals 'r1'and 'r2'. Suppose further that you require the outputs to
track the references with less than 10% cross-coupling. If r1 and r2 have comparable
amplitudes, then it is sufficient to keep the gains from r1 to y2 and r2 and y1 below
0.1. However, if r1 is 100 times larger than r2, the gain from r1 to y2 must be less
than 0.001 to ensure that r1 changes y2 by less than 10% of the r2 target. To ensure
this result, set Adjust for step amplitude to Yes. Then, enter [100,1] in the
Amplitudes of step commands text box. This tells Control System Tuner to take into
account that the first reference signal is 100 times greater than the second reference
signal.
14-106
Overshoot Goal
Use this option when tuning multiple models at once, such as an array of models
obtained by linearizing a Simulink model at different operating points or block-
parameter values. By default, active tuning goals are enforced for all models. To
enforce a tuning requirement for a subset of models in an array, select Only Models.
Then, enter the array indices of the models for which the goal is enforced. For
example, suppose you want to apply the tuning goal to the second, third, and fourth
models in a model array. To restrict enforcement of the requirement, enter 2:4 in the
Only Models text box.
For more information about tuning for multiple models, see “Robust Tuning
Approaches” (Robust Control Toolbox).
Algorithms
When you tune a control system, the software converts each tuning goal into a normalized
scalar value f(x). Here, x is the vector of free (tunable) parameters in the control system.
The software then adjusts the parameter values to minimize f(x) or to drive f(x) below 1 if
the tuning goal is a hard constraint.
For Overshoot Goal, f(x) reflects the relative satisfaction or violation of the goal. The
percent deviation from f(x) = 1 roughly corresponds to the percent deviation from the
specified overshoot target. For example, f(x) = 1.2 means the actual overshoot exceeds
the target by roughly 20%, and f(x) = 0.8 means the actual overshoot is about 20% less
than the target.
Overshoot Goal uses T • as a proxy for the overshoot, based on second-order model
characteristics. Here, T is the closed-loop transfer function that the requirement
This tuning goal also imposes an implicit stability constraint on the closed-loop transfer
function between the specified inputs to outputs, evaluated with loops opened at the
specified loop-opening locations. The dynamics affected by this implicit constraint are the
stabilized dynamics for this tuning goal. The Minimum decay rate and Maximum
natural frequency tuning options control the lower and upper bounds on these implicitly
constrained dynamics. If the optimization fails to meet the default bounds, or if the
default bounds conflict with other requirements, on the Tuning tab, use Tuning Options
to change the defaults.
14-107
14 Control System Tuning
See Also
Related Examples
• “Specify Goals for Interactive Tuning” on page 14-39
• “Manage Tuning Goals” on page 14-179
• “Visualize Tuning Goals” on page 14-189
14-108
Disturbance Rejection Goal
Purpose
Attenuate disturbances at particular locations and in particular frequency bands, when
using Control System Tuner.
Description
Disturbance Rejection Goal specifies the minimum attenuation of a disturbance injected
at a specified location in a control system.
When you use this tuning goal, the software attempts to tune the system so that the
attenuation of a disturbance at the specified location exceeds the minimum attenuation
factor you specify. This attenuation factor is the ratio between the open- and closed-loop
sensitivities to the disturbance, and is a function of frequency.
The following diagram illustrates how the attenuation factor is calculated. Suppose you
specify a location in your control system, y, which is the output of a block A. In that case,
the software calculates the closed-loop sensitivity at out to a signal injected at in. The
software also calculates the sensitivity with the control loop opened at the location z.
y z
A
To specify a Disturbance Rejection Goal, you specify one or more locations at which to
attenuate disturbance. You also provide the frequency-dependent minimum attenuation
factor as a numeric LTI model. You can achieve disturbance attenuation only inside the
control bandwidth. The loop gain must be larger than one for the disturbance to be
attenuated (attenuation factor > 1).
14-109
14 Control System Tuning
When you create a tuning goal in Control System Tuner, a tuning-goal plot is generated.
The dotted line shows the gain profile you specify. The shaded area on the plot represents
the region in the frequency domain where the tuning goal is not satisfied. The solid line is
the current corresponding response of your system.
Creation
In the Tuning tab of Control System Tuner, select New Goal > Disturbance rejection
to create a Disturbance Rejection Goal.
Command-Line Equivalent
Disturbance Scenario
Use this section of the dialog box to specify the signal locations at which to inject the
disturbance. You can also specify loop-opening locations for evaluating the tuning goal.
14-110
Disturbance Rejection Goal
Select one or more signal locations in your model at which to measure the disturbance
attenuation. To constrain a SISO response, select a single-valued location. For
example, to attenuate disturbance at a location named 'y', click Add signal to
list and select 'y'. To constrain a MIMO response, select multiple signals or a vector-
valued signal.
• Evaluate disturbance rejection with the following loops open
Select one or more signal locations in your model at which to open a feedback loop for
the purpose of evaluating this tuning goal. The tuning goal is evaluated against the
open-loop configuration created by opening feedback loops at the locations you
identify. For example, to evaluate the tuning goal with an opening at a location named
'x', click Add signal to list and select 'x'.
Tip To highlight any selected signal in the Simulink model, click . To remove a signal
from the input or output list, click . When you have selected multiple signals, you can
reorder them using and . For more information on how to specify signal locations
for a tuning goal, see “Specify Goals for Interactive Tuning” on page 14-39.
Rejection Performance
Specify the minimum disturbance attenuation as a function of frequency.
Enter a SISO numeric LTI model whose magnitude represents the desired attenuation
profile as a function of frequency. For example, you can specify a smooth transfer function
(tf, zpk, or ss model). Alternatively, you can sketch a piecewise minimum disturbance
rejection using an frd model. When you do so, the software automatically maps the
profile to a smooth transfer function that approximates the desired minimum disturbance
rejection. For example, to specify an attenuation factor of 100 (40 dB) below 1 rad/s, that
gradually drops to 1 (0 dB) past 10 rad/s, enter frd([100 100 1 1],[0 1 10 100]).
If you are tuning in discrete time, you can specify the attenuation profile as a discrete-
time model with the same sampling time as you use for tuning. If you specify the
attenuation profile in continuous time, the tuning software discretizes it. Specifying the
attenuation profile in discrete time gives you more control over the profile near the
Nyquist frequency.
14-111
14 Control System Tuning
Options
Use this section of the dialog box to specify additional characteristics of the disturbance
rejection goal.
Limit the enforcement of the tuning goal to a particular frequency band. Specify the
frequency band as a row vector of the form [min,max], expressed in frequency units
of your model. For example, to create a tuning goal that applies only between 1 and
100 rad/s, enter [1,100]. By default, the tuning goal applies at all frequencies for
continuous time, and up to the Nyquist frequency for discrete time.
Regardless of the limits you enter, a disturbance rejection goal can only be enforced
within the control bandwidth.
• Equalize cross-channel effects
For multiloop or MIMO disturbance rejection requirements, the feedback channels are
automatically rescaled to equalize the off-diagonal (loop interaction) terms in the open-
loop transfer function. Select Off to disable such scaling and shape the unscaled
open-loop response.
• Apply goal to
Use this option when tuning multiple models at once, such as an array of models
obtained by linearizing a Simulink model at different operating points or block-
parameter values. By default, active tuning goals are enforced for all models. To
enforce a tuning requirement for a subset of models in an array, select Only Models.
Then, enter the array indices of the models for which the goal is enforced. For
example, suppose you want to apply the tuning goal to the second, third, and fourth
models in a model array. To restrict enforcement of the requirement, enter 2:4 in the
Only Models text box.
For more information about tuning for multiple models, see “Robust Tuning
Approaches” (Robust Control Toolbox).
Algorithms
Evaluating Tuning Goals
When you tune a control system, the software converts each tuning goal into a normalized
scalar value f(x). Here, x is the vector of free (tunable) parameters in the control system.
14-112
See Also
The software then adjusts the parameter values to minimize f(x) or to drive f(x) below 1 if
the tuning goal is a hard constraint.
f ( x ) = max WS ( jw ) S ( jw, x ) ,
wŒ W •
Implicit Constraints
This tuning goal imposes an implicit stability constraint on the closed-loop sensitivity
function measured at the specified, evaluated with loops opened at the specified loop-
opening locations. The dynamics affected by this implicit constraint are the stabilized
dynamics for this tuning goal. The Minimum decay rate and Maximum natural
frequency tuning options control the lower and upper bounds on these implicitly
constrained dynamics. If the optimization fails to meet the default bounds, or if the
default bounds conflict with other requirements, on the Tuning tab, use Tuning Options
to change the defaults.
See Also
Related Examples
• “Specify Goals for Interactive Tuning” on page 14-39
• “Manage Tuning Goals” on page 14-179
• “Visualize Tuning Goals” on page 14-189
14-113
14 Control System Tuning
Sensitivity Goal
Purpose
Limit sensitivity of feedback loops to disturbances, when using Control System Tuner.
Description
Sensitivity Goal limits the sensitivity of a feedback loop to disturbances. You specify the
maximum sensitivity as a function of frequency. Constrain the sensitivity to be smaller
than one at frequencies where you need good disturbance rejection.
To specify a Sensitivity Goal, you specify one or more locations at which to limit
sensitivity. You also provide the frequency-dependent maximum sensitivity as a numeric
LTI model whose magnitude represents the desired sensitivity as a function of frequency.
When you create a tuning goal in Control System Tuner, a tuning-goal plot is generated.
The dotted line shows the gain profile you specify. The shaded area on the plot represents
the region in the frequency domain where the tuning goal is not satisfied.
14-114
Sensitivity Goal
Creation
In the Tuning tab of Control System Tuner, select New Goal > Sensitivity of feedback
loops to create a Sensitivity Goal.
Command-Line Equivalent
Sensitivity Evaluation
Use this section of the dialog box to specify the signal locations at which to compute the
sensitivity to disturbance. You can also specify loop-opening locations for evaluating the
tuning goal.
Select one or more signal locations in your model at which to measure the sensitivity
to disturbance. To constrain a SISO response, select a single-valued location. For
example, to limit sensitivity at a location named 'y', click Add signal to list and
select 'y'. To constrain a MIMO response, select multiple signals or a vector-valued
signal.
• Evaluate disturbance rejection with the following loops open
Select one or more signal locations in your model at which to open a feedback loop for
the purpose of evaluating this tuning goal. The tuning goal is evaluated against the
open-loop configuration created by opening feedback loops at the locations you
identify. For example, to evaluate the tuning goal with an opening at a location named
'x', click Add signal to list and select 'x'.
Tip To highlight any selected signal in the Simulink model, click . To remove a signal
from the input or output list, click . When you have selected multiple signals, you can
reorder them using and . For more information on how to specify signal locations
for a tuning goal, see “Specify Goals for Interactive Tuning” on page 14-39.
14-115
14 Control System Tuning
Sensitivity Bound
Specify the maximum sensitivity as a function of frequency.
Enter a SISO numeric LTI model whose magnitude represents the desired sensitivity
bound as a function of frequency. For example, you can specify a smooth transfer function
(tf, zpk, or ss model). Alternatively, you can sketch a piecewise maximum sensitivity
using an frd model. When you do so, the software automatically maps the profile to a
smooth transfer function that approximates the desired sensitivity. For example, to specify
a sensitivity that rolls up at 20 dB per decade and levels off at unity above 1 rad/s, enter
frd([0.01 1 1],[0.001 0.1 100]).
If you are tuning in discrete time, you can specify the maximum sensitivity profile as a
discrete-time model with the same sampling time as you use for tuning. If you specify the
sensitivity profile in continuous time, the tuning software discretizes it. Specifying the
profile in discrete time gives you more control over the profile near the Nyquist
frequency.
Options
Use this section of the dialog box to specify additional characteristics of the sensitivity
goal.
Limit the enforcement of the tuning goal to a particular frequency band. Specify the
frequency band as a row vector of the form [min,max], expressed in frequency units
of your model. For example, to create a tuning goal that applies only between 1 and
100 rad/s, enter [1,100]. By default, the tuning goal applies at all frequencies for
continuous time, and up to the Nyquist frequency for discrete time.
• Equalize cross-channel effects
Use this option when tuning multiple models at once, such as an array of models
obtained by linearizing a Simulink model at different operating points or block-
14-116
Sensitivity Goal
parameter values. By default, active tuning goals are enforced for all models. To
enforce a tuning requirement for a subset of models in an array, select Only Models.
Then, enter the array indices of the models for which the goal is enforced. For
example, suppose you want to apply the tuning goal to the second, third, and fourth
models in a model array. To restrict enforcement of the requirement, enter 2:4 in the
Only Models text box.
For more information about tuning for multiple models, see “Robust Tuning
Approaches” (Robust Control Toolbox).
Algorithms
Evaluating Tuning Goals
When you tune a control system, the software converts each tuning goal into a normalized
scalar value f(x). Here, x is the vector of free (tunable) parameters in the control system.
The software then adjusts the parameter values to minimize f(x) or to drive f(x) below 1 if
the tuning goal is a hard constraint.
f ( x ) = WS ( s) S ( s, x ) ,
•
measured at the location specified in the tuning goal. ◊ • denotes the H∞ norm (see
norm). WS is a frequency weighting function derived from the sensitivity profile you
specify. The gain of WS roughly matches the inverse of the specified profile for gain values
ranging from –20 dB to 60 dB. For numerical reasons, the weighting function levels off
outside this range, unless the specified gain profile changes slope outside this range. This
adjustment is called regularization. Because poles of WS close to s = 0 or s = Inf might
lead to poor numeric conditioning for tuning, it is not recommended to specify sensitivity
profiles with very low-frequency or very high-frequency dynamics.For more information
about regularization and its effects, see “Visualize Tuning Goals” on page 14-189.
Implicit Constraint
This tuning goal imposes an implicit stability constraint on the closed-loop sensitivity
function measured at the specified, evaluated with loops opened at the specified loop-
opening locations. The dynamics affected by this implicit constraint are the stabilized
14-117
14 Control System Tuning
dynamics for this tuning goal. The Minimum decay rate and Maximum natural
frequency tuning options control the lower and upper bounds on these implicitly
constrained dynamics. If the optimization fails to meet the default bounds, or if the
default bounds conflict with other requirements, on the Tuning tab, use Tuning Options
to change the defaults.
See Also
Related Examples
• “Specify Goals for Interactive Tuning” on page 14-39
• “Manage Tuning Goals” on page 14-179
• “Visualize Tuning Goals” on page 14-189
14-118
Weighted Gain Goal
Description
Weighted Gain Goal limits the gain of the frequency-weighted transfer function
WL(s)H(s)WR(s), where H(s) is the transfer function between inputs and outputs you
specify. WL(s) and WR(s) are weighting functions that you can use to emphasize
particular frequency bands. Weighted Gain Goal constrains the peak gain of
WL(s)H(s)WR(s) to values less than 1. If H(s) is a MIMO transfer function, Weighted Gain
Goal constrains the largest singular value of H(s).
Creation
In the Tuning tab of Control System Tuner, select New Goal > Frequency-weighted
gain limit to create a Weighted Gain Goal.
Command-Line Equivalent
Select one or more signal locations in your model as inputs to the transfer function
that the tuning goal constrains. To constrain a SISO response, select a single-valued
input signal. For example, to constrain the gain from a location named 'u' to a
14-119
14 Control System Tuning
location named 'y', click Add signal to list and select 'u'. To constrain the
largest singular value of a MIMO response, select multiple signals or a vector-valued
signal.
• Specify output signals
Select one or more signal locations in your model as outputs of the transfer function
that the tuning goal constrains. To constrain a SISO response, select a single-valued
output signal. For example, to constrain the gain from a location named 'u' to a
location named 'y', click Add signal to list and select 'y'. To constrain the
largest singular value of a MIMO response, select multiple signals or a vector-valued
signal.
• Compute input/output gain with the following loops open
Select one or more signal locations in your model at which to open a feedback loop for
the purpose of evaluating this tuning goal. The tuning goal is evaluated against the
open-loop configuration created by opening feedback loops at the locations you
identify. For example, to evaluate the tuning goal with an opening at a location named
'x', click Add signal to list and select 'x'.
Tip To highlight any selected signal in the Simulink model, click . To remove a signal
from the input or output list, click . When you have selected multiple signals, you can
reorder them using and . For more information on how to specify signal locations
for a tuning goal, see “Specify Goals for Interactive Tuning” on page 14-39.
Weights
Use the Left weight WL and Right weight WR text boxes to specify the frequency-
weighting functions for the tuning goal. The tuning goal ensures that the gain H(s) from
the specified input to output satisfies the inequality:
||WL(s)H(s)WR(s)||∞ < 1.
WL provides the weighting for the output channels of H(s), and WR provides the
weighting for the input channels. You can specify scalar weights or frequency-dependent
weighting. To specify a frequency-dependent weighting, use a numeric LTI model whose
14-120
Weighted Gain Goal
magnitude represents the desired weighting function. For example, enter tf(1,[1
0.01]) to specify a high weight at low frequencies that rolls off above 0.01 rad/s.
If the tuning goal constrains a MIMO transfer function, scalar or SISO weighting
functions automatically expand to any input or output dimension. You can specify different
weights for each channel by specifying matrices or MIMO weighting functions. The
dimensions H(s) must be commensurate with the dimensions of WL and WR. For example,
if the constrained transfer function has two inputs, you can specify diag([1 10]) as
WR.
If you are tuning in discrete time, you can specify the weighting functions as discrete-time
models with the same sampling time as you use for tuning. If you specify the weighting
functions in continuous time, the tuning software discretizes them. Specifying the
weighting functions in discrete time gives you more control over the weighting functions
near the Nyquist frequency.
Options
Use this section of the dialog box to specify additional characteristics of the weighted
gain goal.
By default, the tuning goal imposes a stability requirement on the closed-loop transfer
function from the specified inputs to outputs, in addition to the gain constraint. If
stability is not required or cannot be achieved, select No to remove the stability
requirement. For example, if the gain constraint applies to an unstable open-loop
transfer function, select No.
• Enforce goal in frequency range
Limit the enforcement of the tuning goal to a particular frequency band. Specify the
frequency band as a row vector of the form [min,max], expressed in frequency units
of your model. For example, to create a tuning goal that applies only between 1 and
100 rad/s, enter [1,100]. By default, the tuning goal applies at all frequencies for
continuous time, and up to the Nyquist frequency for discrete time.
• Apply goal to
Use this option when tuning multiple models at once, such as an array of models
obtained by linearizing a Simulink model at different operating points or block-
parameter values. By default, active tuning goals are enforced for all models. To
14-121
14 Control System Tuning
enforce a tuning requirement for a subset of models in an array, select Only Models.
Then, enter the array indices of the models for which the goal is enforced. For
example, suppose you want to apply the tuning goal to the second, third, and fourth
models in a model array. To restrict enforcement of the requirement, enter 2:4 in the
Only Models text box.
For more information about tuning for multiple models, see “Robust Tuning
Approaches” (Robust Control Toolbox).
Algorithms
When you tune a control system, the software converts each tuning goal into a normalized
scalar value f(x). Here, x is the vector of free (tunable) parameters in the control system.
The software then adjusts the parameter values to minimize f(x) or to drive f(x) below 1 if
the tuning goal is a hard constraint.
f ( x ) = WL H ( s, x ) WR .
•
H(s,x) is the closed-loop transfer function between the specified inputs and outputs,
This tuning goal also imposes an implicit stability constraint on the weighted closed-loop
transfer function between the specified inputs to outputs, evaluated with loops opened at
the specified loop-opening locations. The dynamics affected by this implicit constraint are
the stabilized dynamics for this tuning goal. The Minimum decay rate and Maximum
natural frequency tuning options control the lower and upper bounds on these implicitly
constrained dynamics. If the optimization fails to meet the default bounds, or if the
default bounds conflict with other requirements, on the Tuning tab, use Tuning Options
to change the defaults.
See Also
Related Examples
• “Specify Goals for Interactive Tuning” on page 14-39
14-122
See Also
14-123
14 Control System Tuning
Purpose
Frequency-weighted limit on noise impact on specified output signals for tuning with
Control System Tuner.
Description
Weighted Variance Goal limits the noise impact on the outputs of the frequency-weighted
transfer function WL(s)H(s)WR(s), where H(s) is the transfer function between inputs and
outputs you specify. WL(s) and WR(s) are weighting functions you can use to model a
noise spectrum or emphasize particular frequency bands. Thus, you can use Weighted
Variance Goal to tune the system response to stochastic inputs with a nonuniform
spectrum such as colored noise or wind gusts.
Weighted Variance minimizes the response to noise at the inputs by minimizing the H2
norm of the frequency-weighted transfer function. The H2 norm measures:
• The total energy of the impulse response, for deterministic inputs to the transfer
function.
• The square root of the output variance for a unit-variance white-noise input, for
stochastic inputs to the transfer function. Equivalently, the H2 norm measures the root-
mean-square of the output for such input.
Creation
In the Tuning tab of Control System Tuner, select New Goal > Frequency-weighted
variance attenuation to create a Weighted Variance Goal.
Command-Line Equivalent
14-124
Weighted Variance Goal
Select one or more signal locations in your model as noise inputs. To constrain a SISO
response, select a single-valued input signal. For example, to constrain the gain from a
location named 'u' to a location named 'y', click Add signal to list and select
'u'. To constrain the noise amplification of a MIMO response, select multiple signals
or a vector-valued signal.
• Specify stochastic outputs
Select one or more signal locations in your model as outputs for computing response
to the noise inputs. To constrain a SISO response, select a single-valued output signal.
For example, to constrain the gain from a location named 'u' to a location named
'y', click Add signal to list and select 'y'. To constrain the noise amplification
of a MIMO response, select multiple signals or a vector-valued signal.
• Compute output variance with the following loops open
Select one or more signal locations in your model at which to open a feedback loop for
the purpose of evaluating this tuning goal. The tuning goal is evaluated against the
open-loop configuration created by opening feedback loops at the locations you
identify. For example, to evaluate the tuning goal with an opening at a location named
'x', click Add signal to list and select 'x'.
Tip To highlight any selected signal in the Simulink model, click . To remove a signal
from the input or output list, click . When you have selected multiple signals, you can
reorder them using and . For more information on how to specify signal locations
for a tuning goal, see “Specify Goals for Interactive Tuning” on page 14-39.
Weights
Use the Left weight WL and Right weight WR text boxes to specify the frequency-
weighting functions for the tuning goal.
WL provides the weighting for the output channels of H(s), and WR provides the
weighting for the input channels.
14-125
14 Control System Tuning
If the tuning goal constrains a MIMO transfer function, scalar or SISO weighting
functions automatically expand to any input or output dimension. You can specify different
weights for each channel by specifying MIMO weighting functions. The dimensions H(s)
must be commensurate with the dimensions of WL and WR. For example, if the
constrained transfer function has two inputs, you can specify diag([1 10]) as WR.
If you are tuning in discrete time, you can specify the weighting functions as discrete-time
models with the same sampling time as you use for tuning. If you specify the weighting
functions in continuous time, the tuning software discretizes them. Specifying the
weighting functions in discrete time gives you more control over the weighting functions
near the Nyquist frequency.
Options
Use this section of the dialog box to specify additional characteristics of the weighted
variance goal.
• Apply goal to
Use this option when tuning multiple models at once, such as an array of models
obtained by linearizing a Simulink model at different operating points or block-
parameter values. By default, active tuning goals are enforced for all models. To
enforce a tuning requirement for a subset of models in an array, select Only Models.
Then, enter the array indices of the models for which the goal is enforced. For
example, suppose you want to apply the tuning goal to the second, third, and fourth
models in a model array. To restrict enforcement of the requirement, enter 2:4 in the
Only Models text box.
For more information about tuning for multiple models, see “Robust Tuning
Approaches” (Robust Control Toolbox).
14-126
Weighted Variance Goal
Tips
• When you use this requirement to tune a control system, Control System Tuner
attempts to enforce zero feedthrough (D = 0) on the transfer that the requirement
constrains. Zero feedthrough is imposed because the H2 norm, and therefore the value
of the tuning goal (see “Algorithms” on page 14-127), is infinite for continuous-time
systems with nonzero feedthrough.
Control System Tuner enforces zero feedthrough by fixing to zero all tunable
parameters that contribute to the feedthrough term. Control System Tuner returns an
error when fixing these tunable parameters is insufficient to enforce zero feedthrough.
In such cases, you must modify the requirement or the control structure, or manually
fix some tunable parameters of your system to values that eliminate the feedthrough
term.
When the constrained transfer function has several tunable blocks in series, the
software’s approach of zeroing all parameters that contribute to the overall
feedthrough might be conservative. In that case, it is sufficient to zero the feedthrough
term of one of the blocks. If you want to control which block has feedthrough fixed to
zero, you can manually fix the feedthrough of the tuned block of your choice.
To fix parameters of tunable blocks to specified values, see “View and Change Block
Parameterization in Control System Tuner” on page 14-26.
• This tuning goal also imposes an implicit stability constraint on the weighted closed-
loop transfer function between the specified inputs to outputs, evaluated with loops
opened at the specified loop-opening locations. The dynamics affected by this implicit
constraint are the stabilized dynamics for this tuning goal. The Minimum decay rate
and Maximum natural frequency tuning options control the lower and upper
bounds on these implicitly constrained dynamics. If the optimization fails to meet the
default bounds, or if the default bounds conflict with other requirements, on the
Tuning tab, use Tuning Options to change the defaults.
Algorithms
When you tune a control system, the software converts each tuning goal into a normalized
scalar value f(x). Here, x is the vector of free (tunable) parameters in the control system.
The software then adjusts the parameter values to minimize f(x) or to drive f(x) below 1 if
the tuning goal is a hard constraint.
14-127
14 Control System Tuning
f ( x ) = WL H ( s, x ) WR .
2
H(s,x) is the closed-loop transfer function between the specified inputs and outputs,
1
f (x) = WL ( z ) H ( z, x ) WR ( z ) .
Ts 2
See Also
Related Examples
• “Specify Goals for Interactive Tuning” on page 14-39
• “Visualize Tuning Goals” on page 14-189
• “Manage Tuning Goals” on page 14-179
14-128
Minimum Loop Gain Goal
Purpose
Boost gain of feedback loops at low frequency when using Control System Tuner.
Description
Minimum Loop Gain Goal enforces a minimum loop gain in a particular frequency band.
This tuning goal is useful, for example, for improving disturbance rejection at a particular
location.
Minimum Loop Gain Goal imposes a minimum gain on the open-loop frequency response
(L) at a specified location in your control system. You specify the minimum open-loop gain
as a function of frequency (a minimum gain profile). For MIMO feedback loops, the
specified gain profile is interpreted as a lower bound on the smallest singular value of L.
When you tune a control system, the minimum gain profile is converted to a minimum
gain constraint on the inverse of the sensitivity function, inv(S) = (I + L).
The following figure shows a typical specified minimum gain profile (dashed line) and a
resulting tuned loop gain, L (blue line). The green region represents gain profile values
that are forbidden by this requirement. The figure shows that when L is much larger than
1, imposing a minimum gain on inv(S) is a good proxy for a minimum open-loop gain.
14-129
14 Control System Tuning
Minimum Loop Gain Goal is a constraint on the open-loop gain of the specified control
loop. Thus, the loop gain is computed with the loop open at the specified location. To
compute the gain with loop openings at other points in the control system, use the
Compute response with the following loops open option in the Open-Loop
Response Selection section of the dialog box.
Minimum Loop Gain Goal and Maximum Loop Gain Goal specify only low-gain or high-
gain constraints in certain frequency bands. When you use these requirements, the
software determines the best loop shape near crossover. When the loop shape near
crossover is simple or well understood (such as integral action), you can use “Loop Shape
Goal” on page 14-141 to specify that target loop shape.
14-130
Minimum Loop Gain Goal
Creation
In the Tuning tab of Control System Tuner, select New Goal > Minimum gain for
open-loop response to create a Minimum Gain Goal.
Command-Line Equivalent
Select one or more signal locations in your model at which to compute and constrain
the open-loop gain. To constrain a SISO response, select a single-valued location. For
example, to constrain the open-loop gain at a location named 'y', click Add signal
to list and select 'y'. To constrain a MIMO response, select multiple signals or a
vector-valued signal.
• Compute response with the following loops open
Select one or more signal locations in your model at which to open a feedback loop for
the purpose of evaluating this tuning goal. The tuning goal is evaluated against the
open-loop configuration created by opening feedback loops at the locations you
identify. For example, to evaluate the tuning goal with an opening at a location named
'x', click Add signal to list and select 'x'.
Tip To highlight any selected signal in the Simulink model, click . To remove a signal
from the input or output list, click . When you have selected multiple signals, you can
reorder them using and . For more information on how to specify signal locations
for a tuning goal, see “Specify Goals for Interactive Tuning” on page 14-39.
14-131
14 Control System Tuning
Check to specify a pure integrator shape for the target minimum loop gain. The
software chooses the integrator constant, K, based on the values you specify for a
target minimum gain and frequency. For example, to specify an integral gain profile
with crossover frequency 10 rad/s, enter 1 in the Choose K to keep gain above text
box. Then, enter 10 in the at the frequency text box. The software chooses the
integrator constant such that the minimum loop gain is 1 at 10 rad/s.
• Other gain profile
Check to specify the minimum gain profile as a function of frequency. Enter a SISO
numeric LTI model whose magnitude represents the desired gain profile. For example,
you can specify a smooth transfer function (tf, zpk, or ss model). Alternatively, you
can sketch a piecewise target loop gain using an frd model. When you do so, the
software automatically maps the profile to a smooth transfer function that
approximates the desired minimum loop gain. For example, to specify minimum gain
of 100 (40 dB) below 0.1 rad/s, rolling off at a rate of –20 dB/dec at higher frequencies,
enter frd([100 100 10],[0 1e-1 1]).
If you are tuning in discrete time, you can specify the minimum gain profile as a
discrete-time model with the same sampling time as you use for tuning. If you specify
the gain profile in continuous time, the tuning software discretizes it. Specifying the
profile in discrete time gives you more control over the profile near the Nyquist
frequency.
Options
Use this section of the dialog box to specify additional characteristics of the minimum
loop gain goal.
Limit the enforcement of the tuning goal to a particular frequency band. Specify the
frequency band as a row vector of the form [min,max], expressed in frequency units
of your model. For example, to create a tuning goal that applies only between 1 and
100 rad/s, enter [1,100]. By default, the tuning goal applies at all frequencies for
continuous time, and up to the Nyquist frequency for discrete time.
14-132
Minimum Loop Gain Goal
By default, the tuning goal imposes a stability requirement on the closed-loop transfer
function from the specified inputs to outputs, in addition to the gain constraint. If
stability is not required or cannot be achieved, select No to remove the stability
requirement. For example, if the gain constraint applies to an unstable open-loop
transfer function, select No.
• Equalize loop interactions
For multi-loop or MIMO loop gain constraints, the feedback channels are automatically
rescaled to equalize the off-diagonal (loop interaction) terms in the open-loop transfer
function. Select Off to disable such scaling and shape the unscaled open-loop
response.
• Apply goal to
Use this option when tuning multiple models at once, such as an array of models
obtained by linearizing a Simulink model at different operating points or block-
parameter values. By default, active tuning goals are enforced for all models. To
enforce a tuning requirement for a subset of models in an array, select Only Models.
Then, enter the array indices of the models for which the goal is enforced. For
example, suppose you want to apply the tuning goal to the second, third, and fourth
models in a model array. To restrict enforcement of the requirement, enter 2:4 in the
Only Models text box.
For more information about tuning for multiple models, see “Robust Tuning
Approaches” (Robust Control Toolbox).
Algorithms
Evaluating Tuning Goals
When you tune a control system, the software converts each tuning goal into a normalized
scalar value f(x). Here, x is the vector of free (tunable) parameters in the control system.
The software then adjusts the parameter values to minimize f(x) or to drive f(x) below 1 if
the tuning goal is a hard constraint.
(
f ( x ) = WS D -1 SD ) •.
14-133
14 Control System Tuning
Implicit Constraints
This tuning goal imposes an implicit stability constraint on the closed-loop sensitivity
function measured at the specified, evaluated with loops opened at the specified loop-
opening locations. The dynamics affected by this implicit constraint are the stabilized
dynamics for this tuning goal. The Minimum decay rate and Maximum natural
frequency tuning options control the lower and upper bounds on these implicitly
constrained dynamics. If the optimization fails to meet the default bounds, or if the
default bounds conflict with other requirements, on the Tuning tab, use Tuning Options
to change the defaults.
See Also
Related Examples
• “Specify Goals for Interactive Tuning” on page 14-39
• “Manage Tuning Goals” on page 14-179
• “Visualize Tuning Goals” on page 14-189
14-134
Maximum Loop Gain Goal
Purpose
Suppress gain of feedback loops at high frequency when using Control System Tuner.
Description
Maximum Loop Gain Goal enforces a maximum loop gain in a particular frequency band.
This tuning goal is useful, for example, for increasing system robustness to unmodeled
dynamics.
Maximum Loop Gain Goal imposes a maximum gain on the open-loop frequency response
(L) at a specified location in your control system. You specify the maximum open-loop gain
as a function of frequency (a maximum gain profile). For MIMO feedback loops, the
specified gain profile is interpreted as an upper bound on the largest singular value of L.
When you tune a control system, the maximum gain profile is converted to a maximum
gain constraint on the complementary sensitivity function, T) = L/(I + L).
The following figure shows a typical specified maximum gain profile (dashed line) and a
resulting tuned loop gain, L (blue line). The shaded region represents gain profile values
that are forbidden by this requirement. The figure shows that when L is much smaller
than 1, imposing a maximum gain on T is a good proxy for a maximum open-loop gain.
14-135
14 Control System Tuning
Maximum Loop Gain Goal is a constraint on the open-loop gain of the specified control
loop. Thus, the loop gain is computed with the loop open at the specified location. To
compute the gain with loop openings at other points in the control system, use the
Compute response with the following loops open option in the Open-Loop
Response Selection section of the dialog box.
Maximum Loop Gain Goal and Minimum Loop Gain Goal specify only high-gain or low-
gain constraints in certain frequency bands. When you use these requirements, the
software determines the best loop shape near crossover. When the loop shape near
crossover is simple or well understood (such as integral action), you can use “Loop Shape
Goal” on page 14-141 to specify that target loop shape.
14-136
Maximum Loop Gain Goal
Creation
In the Tuning tab of Control System Tuner, select New Goal > Maximum gain for
open-loop response to create a Maximum Gain Goal.
Command-Line Equivalent
Select one or more signal locations in your model at which to compute and constrain
the open-loop gain. To constrain a SISO response, select a single-valued location. For
example, to constrain the open-loop gain at a location named 'y', click Add signal
to list and select 'y'. To constrain a MIMO response, select multiple signals or a
vector-valued signal.
• Compute response with the following loops open
Select one or more signal locations in your model at which to open a feedback loop for
the purpose of evaluating this tuning goal. The tuning goal is evaluated against the
open-loop configuration created by opening feedback loops at the locations you
identify. For example, to evaluate the tuning goal with an opening at a location named
'x', click Add signal to list and select 'x'.
Tip To highlight any selected signal in the Simulink model, click . To remove a signal
from the input or output list, click . When you have selected multiple signals, you can
reorder them using and . For more information on how to specify signal locations
for a tuning goal, see “Specify Goals for Interactive Tuning” on page 14-39.
14-137
14 Control System Tuning
Check to specify a pure integrator shape for the target maximum loop gain. The
software chooses the integrator constant, K, based on the values you specify for a
target maximum gain and frequency. For example, to specify an integral gain profile
with crossover frequency 10 rad/s, enter 1 in the Choose K to keep gain below text
box. Then, enter 10 in the at the frequency text box. The software chooses the
integrator constant such that the maximum loop gain is 1 at 10 rad/s.
• Other gain profile
Check to specify the maximum gain profile as a function of frequency. Enter a SISO
numeric LTI model whose magnitude represents the desired gain profile. For example,
you can specify a smooth transfer function (tf, zpk, or ss model). Alternatively, you
can sketch a piecewise target loop gain using an frd model. When you do so, the
software automatically maps the profile to a smooth transfer function that
approximates the desired maximum loop gain. For example, to specify maximum gain
of 100 (40 dB) below 0.1 rad/s, rolling off at a rate of –20 dB/dec at higher frequencies,
enter frd([100 100 10],[0 1e-1 1]).
If you are tuning in discrete time, you can specify the maximum gain profile as a
discrete-time model with the same sampling time as you use for tuning. If you specify
the gain profile in continuous time, the tuning software discretizes it. Specifying the
profile in discrete time gives you more control over the profile near the Nyquist
frequency.
Options
Use this section of the dialog box to specify additional characteristics of the maximum
loop gain goal.
Limit the enforcement of the tuning goal to a particular frequency band. Specify the
frequency band as a row vector of the form [min,max], expressed in frequency units
of your model. For example, to create a tuning goal that applies only between 1 and
100 rad/s, enter [1,100]. By default, the tuning goal applies at all frequencies for
continuous time, and up to the Nyquist frequency for discrete time.
14-138
Maximum Loop Gain Goal
By default, the tuning goal imposes a stability requirement on the closed-loop transfer
function from the specified inputs to outputs, in addition to the gain constraint. If
stability is not required or cannot be achieved, select No to remove the stability
requirement. For example, if the gain constraint applies to an unstable open-loop
transfer function, select No.
• Equalize loop interactions
For multi-loop or MIMO loop gain constraints, the feedback channels are automatically
rescaled to equalize the off-diagonal (loop interaction) terms in the open-loop transfer
function. Select Off to disable such scaling and shape the unscaled open-loop
response.
• Apply goal to
Use this option when tuning multiple models at once, such as an array of models
obtained by linearizing a Simulink model at different operating points or block-
parameter values. By default, active tuning goals are enforced for all models. To
enforce a tuning requirement for a subset of models in an array, select Only Models.
Then, enter the array indices of the models for which the goal is enforced. For
example, suppose you want to apply the tuning goal to the second, third, and fourth
models in a model array. To restrict enforcement of the requirement, enter 2:4 in the
Only Models text box.
For more information about tuning for multiple models, see “Robust Tuning
Approaches” (Robust Control Toolbox).
Algorithms
Evaluating Tuning Goals
When you tune a control system, the software converts each tuning goal into a normalized
scalar value f(x). Here, x is the vector of free (tunable) parameters in the control system.
The software then adjusts the parameter values to minimize f(x) or to drive f(x) below 1 if
the tuning goal is a hard constraint.
(
f ( x ) = WT D-1TD ) •.
14-139
14 Control System Tuning
Implicit Constraints
This tuning goal imposes an implicit stability constraint on the closed-loop sensitivity
function measured at the specified, evaluated with loops opened at the specified loop-
opening locations. The dynamics affected by this implicit constraint are the stabilized
dynamics for this tuning goal. The Minimum decay rate and Maximum natural
frequency tuning options control the lower and upper bounds on these implicitly
constrained dynamics. If the optimization fails to meet the default bounds, or if the
default bounds conflict with other requirements, on the Tuning tab, use Tuning Options
to change the defaults.
See Also
Related Examples
• “Specify Goals for Interactive Tuning” on page 14-39
• “Manage Tuning Goals” on page 14-179
• “Visualize Tuning Goals” on page 14-189
14-140
Loop Shape Goal
Purpose
Shape open-loop response of feedback loops when using Control System Tuner.
Description
Loop Shape Goal specifies a target gain profile (gain as a function of frequency) of an
open-loop response. Loop Shape Goal constrains the open-loop, point-to-point response
(L) at a specified location in your control system.
When you tune a control system, the target open-loop gain profile is converted into
constraints on the inverse sensitivity function inv(S) = (I + L) and the complementary
sensitivity function T = 1–S. These constraints are illustrated for a representative tuned
system in the following figure.
14-141
14 Control System Tuning
Where L is much greater than 1, a minimum gain constraint on inv(S) (green shaded
region) is equivalent to a minimum gain constraint on L. Similarly, where L is much
smaller than 1, a maximum gain constraint on T (red shaded region) is equivalent to a
maximum gain constraint on L. The gap between these two constraints is twice the
crossover tolerance, which specifies the frequency band where the loop gain can cross 0
dB.
For multi-input, multi-output (MIMO) control systems, values in the gain profile greater
than 1 are interpreted as minimum performance requirements. Such values are lower
14-142
Loop Shape Goal
bounds on the smallest singular value of the open-loop response. Gain profile values less
than one are interpreted as minimum roll-off requirements, which are upper bounds on
the largest singular value of the open-loop response. For more information about singular
values, see sigma.
Use Loop Shape Goal when the loop shape near crossover is simple or well understood
(such as integral action). To specify only high gain or low gain constraints in certain
frequency bands, use “Minimum Loop Gain Goal” on page 14-129 or “Maximum Loop
Gain Goal” on page 14-135. When you do so, the software determines the best loop shape
near crossover.
Creation
In the Tuning tab of Control System Tuner, select New Goal > Target shape for open-
loop response to create a Loop Shape Goal.
Command-Line Equivalent
Select one or more signal locations in your model at which to compute and constrain
the open-loop gain. To constrain a SISO response, select a single-valued location. For
example, to constrain the open-loop gain at a location named 'y', click Add signal
to list and select 'y'. To constrain a MIMO response, select multiple signals or a
vector-valued signal.
• Compute response with the following loops open
Select one or more signal locations in your model at which to open a feedback loop for
the purpose of evaluating this tuning goal. The tuning goal is evaluated against the
open-loop configuration created by opening feedback loops at the locations you
identify. For example, to evaluate the tuning goal with an opening at a location named
'x', click Add signal to list and select 'x'.
14-143
14 Control System Tuning
Tip To highlight any selected signal in the Simulink model, click . To remove a signal
from the input or output list, click . When you have selected multiple signals, you can
reorder them using and . For more information on how to specify signal locations
for a tuning goal, see “Specify Goals for Interactive Tuning” on page 14-39.
Check to specify a pure integrator and crossover frequency for the target loop shape.
For example, to specify an integral gain profile with crossover frequency 10 rad/s,
enter 10 in the Crossover frequency wc text box.
• Other gain profile
Check to specify the target loop shape as a function of frequency. Enter a SISO
numeric LTI model whose magnitude represents the desired gain profile. For example,
you can specify a smooth transfer function (tf, zpk, or ss model). Alternatively, you
can sketch a piecewise target loop shape using an frd model. When you do so, the
software automatically maps the profile to a smooth transfer function that
approximates the desired loop shape. For example, to specify a target loop shape of
100 (40 dB) below 0.1 rad/s, rolling off at a rate of –20 dB/decade at higher
frequencies, enter frd([100 100 10],[0 1e-1 1]).
If you are tuning in discrete time, you can specify the loop shape as a discrete-time
model with the same sample time that you are using for tuning. If you specify the loop
shape in continuous time, the tuning software discretizes it. Specifying the loop shape
in discrete time gives you more control over the loop shape near the Nyquist
frequency.
Options
Use this section of the dialog box to specify additional characteristics of the loop shape
goal.
14-144
Loop Shape Goal
Specify the tolerance in the location of the crossover frequency, in decades. For
example, to allow gain crossovers within half a decade on either side of the target
crossover frequency, enter 0.5. Increase the crossover tolerance to increase the ability
of the tuning algorithm to enforce the target loop shape for all loops in a MIMO
control system.
• Enforce goal in frequency range
Limit the enforcement of the tuning goal to a particular frequency band. Specify the
frequency band as a row vector of the form [min,max], expressed in frequency units
of your model. For example, to create a tuning goal that applies only between 1 and
100 rad/s, enter [1,100]. By default, the tuning goal applies at all frequencies for
continuous time, and up to the Nyquist frequency for discrete time.
• Stabilize closed loop system
By default, the tuning goal imposes a stability requirement on the closed-loop transfer
function from the specified inputs to outputs, in addition to the gain constraint. If
stability is not required or cannot be achieved, select No to remove the stability
requirement. For example, if the gain constraint applies to an unstable open-loop
transfer function, select No.
For multi-loop or MIMO loop gain constraints, the feedback channels are automatically
rescaled to equalize the off-diagonal (loop interaction) terms in the open-loop transfer
function. Select Off to disable such scaling and shape the unscaled open-loop
response.
• Apply goal to
Use this option when tuning multiple models at once, such as an array of models
obtained by linearizing a Simulink model at different operating points or block-
parameter values. By default, active tuning goals are enforced for all models. To
enforce a tuning requirement for a subset of models in an array, select Only Models.
Then, enter the array indices of the models for which the goal is enforced. For
example, suppose you want to apply the tuning goal to the second, third, and fourth
models in a model array. To restrict enforcement of the requirement, enter 2:4 in the
Only Models text box.
For more information about tuning for multiple models, see “Robust Tuning
Approaches” (Robust Control Toolbox).
14-145
14 Control System Tuning
Algorithms
Evaluating Tuning Goals
When you tune a control system, the software converts each tuning goal into a normalized
scalar value f(x). Here, x is the vector of free (tunable) parameters in the control system.
The software then adjusts the parameter values to minimize f(x) or to drive f(x) below 1 if
the tuning goal is a hard constraint.
WS S
f (x) = .
WT T •
WS and WT are frequency weighting functions derived from the specified loop shape. The
gains of these functions roughly match your specified loop shape and its inverse,
respectively, for values ranging from –20 dB to 60 dB. For numerical reasons, the
weighting functions level off outside this range, unless the specified gain profile changes
slope outside this range. Because poles of WS or WT close to s = 0 or s = Inf might lead
to poor numeric conditioning for tuning, it is not recommended to specify loop shapes
with very low-frequency or very high-frequency dynamics. For more information about
regularization and its effects, see “Visualize Tuning Goals” on page 14-189.
Implicit Constraints
This tuning goal imposes an implicit stability constraint on the closed-loop sensitivity
function measured at the specified, evaluated with loops opened at the specified loop-
opening locations. The dynamics affected by this implicit constraint are the stabilized
dynamics for this tuning goal. The Minimum decay rate and Maximum natural
frequency tuning options control the lower and upper bounds on these implicitly
constrained dynamics. If the optimization fails to meet the default bounds, or if the
14-146
See Also
default bounds conflict with other requirements, on the Tuning tab, use Tuning Options
to change the defaults.
See Also
Related Examples
• “Specify Goals for Interactive Tuning” on page 14-39
• “Manage Tuning Goals” on page 14-179
• “Visualize Tuning Goals” on page 14-189
14-147
14 Control System Tuning
Margins Goal
Purpose
Enforce specified gain and phase margins when using Control System Tuner.
Description
Margins Goal enforces specified gain and phase margins on a SISO or MIMO feedback
loop. For MIMO feedback loops, the gain and phase margins are based on the notion of
disk margins, which guarantee stability for concurrent gain and phase variations in all
feedback channels. See loopmargin for more information about disk margins.
In Control System Tuner, the shaded area on the plot represents the region in the
frequency domain where the margins goal is not met. For more information about
interpreting this plot, see “Stability Margins in Control System Tuning” on page 14-218.
14-148
Margins Goal
Creation
In the Tuning tab of Control System Tuner, select New Goal > Minimum stability
margins to create a Margins Goal.
Command-Line Equivalent
When tuning control systems at the command line, use TuningGoal.Margins to specify
a stability margin goal.
Select one or more signal locations in your model at which to compute and constrain
the stability margins. To constrain a SISO loop, select a single-valued location. For
example, to constrain the stability margins at a location named 'y', click Add
signal to list and select 'y'. To constrain a MIMO loop, select multiple signals or a
vector-valued signal.
• Measure stability margins with the following loops open
Select one or more signal locations in your model at which to open a feedback loop for
the purpose of evaluating this tuning goal. The tuning goal is evaluated against the
open-loop configuration created by opening feedback loops at the locations you
identify. For example, to evaluate the tuning goal with an opening at a location named
'x', click Add signal to list and select 'x'.
Tip To highlight any selected signal in the Simulink model, click . To remove a signal
from the input or output list, click . When you have selected multiple signals, you can
reorder them using and . For more information on how to specify signal locations
for a tuning goal, see “Specify Goals for Interactive Tuning” on page 14-39.
14-149
14 Control System Tuning
Desired Margins
Use this section of the dialog box to specify the minimum gain and phase margins for the
feedback loop.
Enter the required minimum gain margin for the feedback loop as a scalar value
expressed in dB.
• Phase margin (degrees)
Enter the required minimum phase margin for the feedback loop as a scalar value
expressed in degrees.
For MIMO feedback loops, the gain and phase margins are based on the notion of disk
margins, which guarantee stability for concurrent gain and phase variations in all
feedback channels. See loopmargin for more information about disk margins.
Options
Use this section of the dialog box to specify additional characteristics of the stability
margin goal.
Limit the enforcement of the tuning goal to a particular frequency band. Specify the
frequency band as a row vector of the form [min,max], expressed in frequency units
of your model. For example, to create a tuning goal that applies only between 1 and
100 rad/s, enter [1,100]. By default, the tuning goal applies at all frequencies for
continuous time, and up to the Nyquist frequency for discrete time.
For best results with stability margin requirements, pick a frequency band extending
about one decade on each side of the gain crossover frequencies.
• D scaling order
This value controls the order (number of states) of the scalings involved in computing
MIMO stability margins. Static scalings (scaling order 0) are used by default.
Increasing the order may improve results at the expense of increased computations. If
the stability margin plot shows a large gap between the optimized and actual margins,
consider increasing the scaling order. See “Stability Margins in Control System
Tuning” on page 14-218.
14-150
Margins Goal
• Apply goal to
Use this option when tuning multiple models at once, such as an array of models
obtained by linearizing a Simulink model at different operating points or block-
parameter values. By default, active tuning goals are enforced for all models. To
enforce a tuning requirement for a subset of models in an array, select Only Models.
Then, enter the array indices of the models for which the goal is enforced. For
example, suppose you want to apply the tuning goal to the second, third, and fourth
models in a model array. To restrict enforcement of the requirement, enter 2:4 in the
Only Models text box.
For more information about tuning for multiple models, see “Robust Tuning
Approaches” (Robust Control Toolbox).
Algorithms
When you tune a control system, the software converts each tuning goal into a normalized
scalar value f(x). Here, x is the vector of free (tunable) parameters in the control system.
The software then adjusts the parameter values to minimize f(x) or to drive f(x) below 1 if
the tuning goal is a hard constraint.
f ( x ) = 2a S - a I •
.
α is a scalar parameter computed from the specified gain and phase margin.
This tuning goal imposes an implicit stability constraint on the closed-loop sensitivity
function measured at the specified, evaluated with loops opened at the specified loop-
opening locations. The dynamics affected by this implicit constraint are the stabilized
dynamics for this tuning goal. The Minimum decay rate and Maximum natural
frequency tuning options control the lower and upper bounds on these implicitly
constrained dynamics. If the optimization fails to meet the default bounds, or if the
default bounds conflict with other requirements, on the Tuning tab, use Tuning Options
to change the defaults.
14-151
14 Control System Tuning
See Also
Related Examples
• “Specify Goals for Interactive Tuning” on page 14-39
• “Manage Tuning Goals” on page 14-179
• “Visualize Tuning Goals” on page 14-189
More About
• “Stability Margins in Control System Tuning” on page 14-218
14-152
Passivity Goal
Passivity Goal
Purpose
Enforce passivity of specific input/output map when using Control System Tuner.
Description
Passivity Goal enforces passivity of the response of the transfer function between the
specified signal locations. A system is passive if all its I/O trajectories (u(t),y(t)) satisfy:
T
Ú0 y (t ) u ( t) dt > 0,
T
for all T > 0. Equivalently, a system is passive if its frequency response is positive real,
which means that for all ω > 0,
H
G ( jw ) + G ( jw ) >0
T T T
Ú0 y (t ) u ( t) dt > n Ú0 u (t ) u (t ) dt + r Ú0 y( t) y (t ) dt,
T T T
for all T > 0. To enforce the overall passivity condition, set the minimum input passivity
index (ν) and the minimum output passivity index (ρ) to zero. To enforce an excess of
passivity at the inputs or outputs, set ν or ρ to a positive value. To permit a shortage of
passivity, set ν or ρ to a negative value. See “About Passivity and Passivity Indices” on
page 10-2 for more information about these indices.
14-153
14 Control System Tuning
In Control System Tuner, the shaded area on the plot represents the region in the
frequency domain in which the tuning goal is not met. The plot shows the value of the
index described in “Algorithms” on page 14-156.
Creation
In the Tuning tab of Control System Tuner, select New Goal > Passivity Goal.
Command-Line Equivalent
Select one or more signal locations in your model as inputs to the transfer function
that the tuning goal constrains. To constrain a SISO response, select a single-valued
14-154
Passivity Goal
input signal. For example, to constrain the gain from a location named 'u' to a
location named 'y', click Add signal to list and select 'u'. To constrain the
passivity of a MIMO response, select multiple signals or a vector-valued signal.
• Specify output signals
Select one or more signal locations in your model as outputs of the transfer function
that the tuning goal constrains. To constrain a SISO response, select a single-valued
output signal. For example, to constrain the gain from a location named 'u' to a
location named 'y', click Add signal to list and select 'y'. To constrain the
passivity of a MIMO response, select multiple signals or a vector-valued signal.
• Compute input/output gain with the following loops open
Select one or more signal locations in your model at which to open a feedback loop for
the purpose of evaluating this tuning goal. The tuning goal is evaluated against the
open-loop configuration created by opening feedback loops at the locations you
identify. For example, to evaluate the tuning goal with an opening at a location named
'x', click Add signal to list and select 'x'.
Tip To highlight any selected signal in the Simulink model, click . To remove a signal
from the input or output list, click . When you have selected multiple signals, you can
reorder them using and . For more information on how to specify signal locations
for a tuning goal, see “Specify Goals for Interactive Tuning” on page 14-39.
Options
Use this section of the dialog box to specify additional characteristics of the passivity
goal.
Enter the target value of ν in the text box. To enforce an excess of passivity at the
specified inputs, set ν > 0. To permit a shortage of passivity, set ν < 0. By default, the
passivity goal enforces ν = 0, passive at the inputs with no required excess of
passivity.
• Minimum output passivity index
14-155
14 Control System Tuning
Enter the target value of ρ in the text box. To enforce an excess of passivity at the
specified outputs, set ρ > 0. To permit a shortage of passivity, set ρ < 0. By default, the
passivity goal enforces ρ = 0, passive at the outputs with no required excess of
passivity.
• Enforce goal in frequency range
Limit the enforcement of the tuning goal to a particular frequency band. Specify the
frequency band as a row vector of the form [min,max], expressed in frequency units
of your model. For example, to create a tuning goal that applies only between 1 and
100 rad/s, enter [1,100]. By default, the tuning goal applies at all frequencies for
continuous time, and up to the Nyquist frequency for discrete time.
• Apply goal to
Use this option when tuning multiple models at once, such as an array of models
obtained by linearizing a Simulink model at different operating points or block-
parameter values. By default, active tuning goals are enforced for all models. To
enforce a tuning requirement for a subset of models in an array, select Only Models.
Then, enter the array indices of the models for which the goal is enforced. For
example, suppose you want to apply the tuning goal to the second, third, and fourth
models in a model array. To restrict enforcement of the requirement, enter 2:4 in the
Only Models text box.
For more information about tuning for multiple models, see “Robust Tuning
Approaches” (Robust Control Toolbox).
Algorithms
When you tune a control system, the software converts each tuning goal into a normalized
scalar value f(x). Here, x is the vector of free (tunable) parameters in the control system.
The software then adjusts the parameter values to minimize f(x) or to drive f(x) below 1 if
the tuning goal is a hard constraint.
For Passivity Goal, for a closed-loop transfer function G(s,x) from the specified inputs to
the specified outputs, f(x) is given by:
R
f ( x) = , Rmax = 106.
1 + R Rmax
14-156
See Also
R is the relative sector index (see getSectorIndex) of [G(s,x); I], for the sector
represented by:
Ê 2r -I ˆ
Q=Á ˜,
Ë -I 2n ¯
where ρ is the minimum output passivity index and ν is the minimum input passivity index
specified in the dialog box. Rmax is fixed at 106, included to avoid numeric errors for very
large R.
This tuning goal imposes an implicit minimum-phase constraint on the transfer function G
+ I. The transmission zeros of G + I are the stabilized dynamics for this tuning goal. The
Minimum decay rate and Maximum natural frequency tuning options control the
lower and upper bounds on these implicitly constrained dynamics. If the optimization fails
to meet the default bounds, or if the default bounds conflict with other requirements, on
the Tuning tab, use Tuning Options to change the defaults.
See Also
Related Examples
• “Specify Goals for Interactive Tuning” on page 14-39
• “Manage Tuning Goals” on page 14-179
• “Visualize Tuning Goals” on page 14-189
• “Passive Control of Water Tank Level” on page 17-250
• “About Passivity and Passivity Indices” on page 10-2
14-157
14 Control System Tuning
Purpose
Enforce sector bound on specific input/output map when using Control System Tuner.
Description
Conic Sector Goal creates a constraint that restricts the output trajectories of a system. If
for all nonzero input trajectories u(t), the output trajectory z(t) = (Hu)(t) of a linear
system H satisfies:
T
Ú0 z (t ) Q z (t ) dt < 0,
T
for all T ≥ 0, then the output trajectories of H lie in the conic sector described by the
symmetric indefinite matrix Q. Selecting different Q matrices imposes different conditions
on the system response. When you create a Conic Sector Goal, you specify the input
signals, output signals, and the sector geometry.
14-158
Conic Sector Goal
In Control System Tuner, the shaded area on the plot represents the region in the
frequency domain in which the tuning goal is not met. The plot shows the value of the R-
index described in “About Sector Bounds and Sector Indices” on page 10-9.
Creation
In the Tuning tab of Control System Tuner, select New Goal > Conic Sector Goal.
Command-Line Equivalent
Select one or more signal locations in your model as inputs to the transfer function
that the tuning goal constrains. To constrain a SISO response, select a single-valued
input signal. For example, to constrain the gain from a location named 'u' to a
location named 'y', click Add signal to list and select 'u'. To constrain the
passivity of a MIMO response, select multiple signals or a vector-valued signal.
• Specify output signals
Select one or more signal locations in your model as outputs of the transfer function
that the tuning goal constrains. To constrain a SISO response, select a single-valued
output signal. For example, to constrain the gain from a location named 'u' to a
location named 'y', click Add signal to list and select 'y'. To constrain the
passivity of a MIMO response, select multiple signals or a vector-valued signal.
• Compute input/output gain with the following loops open
Select one or more signal locations in your model at which to open a feedback loop for
the purpose of evaluating this tuning goal. The tuning goal is evaluated against the
open-loop configuration created by opening feedback loops at the locations you
identify. For example, to evaluate the tuning goal with an opening at a location named
'x', click Add signal to list and select 'x'.
14-159
14 Control System Tuning
Tip To highlight any selected signal in the Simulink model, click . To remove a signal
from the input or output list, click . When you have selected multiple signals, you can
reorder them using and . For more information on how to specify signal locations
for a tuning goal, see “Specify Goals for Interactive Tuning” on page 14-39.
Options
Specify additional characteristics of the conic sector goal using this section of the dialog
box.
For more information, see “About Sector Bounds and Sector Indices” on page 10-9.
• Regularization
For more information about the conditions that require regularization, see the
Regularization property of TuningGoal.ConicSector.
• Enforce goal in frequency range
14-160
Conic Sector Goal
Limit the enforcement of the tuning goal to a particular frequency band. Specify the
frequency band as a row vector of the form [min,max], expressed in frequency units
of your model. For example, to create a tuning goal that applies only between 1 and
100 rad/s, enter [1,100]. By default, the tuning goal applies at all frequencies for
continuous time, and up to the Nyquist frequency for discrete time.
• Apply goal to
Use this option when tuning multiple models at once, such as an array of models
obtained by linearizing a Simulink model at different operating points or block-
parameter values. By default, active tuning goals are enforced for all models. To
enforce a tuning requirement for a subset of models in an array, select Only Models.
Then, enter the array indices of the models for which the goal is enforced. For
example, suppose you want to apply the tuning goal to the second, third, and fourth
models in a model array. To restrict enforcement of the requirement, enter 2:4 in the
Only Models text box.
For more information about tuning for multiple models, see “Robust Tuning
Approaches” (Robust Control Toolbox).
Tips
Constraining Input and Output Trajectories to Conic Sector
r + e C u G y
−
Suppose that the signal u is marked as an analysis point in the model you are tuning.
Suppose also that G is the closed-loop transfer function from u to y. A common application
is to create a tuning goal that constrains all the I/O trajectories {u(t),y(t)} of G to satisfy:
(t )ˆ Ê y (t )ˆ
T
TÊy
Ú0 ÁÁ ˜˜ Q ÁÁ ˜˜ dt < 0,
Ë u ( t) ¯ Ë u ( t) ¯
14-161
14 Control System Tuning
for all T ≥ 0. Constraining the I/O trajectories of G is equivalent to restricting the output
trajectories z(t) of the system H = [G;I] to the sector defined by:
T
Ú0 z (t ) Q z (t ) dt < 0.
T
(See “About Sector Bounds and Sector Indices” on page 10-9 for more details about this
equivalence.) To specify a constraint of this type using Conic Sector Goal, specify u as the
input signal, and specify y and u as output signals. When you specify u as both input and
output, Conic Sector Goal sets the corresponding transfer function to the identity.
Therefore, the transfer function that the goal constrains is H = [G;I] as intended. This
treatment is specific to Conic Sector Goal. For other tuning goals, when the same signal
appears in both inputs and outputs, the resulting transfer function is zero in the absence
of feedback loops, or the complementary sensitivity at that location otherwise. This result
occurs because when the software processes analysis points, it assumes that the input is
injected after the output. See “Mark Signals of Interest for Control System Analysis and
Design” on page 2-89 for more information about how analysis points work.
Algorithms
Let
Q = W1W1T - W2W2T
T
Ú0 z (t ) Q z (t ) dt < 0,
T
H ( - jw ) QH ( jw ) < 0
for all frequencies. Conic Sector Goal uses this equivalence to convert the time-domain
characterization into a frequency-domain condition that Control System Tuner can handle
in the same way it handles gain constraints. To secure this equivalence, Conic Sector Goal
14-162
See Also
also makes W2T H ( s ) minimum phase by making all its zeros stable. The transmission
zeros affected by this minimum-phase condition are the stabilized dynamics for this
tuning goal. The Minimum decay rate and Maximum natural frequency tuning
options control the lower and upper bounds on these implicitly constrained dynamics. If
the optimization fails to meet the default bounds, or if the default bounds conflict with
other requirements, on the Tuning tab, use Tuning Options to change the defaults.
For sector bounds, the R-index plays the same role as the peak gain does for gain
constraints (see “About Sector Bounds and Sector Indices” on page 10-9). The condition
H ( - jw ) QH ( jw ) < 0
is satisfied at all frequencies if and only if the R-index is less than one. The plot that
Control System Tuner displays for Conic Sector Goal shows the R-index value as a
function of frequency (see sectorplot).
When you tune a control system, the software converts each tuning goal into a normalized
scalar value f(x), where x is the vector of free (tunable) parameters in the control system.
The software then adjusts the parameter values to minimize f(x) or to drive f(x) below 1 if
the tuning goal is a hard constraint.
For Conic Sector Goal, for a closed-loop transfer function H(s,x) from the specified
inputs to the specified outputs, f(x) is given by:
R
f ( x) = , Rmax = 106.
1 + R Rmax
R is the relative sector index (see getSectorIndex) of H(s,x), for the sector
represented by Q.
See Also
Related Examples
• “About Sector Bounds and Sector Indices” on page 10-9
• “Specify Goals for Interactive Tuning” on page 14-39
14-163
14 Control System Tuning
14-164
Weighted Passivity Goal
Purpose
Enforce passivity of a frequency-weighted transfer function when tuning in Control
System Tuner.
Description
Weighted Passivity Goal enforces the passivity of H(s) = WL(s)T(s)WR(s), where T(s) is the
transfer function from specified inputs to outputs. WL(s) and WR(s) are frequency weights
used to emphasize particular frequency bands. A system is passive if all its I/O
trajectories (u(t),y(t)) satisfy:
T
Ú0 y (t ) u ( t) dt > 0,
T
for all T > 0. Weighted Passivity Goal creates a constraint that enforces:
T T T
Ú0 y (t ) u ( t) dt > n Ú0 u (t ) u (t ) dt + r Ú0 y( t) y (t ) dt,
T T T
for the trajectories of the weighted transfer function H(s), for all T > 0. To enforce the
overall passivity condition, set the minimum input passivity index (ν) and the minimum
output passivity index (ρ) to zero. To enforce an excess of passivity at the inputs or
outputs of the weighted transfer function, set ν or ρ to a positive value. To permit a
shortage of passivity, set ν or ρ to a negative value. See getPassiveIndex for more
information about these indices.
14-165
14 Control System Tuning
In Control System Tuner, the shaded area on the plot represents the region in the
frequency domain in which the tuning goal is not met. The plot shows the value of the
index described in “Algorithms” on page 14-169.
Creation
In the Tuning tab of Control System Tuner, select New Goal > Weighted Passivity
Goal.
Command-Line Equivalent
14-166
Weighted Passivity Goal
Select one or more signal locations in your model as inputs to the transfer function
that the tuning goal constrains. To constrain a SISO response, select a single-valued
input signal. For example, to constrain the gain from a location named 'u' to a
location named 'y', click Add signal to list and select 'u'. To constrain the
passivity of a MIMO response, select multiple signals or a vector-valued signal.
• Specify output signals
Select one or more signal locations in your model as outputs of the transfer function
that the tuning goal constrains. To constrain a SISO response, select a single-valued
output signal. For example, to constrain the gain from a location named 'u' to a
location named 'y', click Add signal to list and select 'y'. To constrain the
passivity of a MIMO response, select multiple signals or a vector-valued signal.
• Compute input/output gain with the following loops open
Select one or more signal locations in your model at which to open a feedback loop for
the purpose of evaluating this tuning goal. The tuning goal is evaluated against the
open-loop configuration created by opening feedback loops at the locations you
identify. For example, to evaluate the tuning goal with an opening at a location named
'x', click Add signal to list and select 'x'.
Tip To highlight any selected signal in the Simulink model, click . To remove a signal
from the input or output list, click . When you have selected multiple signals, you can
reorder them using and . For more information on how to specify signal locations
for a tuning goal, see “Specify Goals for Interactive Tuning” on page 14-39.
Weights
Use the Left weight WL and Right weight WR text boxes to specify the frequency-
weighting functions for the tuning goal. H(s) = WL(s)T(s)WR(s), where T(s) is the transfer
function from specified inputs to outputs.
WL provides the weighting for the output channels of H(s), and WR provides the weighting
for the input channels. You can specify scalar weights or frequency-dependent weighting.
To specify a frequency-dependent weighting, use a numeric LTI model whose magnitude
represents the desired weighting function. For example, enter tf(1,[1 0.01]) to
specify a high weight at low frequencies that rolls off above 0.01 rad/s.
14-167
14 Control System Tuning
If the tuning goal constrains a MIMO transfer function, scalar or SISO weighting
functions automatically expand to any input or output dimension. You can specify different
weights for each channel by specifying matrices or MIMO weighting functions. The
dimensions H(s) must be commensurate with the dimensions of WL and WR. For example,
if the constrained transfer function has two inputs, you can specify diag([1 10]) as
WR.
If you are tuning in discrete time, you can specify the weighting functions as discrete-time
models with the same sampling time as you use for tuning. If you specify the weighting
functions in continuous time, the tuning software discretizes them. Specifying the
weighting functions in discrete time gives you more control over the weighting functions
near the Nyquist frequency.
Options
Use this section of the dialog box to specify additional characteristics of the step response
goal.
Enter the target value of ν in the text box. To enforce an excess of passivity at the
specified inputs, set ν > 0. To permit a shortage of passivity, set ν < 0. By default, the
passivity goal enforces ν = 0, passive at the inputs with no required excess of
passivity.
• Minimum output passivity index
Enter the target value of ρ in the text box. To enforce an excess of passivity at the
specified outputs, set ρ > 0. To permit a shortage of passivity, set ρ < 0. By default, the
passivity goal enforces ρ = 0, passive at the outputs with no required excess of
passivity.
• Enforce goal in frequency range
Limit the enforcement of the tuning goal to a particular frequency band. Specify the
frequency band as a row vector of the form [min,max], expressed in frequency units
of your model. For example, to create a tuning goal that applies only between 1 and
100 rad/s, enter [1,100]. By default, the tuning goal applies at all frequencies for
continuous time, and up to the Nyquist frequency for discrete time.
• Apply goal to
Use this option when tuning multiple models at once, such as an array of models
obtained by linearizing a Simulink model at different operating points or block-
14-168
Weighted Passivity Goal
parameter values. By default, active tuning goals are enforced for all models. To
enforce a tuning requirement for a subset of models in an array, select Only Models.
Then, enter the array indices of the models for which the goal is enforced. For
example, suppose you want to apply the tuning goal to the second, third, and fourth
models in a model array. To restrict enforcement of the requirement, enter 2:4 in the
Only Models text box.
For more information about tuning for multiple models, see “Robust Tuning
Approaches” (Robust Control Toolbox).
Algorithms
When you tune a control system, the software converts each tuning goal into a normalized
scalar value f(x). Here, x is the vector of free (tunable) parameters in the control system.
The software then adjusts the parameter values to minimize f(x) or to drive f(x) below 1 if
the tuning goal is a hard constraint.
For Weighted Passivity Goal, for a closed-loop transfer function T(s,x) from the
specified inputs to the specified outputs, and the weighted transfer function H(s,x) =
WL(s)T(s,x)WR(s), f(x) is given by:
R
f ( x) = , Rmax = 106.
1 + R Rmax
R is the relative sector index (see getSectorIndex) of [H(s,x); I], for the sector
represented by:
Ê 2r -I ˆ
Q=Á ˜,
Ë -I 2n ¯
where ρ is the minimum output passivity index and ν is the minimum input passivity index
specified in the dialog box. Rmax is fixed at 106, included to avoid numeric errors for very
large R.
This tuning goal imposes an implicit minimum-phase constraint on the weighted transfer
function H + I. The transmission zeros of H + I are the stabilized dynamics for this tuning
goal. The Minimum decay rate and Maximum natural frequency tuning options
control the lower and upper bounds on these implicitly constrained dynamics. If the
14-169
14 Control System Tuning
optimization fails to meet the default bounds, or if the default bounds conflict with other
requirements, on the Tuning tab, use Tuning Options to change the defaults.
See Also
Related Examples
• “Specify Goals for Interactive Tuning” on page 14-39
• “Manage Tuning Goals” on page 14-179
• “Visualize Tuning Goals” on page 14-189
• “About Passivity and Passivity Indices” on page 10-2
14-170
Poles Goal
Poles Goal
Purpose
Constrain the dynamics of the closed-loop system, specified feedback loops, or specified
open-loop configurations, when using Control System Tuner.
Description
Poles Goal constrains the dynamics of your entire control system or of specified feedback
loops of your control system. Constraining the dynamics of a feedback loop means
constraining the dynamics of the sensitivity function measured at a specified location in
the control system.
Using Poles Goal, you can specify finite minimum decay rate or minimum damping for the
poles in the control system or specified loop. You can specify a maximum natural
frequency for these poles, to eliminate fast dynamics in the tuned control system.
14-171
14 Control System Tuning
In Control System Tuner, the shaded area on the plot represents the region in the
frequency domain where the pole location constraints are not met.
Creation
In the Tuning tab of Control System Tuner, select New Goal > Constraint on closed-
loop dynamics to create a Poles Goal.
Command-Line Equivalent
When tuning control systems at the command line, use TuningGoal.Poles to specify a
disturbance rejection goal.
Feedback Configuration
Use this section of the dialog box to specify the portion of the control system for which
you want to constrain dynamics. You can also specify loop-opening locations for
evaluating the tuning goal.
• Entire system
Select this option to constrain the locations of closed-loop poles of the control system.
• Specific feedback loop(s)
Select this option to specify one or more feedback loops to constrain. Specify a
feedback loop by selecting a signal location in your control system. Poles Goal
constrains the dynamics of the sensitivity function measured at that location. (See
getSensitivity for information about sensitivity functions.)
To constrain the dynamics of a SISO loop, select a single-valued location. For example,
to constrain the dynamics of the sensitivity function measured at a location named
'y', click Add signal to list and select 'y'. To constrain the dynamics of a MIMO
loop, select multiple signals or a vector-valued signal.
• Compute poles with the following loops open
Select one or more signal locations in your model at which to open a feedback loop for
the purpose of evaluating this tuning goal. The tuning goal is evaluated against the
14-172
Poles Goal
Tip To highlight any selected signal in the Simulink model, click . To remove a signal
from the input or output list, click . When you have selected multiple signals, you can
reorder them using and . For more information on how to specify signal locations
for a tuning goal, see “Specify Goals for Interactive Tuning” on page 14-39.
Pole Location
Use this section of the dialog box to specify the limits on pole locations.
Enter the target minimum decay rate for the system poles. Closed-loop system poles
that depend on the tunable parameters are constrained to satisfy Re(s) < -
MinDecay for continuous-time systems, or log(|z|) < -MinDecay*Ts for discrete-
time systems with sample time Ts. This constraint helps ensure stable dynamics in the
tuned system.
Enter the target minimum damping of closed-loop poles of tuned system, as a value
between 0 and 1. Closed-loop system poles that depend on the tunable parameters are
constrained to satisfy Re(s) < -MinDamping*|s|. In discrete time, the damping
ratio is computed using s = log(z)/Ts.
Enter the target maximum natural frequency of poles of tuned system, in the units of
the control system model you are tuning. When you tune the control system using this
requirement, closed-loop system poles that depend on the tunable parameters are
constrained to satisfy |s| < MaxFrequency for continuous-time systems, or |
14-173
14 Control System Tuning
log(z)| < MaxFrequency*Ts for discrete-time systems with sample time Ts. This
constraint prevents fast dynamics in the control system.
Options
Use this section of the dialog box to specify additional characteristics of the poles goal.
Limit the enforcement of the tuning goal to a particular frequency band. Specify the
frequency band as a row vector of the form [min,max], expressed in frequency units
of your model. For example, to create a tuning goal that applies only between 1 and
100 rad/s, enter [1,100]. By default, the tuning goal applies at all frequencies for
continuous time, and up to the Nyquist frequency for discrete time.
The Poles Goal applies only to poles with natural frequency within the range you
specify.
• Apply goal to
Use this option when tuning multiple models at once, such as an array of models
obtained by linearizing a Simulink model at different operating points or block-
parameter values. By default, active tuning goals are enforced for all models. To
enforce a tuning requirement for a subset of models in an array, select Only Models.
Then, enter the array indices of the models for which the goal is enforced. For
example, suppose you want to apply the tuning goal to the second, third, and fourth
models in a model array. To restrict enforcement of the requirement, enter 2:4 in the
Only Models text box.
For more information about tuning for multiple models, see “Robust Tuning
Approaches” (Robust Control Toolbox).
Algorithms
When you tune a control system, the software converts each tuning goal into a normalized
scalar value f(x). Here, x is the vector of free (tunable) parameters in the control system.
The software then adjusts the parameter values to minimize f(x) or to drive f(x) below 1 if
the tuning goal is a hard constraint.
14-174
See Also
For Poles Goal, f(x) reflects the relative satisfaction or violation of the goal. For example,
if your Poles Goal constrains the closed-loop poles of a feedback loop to a minimum
damping of ζ = 0.5, then:
• f(x) = 1 means the smallest damping among the constrained poles is ζ = 0.5 exactly.
• f(x) = 1.1 means the smallest damping ζ = 0.5/1.1 = 0.45, roughly 10% less than the
target.
• f(x) = 0.9 means the smallest damping ζ = 0.5/0.9 = 0.55, roughly 10% better than the
target.
See Also
Related Examples
• “Specify Goals for Interactive Tuning” on page 14-39
• “Manage Tuning Goals” on page 14-179
• “Visualize Tuning Goals” on page 14-189
14-175
14 Control System Tuning
Purpose
Constrain the dynamics of a specified tunable block in the tuned control system, when
using Control System Tuner.
Description
Controller Poles Goal constrains the dynamics of a tunable block in your control system
model. Controller Poles Goal can impose a stability constraint on the specified block. You
can also specify a finite minimum decay rate, a minimum damping rate, or a maximum
natural frequency for the poles of the block. These constraints allow you to eliminate fast
dynamics and control ringing in the response of the tunable block.
In Control System Tuner, the shaded area on the plot represents the region in the
frequency domain where the pole location constraints are not met. The constraint applies
to all poles in the block except fixed integrators, such as the I term of a PID controller.
14-176
Controller Poles Goal
Creation
In the Tuning tab of Control System Tuner, select New Goal > Constraint on
controller dynamics to create a Controller Poles Goal.
Command-Line Equivalent
If the block you want to constrain is not in the list, add it to the Tuned Blocks list. In
Control System Tuner, in the Tuning tab, click Select Blocks. For more information
about adding tuned blocks, see “Specify Blocks to Tune in Control System Tuner” on page
14-24.
Enter the desired minimum decay rate for the poles of the tunable block. Poles of the
block are constrained to satisfy Re(s) < -MinDecay for continuous-time blocks, or
log(|z|) < -MinDecay*Ts for discrete-time blocks with sample time Ts.
Specify a nonnegative value to ensure that the block is stable. If you specify a negative
value, the tuned block can include unstable poles.
• Minimum damping
Enter the desired minimum damping ratio of poles of the tunable block, as a value
between 0 and 1. Poles of the block that depend on the tunable parameters are
constrained to satisfy Re(s) < -MinDamping*|s|. In discrete time, the damping
ratio is computed using s=log(z)/Ts.
14-177
14 Control System Tuning
Enter the target maximum natural frequency of poles of the tunable block, in the units
of the control system model you are tuning. Poles of the block are constrained to
satisfy |s| < MaxFrequency for continuous-time blocks, or |log(z)| <
MaxFrequency*Ts for discrete-time blocks with sample time Ts. This constraint
prevents fast dynamics in the tunable block.
Algorithms
When you tune a control system, the software converts each tuning goal into a normalized
scalar value f(x). Here, x is the vector of free (tunable) parameters in the control system.
The software then adjusts the parameter values to minimize f(x) or to drive f(x) below 1 if
the tuning goal is a hard constraint.
For Controller Poles Goal, f(x) reflects the relative satisfaction or violation of the goal.
For example, if your Controller Poles Goal constrains the pole of a tuned block to a
minimum damping of ζ = 0.5, then:
See Also
Related Examples
• “Specify Goals for Interactive Tuning” on page 14-39
• “Manage Tuning Goals” on page 14-179
• “Visualize Tuning Goals” on page 14-189
14-178
Manage Tuning Goals
By default, new goals are designated soft goals. In the Tuning tab, click Manage
Goals to open the Manage tuning goals dialog box. Check Hard for any goal to
designate it a hard goal.
You can also designate any tuning goal as inactive for tuning. In this case the software
ignores the tuning goal entirely. Use this dialog box to select which tuning goals are
active when you tune the control system. Active is checked by default for any new goals.
Uncheck Active for any design goal that you do not want enforced.
For example, if you tune with the following configuration, Control System Tuner optimizes
StepRespGoal1, subject to MarginsGoal1. The tuning goal PolesGoal1 is ignored.
14-179
14 Control System Tuning
All tuning goals you have created in the Control System Tuner session are listed in the
dialog box. To edit an existing tuning goal, select it in the list and click Edit. To delete a
tuning goal from the list, select it and click Remove.
To add more tuning goals to the list, in Control System Tuner, in the Tuning tab, click
New Goal. For more information about creating tuning goals, see “Specify Goals for
Interactive Tuning” on page 14-39.
14-180
Generate MATLAB Code from Control System Tuner for Command-Line Tuning
Tip You can also save a Control System Tuner session to reproduce within Control
System Tuner. To do so, in the Control System tab, click Save Session.
To generate a MATLAB script in Control System Tuner, in the Tuning tab, click Tune .
Select Script with current values.
The MATLAB Editor displays the generated script, which script reproduces
programmatically the current tuning configuration of Control System Tuner.
14-181
14 Control System Tuning
For example, suppose you generate a MATLAB script after completing all steps in the
example “Control of a Linear Electric Actuator Using Control System Tuner” on page 17-
115. The generated script computes the operating point used for tuning, designates the
blocks to tune, creates the tuning goals, and performs other operations to reproduce the
result at the command line.
The first section of the script creates the slTuner interface to the Simulinkmodel
(rct_linact in this example). The slTuner interface stores a linearization of the model
and parameterizations of the blocks to tune.
%% Create system data with slTuner interface
TunedBlocks = {'rct_linact/Current Controller/Current PID'; ...
'rct_linact/Speed Controller/Speed PID'};
AnalysisPoints = {'rct_linact/Speed Demand (rpm)/1'; ...
'rct_linact/Current Sensor/1'; ...
'rct_linact/Hall Effect Sensor/1'; ...
'rct_linact/Speed Controller/Speed PID/1'; ...
'rct_linact/Current Controller/Current PID/1'};
OperatingPoints = 0.5;
% Specify the custom options
Options = slTunerOptions('AreParamsTunable',false);
% Create the slTuner object
CL0 = slTuner('rct_linact',TunedBlocks,AnalysisPoints,OperatingPoints,Options);
The slTuner interface also specifies the operating point at which the model is linearized,
and marks as analysis points all the signal locations required to specify the tuning goals
for the example. (See “Create and Configure slTuner Interface to Simulink Model” on
page 14-212.)
If you are tuning a control system modeled in MATLAB instead of Simulink, the first
section of the script constructs a genss model that has equivalent dynamics and
parameterization to the genss model of the control system that you specified Control
System Tuner.
Next, the script creates the three tuning goals specified in the example. The script uses
TuningGoal objects to capture these tuning goals. For instance, the script uses
TuningGoal.Tracking to capture the Tracking Goal of the example.
%% Create tuning goal to follow reference commands with prescribed performance
% Inputs and outputs
Inputs = {'rct_linact/Speed Demand (rpm)/1'};
Outputs = {'rct_linact/Hall Effect Sensor/1[rpm]'};
% Tuning goal specifications
ResponseTime = 0.1; % Approximately reciprocal of tracking bandwidth
DCError = 0.001; % Maximum steady-state error
PeakError = 1; % Peak error across frequency
% Create tuning goal for tracking
TR = TuningGoal.Tracking(Inputs,Outputs,ResponseTime,DCError,PeakError);
TR.Name = 'TR'; % Tuning goal name
14-182
See Also
After creating the tuning goals, the script sets any algorithm options you had set in
Control System Tuner. The script also designates tuning goals as soft or hard goals,
according to the configuration of tuning goals in Control System Tuner. (See “Manage
Tuning Goals” on page 14-179.)
In this example, all the goals are designated as soft goals when the script is generated.
Therefore, HardGoals is empty.
Finally, the script tunes the control system by calling systune on the slTuner interface
using the tuning goals and options.
The script also includes an optional call to viewGoal, which displays graphical
representations of the tuning goals to aid you in interpreting and validating the tuning
results. Uncomment this line of code to generate the plots.
You can add calls to functions such getIOTransfer to make the script generate
additional analysis plots.
See Also
Related Examples
• “Create and Configure slTuner Interface to Simulink Model” on page 14-212
• “Tune Control System at the Command Line” on page 14-223
• “Validate Tuned Control System” on page 14-227
14-183
14 Control System Tuning
Minimize max fi ( x ) subject to max g j ( x ) < 1 , for xmin < x < xmax .
i j
xmin and xmax are the minimum and maximum values of the free parameters of the control
system. (For information about the specific functions used to evaluate each type of
requirement, see the reference pages for each tuning goal.)
When you use both soft and hard tuning goals, the software solves the optimization as a
sequence of subproblems of the form:
min max ( a f ( x ) , g ( x ) ) .
x
The software adjusts the multiplier α so that the solution of the subproblems converges to
the solution of the original constrained optimization problem.
The tuning software reports the final scalar values for each tuning goal. When the final
value of fi(x) or gj(x) is less than 1, the corresponding tuning goal is satisfied. Values
greater than 1 indicate that the tuning goal is not satisfied for at least some conditions.
For instance, a tuning goal that describes a frequency-domain constraint might be
satisfied at some frequencies and not at others. The closer the value is to 1, the closer the
tuning goal is to being satisfied. Thus these values give you an overview of how
successfully the tuned system meets your requirements.
14-184
Interpret Numeric Tuning Results
The form in which the software presents the optimized tuning-goal values depends on
whether you are tuning with Control System Tuner or at the command line.
By default, systune displays the best achieved final values of the tuning goals in the
command window. For instance, in the example “PID Tuning for Setpoint Tracking vs.
Disturbance Rejection” on page 17-14, systune is called with one soft requirement, R1,
and two hard requirements R2 and R3.
T1 = systune(T0,R1,[R2 R3]);
This display indicates that the largest optimized value of the hard tuning goals is less than
1, so both hard goals are satisfied. The soft goal value is slightly greater than one,
indicating that the soft goal is nearly satisfied. You can use tuning-goal plots to see in
what regimes and by how much the tuning goals are violated. (See “Visualize Tuning
Goals” on page 14-189.)
You can obtain additional information about the optimization progress and values using
the info output of systune. To make systune display additional information during
tuning, use systuneOptions.
In Control System Tuner, when you click , the app compiles a Tuning Report
summarizing the best achieved values of fi(x) and gj(x). To view the tuning report
immediately after tuning a control system, click Tuning Report at the bottom-right
corner of Control System Tuner.
14-185
14 Control System Tuning
The tuning report displays the final fi(x) and gj(x) values obtained by the algorithm.
The Hard Goals area shows the minimized gi(x) values and indicates which are satisfied.
The Soft Goals area highlights the largest of the minimized fi(x) values as Worst Value,
and lists the values for all the requirements. In this example, the hard goal is satisfied,
while the soft goals are nearly satisfied. As in the command-line case, you can use tuning-
goal plots to see where and by how much tuning goals are violated. (See “Visualize
Tuning Goals” on page 14-189.)
14-186
Interpret Numeric Tuning Results
Tip You can view a report from the most recent tuning run at any time. In the Tuning
tab, click Tune , and select Tuning Report.
• Designate tuning goals that are must-have requirements as hard goals. Or, relax
tuning goals that are not absolute requirements by designating them as soft goals.
• Limit the frequency range in which frequency-domain goals are enforced.
• In Control System Tuner, use the Enforce goal in frequency range field of the
tuning goal dialog box.
• At the command line, use the Focus property of the TuningGoal object.
If the tuning results do satisfy your design requirements, you can validate the tuned
control system as described in “Validate Tuned Control System” on page 14-227.
14-187
14 Control System Tuning
See Also
evalGoal | systune | systune (for slTuner) | viewGoal
Related Examples
• “Visualize Tuning Goals” on page 14-189
• “Validate Tuned Control System” on page 14-227
14-188
Visualize Tuning Goals
Tuning-Goal Plots
How you obtain tuning-goal plots depends on your work environment.
The form of the tuning-goal plot depends on the specific tuning goal you use. For
instance, for time-domain tuning goals, the tuning-goal plot is a time-domain plot of the
relevant system response. The following plot, adapted from the example “MIMO Control
of Diesel Engine” on page 17-183, shows a typical tuning-goal plot for a time-domain
disturbance-rejection goal. The dashed lines represent the worst acceptable step
response specified in the tuning goal. The solid line shows the corresponding response of
the tuned system.
14-189
14 Control System Tuning
Similarly, the plots for frequency-domain tuning goals show the target response and the
tuned response in the frequency domain. The following plot, adapted from the example
“Fixed-Structure Autopilot for a Passenger Jet” on page 17-225, shows a plot for a gain
goal (TuningGoal.Gain at the command line). This tuning goal limits the gain between
a specified input and output to a frequency-dependent profile. In the plot, the dashed line
shows the gain profile specified in the tuning goal. If the tuned system response (solid
line) enters the shaded region, the tuning goal is violated. In this case, the tuning goal is
satisfied at all frequencies.
14-190
Visualize Tuning Goals
• You tune a control system in discrete time, but specify the gain profile in continuous
time.
• The software modifies the asymptotes of the specified gain profile to improve numeric
stability.
14-191
14 Control System Tuning
When you tune a discrete-time control system, you can specify frequency-dependent
tuning goals using discrete-time or continuous-time transfer functions. If you use a
continuous-time transfer function, the tuning algorithm discretizes the transfer function
before tuning. For instance, suppose that you specify a tuning goal as follows.
Suppose further that you use the tuning goal with systune to tune a discrete-time genss
model or slTuner interface. CL is the resulting tuned control system. To examine the
result, generate a tuning-goal plot.
viewGoal(Req,CL)
14-192
Visualize Tuning Goals
The plot shows W, the continuous-time maximum loop gain that you specified, as a dashed
line. The shaded region shows the discretized version of W that systune uses for tuning.
The discretized maximum loop gain cuts off at the Nyquist frequency corresponding to
the sample time of CL. Near that cutoff, the shaded region diverges from the dashed line.
The plot highlights that sometimes it is preferable to specify tuning goals for discrete-
time tuning using discrete-time gain profiles. In particular, specifying a discrete-time
profile gives you more control over the behavior of the gain profile near the Nyquist
frequency.
14-193
14 Control System Tuning
When you use a tuning goal with a frequency-dependent specification, the tuning
algorithm uses a frequency-weighting function to compute the normalized value of the
tuning goal. This weighting function is derived from the gain profile that you specify. For
numeric tractability, weighting functions must be stable and proper. For numeric stability,
their dynamics must be in the same frequency range as the control system dynamics. For
these reasons, the software might adjust the specified gain profile to eliminate
undesirable low-frequency or high-frequency dynamics or asymptotes. The process of
modifying the tuning goal for better numeric conditioning is called regularization.
14-194
Visualize Tuning Goals
Here the control bandwidth is about 1 rad/s and the gain profile has two zeros at s = 0,
which become unstable poles in the weighting function (see TuningGoal.Tracking for
details). The regularization moves these zeros to about 0.01 rad/s, and the maximum
tracking error levels off at about 10–3 (0.1%). If you need better tracking accuracy, you
can explicitly specify the cutoff frequency in the error profile.
14-195
14 Control System Tuning
However, for numeric safety, the regularized weighting function always levels off at very
low and very high frequencies, regardless of the specified gain profile.
When you are working at the command line, you can obtain the regularized gain profile
using the getWeight or getWeights commands. For details, see the reference pages for
the individual tuning goals for which the tuning algorithm performs regularization:
• TuningGoal.Gain
• TuningGoal.LoopShape
• TuningGoal.MaxLoopGain
14-196
See Also
• TuningGoal.MinLoopGain
• TuningGoal.Rejection
• TuningGoal.Sensitivity
• TuningGoal.StepRejection
• TuningGoal.Tracking
In Control System Tuner, you cannot view the regularized weighting functions directly.
Instead, use the tuning-goal commands to generate an equivalent tuning goal, and use
getWeight or getWeights to access the regularized functions.
• Designate tuning goals that are must-have requirements as hard goals. Or, relax
tuning goals that are not absolute requirements by designating them as soft goals.
• Limit the frequency range in which frequency-domain goals are enforced.
• In Control System Tuner, use the Enforce goal in frequency range field of the
tuning goal dialog box.
• At the command line, use the Focus property of the TuningGoal object.
If the tuning results do satisfy your design requirements, you can validate the tuned
control system as described in “Validate Tuned Control System” on page 14-227.
See Also
viewGoal
Related Examples
• “Interpret Numeric Tuning Results” on page 14-184
• “Create Response Plots in Control System Tuner” on page 14-198
• “Validate Tuned Control System” on page 14-227
14-197
14 Control System Tuning
This example creates response plots for analyzing the sample model rct_helico.
In Control System Tuner, in the Control System tab, click New Plot. Select the type
of plot you want to create.
A new plot dialog box opens in which you specify the inputs and outputs of the portion of
your control system whose response you want to plot. For example, select New step to
create a step response plot from specified inputs to specified outputs of your system.
14-198
Create Response Plots in Control System Tuner
Choose which transfer function associated with the specified inputs and outputs you want
to analyze.
For most response plots types, the Select Response to Plot menu lets you choose one of
the following transfer functions:
Type a name for the response in the Response Name text box. Once you have specified
signal locations defining the response, Control System Tuner stores the response under
this name. When you create additional new response plots, the response appears by this
name in Select Response to Plot menu.
Specify the signal locations in your control system at which to evaluate the selected
response. For example, the step response plot displays the response of the system at one
14-199
14 Control System Tuning
or more output locations to a unit step applied at one or more input locations. Use the
Specify input signals and Specify output signals sections of the dialog box to specify
these locations. (Other tuning goal types, such as loop-shape or stability margins, require
you to specify only one location for evaluation. The procedure for specifying the location
is the same as illustrated here.)
Under Specify input signals, click Add signal to list. A list of available input
locations appears.
If the signal you want to designate as a step-response input is in the list, click the signal
to add it to the step-response inputs. If the signal you want to designate does not appear,
and you are tuning a Simulink model, click Select signal from model.
In the Select signals dialog box, build a list of the signals you want. To do so, click
signals in the Simulink model editor. The signals that you click appear in the Select
signals dialog box. Click one signal to create a SISO response, and click multiple signals
to create a MIMO response.
14-200
Create Response Plots in Control System Tuner
The signal or signals you selected now appear in the list of step-response inputs in the
new-plot dialog box.
Similarly, specify the locations at which the step response is measured to the step-
response outputs list. For example, the following configuration plots the MIMO response
to a step input applied at theta-ref and phi-ref and measured at theta and phi in
the Simulink model rct_helico.
14-201
14 Control System Tuning
Tip To highlight any selected signal in the Simulink model, click . To remove a signal
from the input or output list, click . When you have selected multiple signals, you can
You can evaluate most system responses with loops open at one or more locations in the
control system. Click Add loop opening location to list to specify such locations for
the response.
When you have finished specifying the response, click Plot in the new plot dialog box. The
new response appears in the Responses section of the Data Browser. A new figure opens
14-202
Create Response Plots in Control System Tuner
displaying the response plot. When you tune your control system, you can refer to this
figure to evaluate the performance of the tuned system.
Tip To edit the specifications of the response, double-click the response in the Data
Browser. Any plots using that response update to reflect the edited response.
14-203
14 Control System Tuning
See Also
Related Examples
• “Compare Performance of Multiple Tuned Controllers” on page 14-207
• “Examine Tuned Controller Parameters in Control System Tuner” on page 14-205
• “Visualize Tuning Goals” on page 14-189
14-204
Examine Tuned Controller Parameters in Control System Tuner
• In the Data Browser, in the Tuned Blocks area, select the block whose parameters
you want to view. A text summary of the block and its current parameter values
appears in the Data Browser in the Data Preview area.
• In the Data Browser, in the Tuned Blocks area, double-click the block whose
parameters you want to view. The Tuned Block Editor opens, displaying the current
14-205
14 Control System Tuning
Note To find a tuned block in the Simulink model, right-click the block name in the Data
Browser and select Highlight.
See Also
Related Examples
• “View and Change Block Parameterization in Control System Tuner” on page 14-26
14-206
Compare Performance of Multiple Tuned Controllers
This example compares tuning results for the sample model rct_linact.
After tuning a control system with a first set of design requirements, store the design in
Control System Tuner.
In the Control System tab, click Store. The stored design appears in the Data
Browser in the Designs area.
14-207
14 Control System Tuning
Change the name of the stored design, if desired, by right-clicking on the data browser
entry.
14-208
Compare Performance of Multiple Tuned Controllers
In the Tuning tab, make any desired changes to the tuning goals for the second design.
For example, add new tuning goals or edit existing tuning goals to change specifications.
Or, in Manage Goals, change which tuning goals are active and which are
designated hard constraints or soft requirements.
When you are ready, retune the control system with the new set of tuning goals. Click
Tune. Control System Tuner updates the current design (the current set of controller
parameters) with the new tuned design. All existing plots, which by default show the
current design, are updated to reflect the new current design.
Update all plots to reflect both the new design and the stored design. In the Control
System tab, click Compare. The Compare Designs dialog box opens.
In the Compare Designs dialog box, the current design is checked by default. Check the
box for the design you want to compare to the current design. All response plots and
14-209
14 Control System Tuning
tuning goal plots update to reflect the checked designs. The solid trace corresponds to the
current design. Other designs are identified by name in the plot legend.
Use the same procedure save and compare as many designs as you need.
Under some conditions, it is useful to restore the tuned parameter values from a
previously saved design as the current design. For example, clicking Update Blocks
writes the current parameter values to the Simulink model. If you decide to test a stored
controller design in your full nonlinear model, you must first restore those stored values
as the current design.
14-210
See Also
To do so, click Retrieve. Select the stored design that you want to make the current
design.
See Also
Related Examples
• “Create Response Plots in Control System Tuner” on page 14-198
14-211
14 Control System Tuning
For this example, create and configure an slTuner interface for tuning the Simulink
model rct_helico, a multiloop controller for a rotorcraft. Open the model.
open_system('rct_helico');
The control system consists of two feedback loops. The inner loop (static output feedback)
provides stability augmentation and decoupling. The outer loop (PI controllers) provides
the desired setpoint tracking performance.
Suppose that you want to tune this model to meet the following control objectives:
14-212
Create and Configure slTuner Interface to Simulink Model
• Track setpoint changes in theta, phi, and r with zero steady-state error, specified
rise times, minimal overshoot, and minimal cross-coupling.
• Limit the control bandwidth to guard against neglected high-frequency rotor dynamics
and measurement noise.
• Provide strong multivariable gain and phase margins (robustness to simultaneous
gain/phase variations at the plant inputs and outputs).
The systune command can jointly tune the controller blocks SOF and the PI controllers
to meet these design requirements. The slTuner interface sets up this tuning task.
ST0 = slTuner('rct_helico',{'PI1','PI2','PI3','SOF'});
This command initializes the slTuner interface with the three PI controllers and the SOF
block designated as tunable. Each tunable block is automatically parameterized according
to its type and initialized with its value in the Simulink model.
To configure the slTuner interface, designate as analysis points any signal locations of
relevance to your design requirements. First, add the outputs and reference inputs for the
tracking requirements.
addPoint(ST0,{'theta-ref','theta','phi-ref','phi','r-ref','r'});
Configure the slTuner interface for the stability margin requirements. Designate as
analysis points the plant inputs and outputs (control and measurement signals) where the
stability margins are measured.
addPoint(ST0,{'u','y'});
ST0
14-213
14 Control System Tuning
Block 2: rct_helico/PI2
Block 3: rct_helico/PI3
Block 4: rct_helico/SOF
8 Analysis points:
--------------------------
Point 1: Port 1 of rct_helico/theta-ref
Point 2: Signal "theta", located at port 1 of rct_helico/Demux1
Point 3: Port 1 of rct_helico/phi-ref
Point 4: Signal "phi", located at port 2 of rct_helico/Demux1
Point 5: Port 1 of rct_helico/r-ref
Point 6: Signal "r", located at port 3 of rct_helico/Demux1
Point 7: Signal "u", located at port 1 of rct_helico/Mux3
Point 8: Signal "y", located at port 1 of rct_helico/Helicopter
No permanent openings. Use the addOpening command to add new permanent openings.
Properties with dot notation get/set access:
Parameters : []
OperatingPoints : [] (model initial condition will be used.)
BlockSubstitutions : []
Options : [1x1 linearize.SlTunerOptions]
Ts : 0
In the command window, click on any highlighted signal to see its location in the Simulink
model.
In addition to specifying design requirements, you can use analysis points for extracting
system responses. For example, extract and plot the step responses between the
reference signals and 'theta', 'phi', and 'r'.
T0 = getIOTransfer(ST0,{'theta-ref','phi-ref','r-ref'},{'theta','phi','r'});
stepplot(T0,1)
14-214
Create and Configure slTuner Interface to Simulink Model
All the step responses are unstable, including the cross-couplings, because this model has
not yet been tuned.
After you tune the model, you can similarly use the designated analysis points to extract
system responses for validating the tuned system. If you want to examine system
responses at locations that are not needed to specify design requirements, add these
locations to the slTuner interface as well. For example, plot the sensitivity function
measured at the output of the block roll-off 2.
addPoint(ST0,'dc')
dcS0 = getSensitivity(ST0,'dc');
bodeplot(dcS0)
14-215
14 Control System Tuning
Suppose you want to change the parameterization of tunable blocks in the slTuner
interface. For example, suppose that after tuning the model, you want to test whether
changing from PI to PID controllers yields improved results. Change the parameterization
of the three PI controllers to PID controllers.
setBlockParam(ST0,'PI1',PID1,'PI2',PID2,'PI3',PID3);
14-216
See Also
After you configure the slTuner interface to your Simulink model, you can create tuning
goals and tune the model using systune or looptune.
See Also
addBlock | addPoint | getIOTransfer | getSensitivity | setBlockParam |
slTuner
Related Examples
• “Mark Signals of Interest for Control System Analysis and Design” on page 2-89
• “Multiloop Control of a Helicopter” on page 17-216
• “Control of a Linear Electric Actuator” on page 17-105
14-217
14 Control System Tuning
• Tuning in Control System Tuner using a “Margins Goal” on page 14-148 or “Quick
Loop Tuning” on page 14-58.
14-218
Stability Margins in Control System Tuning
viewGoal(Req,S)
For MIMO systems, gain and phase margins are interpreted as follows:
• Gain margin: Stability is preserved when the gain increases or decreases by up to the
gain margin value in each channel of the feedback loop.
• Phase margin: Stability is preserved when the phase increases or decreases by up to
the phase margin value in each channel of the feedback loop.
In MIMO systems, the gain or phase can change in all channels at once, and by a different
amount in each channel. The Margins Goal and TuningGoal.Margins rely on the notion
of disk margin for MIMO systems. (See “Algorithm” on page 14-222.) Like SISO stability
margins, gain and phase margins in MIMO systems typically vary across frequency.
14-219
14 Control System Tuning
For example, if the gain margin plot in Control System Tuner indicates a 10 dB margin at
a particular frequency, then trace the contour starting at (Gain,Phase) = (10,0) to
see how a given amount of phase variation reduces the allowable gain variation at that
frequency. For example, if the phase can vary by 30 degrees than the gain can only vary
by about 8.4 dB (red mark).
14-220
Stability Margins in Control System Tuning
These gain and phase margin curves are obtained using an exact calculation involving μ-
analysis. For computational efficiency, however, the tuning algorithm uses an approximate
calculation that can yield smaller margins in parts of the frequency range. To see the
lower bound used by the tuner, right-click on the plot, and select Systems > Tuned
Lower Bound.
If there is a significant gap between the true margins and the tuner approximation, try
increasing the D-scaling order. The default order is zero (static scaling). For tuning in
Control System Tuner, set the D-scaling order in the Margins Goal dialog box. For
command-line tuning, set this value using the ScalingOrder property of
TuningGoal.Margins.
14-221
14 Control System Tuning
Algorithm
The gain and phase margin values are both derived from the disk margin (see
loopmargin). The disk margin measures the radius of a circular exclusion region
centered near the critical point. This radius is a decreasing function of the scaled norm:
-1
min D -1 ( I - L ( jw ) ) ( I + L ( jw ) ) D .
D diagonal 2
Unlike the traditional gain and phase margins, the disk margins and associated gain and
phase margins guarantee that the open-loop response L(jω) stays at a safe distance from
the critical point at all frequencies.
See Also
TuningGoal.Margins | loopmargin
More About
• “Loop Shape and Stability Margin Specifications” on page 17-43
• “Margins Goal” on page 14-148
14-222
Tune Control System at the Command Line
The systune command lets you designate one or more design goals as hard goals. This
designation gives you a way to differentiate must-have goals from nice-to-have tuning
goals.systune attempts to satisfy hard requirements by driving their associated cost
functions below 1. Subject to that constraint, the software comes as close as possible to
satisfying remaining (soft) requirements. For best results, make sure you can obtain a
reasonable design with all goals treated as soft goals before attempting to enforce any
goal as a hard constraint.
Organize your TuningGoal objects into a vector of soft requirements and a vector of
hard requirements. For example, suppose you have created a tracking requirement, a
rejection requirement, and stability margin requirements at the plant inputs and outputs.
The following commands tune the control system represented by T0, treating the stability
margins as hard goals, the tracking and rejection requirements as soft goals. (T0 is either
a genss model or an slTuner interface previously configured for tuning.)
SoftReqs = [Rtrack,Rreject];
HardReqs = [RmargIn,RmargOut];
[T,fSoft,gHard] = systune(T0,SoftReqs,HardReqs);
systune converts each tuning requirement into a normalized scalar value, f for the soft
constraints and g for the hard constraints. The command adjusts the tunable parameters
of T0 to minimize the f values, subject to the constraint that each g < 1. systune returns
the vectors fSoft and gHard that contain the final normalized values for each tuning
goal in SoftReqs and HardReqs.
Use systuneOptions to configure additional options for the systune algorithm, such as
the number of independent optimization runs, convergence tolerance, and output display
options.
See Also
systune | systune (for slTuner) | systuneOptions
14-223
14 Control System Tuning
More About
• “Interpret Numeric Tuning Results” on page 14-184
14-224
Speed Up Tuning with Parallel Computing Toolbox Software
parpool;
If Automatically create a parallel pool is selected in your preferences, you do not need
to manually start a pool.
options = systuneOptions('RandomStart',20,'UseParallel',true);
Use the options set when you call the tuning command. For example, if you have already
created a tunable control system model, CL0, and tunable controller, and tuning
requirement vectors SoftReqs and HardReqs, the following command uses parallel
computing to tune the control system of CL0 with systune.
[CL,fSoft,gHard,info] = systune(CL0,SoftReq,Hardreq,options);
To learn more about configuring a parallel pool, see the Parallel Computing Toolbox
documentation.
See Also
parpool
14-225
14 Control System Tuning
Related Examples
• “Using Parallel Computing to Accelerate Tuning” on page 17-100
More About
• “Specify Your Parallel Preferences” (Parallel Computing Toolbox)
14-226
Validate Tuned Control System
The tuning tools include analysis functions that let you extract responses from your tuned
control system.
• getIOTransfer
• getLoopTransfer
• getSensitivity
• getCompSensitivity
14-227
14 Control System Tuning
In either case, the extracted responses are represented by state-space (ss) models. You
can analyze these models using commands such as step, bode, sigma, or margin.
For instance, suppose that you are tuning the control system of the example “Multiloop
Control of a Helicopter” on page 17-216. You have created an slTuner interface ST0 for
the Simulink model. You have also specified tuning goals TrackReq, MarginReq1,
MarginReq2, and PoleReq. You tune the control system using systune.
AllReqs = [TrackReq,MarginReq1,MarginReq2,PoleReq];
ST1 = systune(ST0,AllReqs);
Suppose also that ST0 has analysis points that include signals named theta-ref, theta,
phi-ref, and phi. Use getIOTransfer to extract the tuned transfer functions from
theta-ref and phi-ref to theta and phi.
T1 = getIOTransfer(ST1,{'theta-ref','phi-ref'},{'theta','phi'});
step(T1,5)
14-228
Validate Tuned Control System
The step plot shows that the extracted transfer function is the 2-input, 2-output response
from the specified reference inputs to the specified outputs.
For an example that shows how to extract responses from a tuned genss model, see
“Extract Responses from Tuned MATLAB Model at the Command Line” on page 14-232.
For information about extracting and plotting system responses in Control System Tuner,
see “Create Response Plots in Control System Tuner” on page 14-198.
14-229
14 Control System Tuning
Tip If you tune the Simulink model at an operating point other than the model initial
condition, initialize the model at the same operating point before validating the tuned
controller parameters. See “Simulate Simulink Model at Specific Operating Point”
(Simulink Control Design).
To write tuned block values from a tuned slTuner interface to the corresponding
Simulink model, use the writeBlockValue command. For example, suppose ST1 is the
tuned slTuner interface returned by systune. The following command writes the tuned
parameters from ST1 to the associated Simulink model.
writeBlockValue(ST1)
Simulate the Simulink model to evaluate system performance with the tuned parameter
values.
To write tuned block parameters to a Simulink model, in the Control System tab, click
Update Blocks.
14-230
See Also
Control System Tuner transfers the current values of the tuned block parameters to the
corresponding blocks in the Simulink model. Simulate the model to evaluate system
performance using the tuned parameter values.
To update Simulink model with parameter values from a previous design stored in Control
System Tuner, click Retrieve and select the stored design that you want to make the
current design. Then click Update Blocks.
See Also
Related Examples
• “Extract Responses from Tuned MATLAB Model at the Command Line” on page 14-
232
• “Create Response Plots in Control System Tuner” on page 14-198
• “Visualize Tuning Goals” on page 14-189
14-231
14 Control System Tuning
+ +
r C1 C2 G2 G1 y
- -
d2
X2
d1
X1
Suppose you have used systune to tune a genss model of this control system. The result
is a genss model, T, which contains tunable blocks representing the controller elements
C1 and C2. The tuned model also contains AnalysisPoint blocks that represent the
analysis-point locations, X1 and X2.
Analyze the tuned system performance by examining various system responses extracted
from T. For example, examine the response at the output, y, to a disturbance injected at
the point d1.
H1 = getIOTransfer(T,'X1','y');
14-232
See Also
H1 is a genss model that includes the tunable blocks of T. H1 allows you to validate the
disturbance response of your tuned system. For example, you can use analysis commands
such as bodeplot or stepplot to analyze H1. You can also use getValue to obtain the
current value of H1, in which all the tunable blocks are evaluated to their current numeric
values.
Similarly, examine the response at the output to a disturbance injected at the point d2.
H2 = getIOTransfer(T,'X2','y');
You can also generate a two-input, one-output model representing the response of the
control system to simultaneous disturbances at both d1 and d2. To do so, provide
getIOTransfer with a cell array that specifies the multiple input locations.
H = getIOTransfer(T,{'X1','X2'},'y');
See Also
AnalysisPoint | getCompSensitivity | getIOTransfer | getLoopTransfer |
getSensitivity
Related Examples
• “Interpret Numeric Tuning Results” on page 14-184
14-233
15
Loop-Shaping Design
u y
C represents the controller and G represents the plant. The sensor outputsy
(measurement signals) and actuator outputs u (control signals) define the boundary
between plant and controller. The controller is the portion of your control system whose
inputs are measurements, and whose outputs are control signals. Conversely, the plant is
the remainder—the portion of your control system that receives control signals as inputs,
and produces measurements as outputs.
For example, in the control system of the following illustration, the controller C receives
the measurement y, and the reference signal r. The controller produces the controls qL
and qV as outputs.
C
pL qL
+ e PIL
r D G y
pV PIV
-
qV
The controller C has a fixed internal structure. C includes a gain matrix D , the PI
controllers PI_L and PI_V, and a summing junction. The looptune command tunes free
15-2
Structure of Control System for Tuning With looptune
parameters of C such as the gains in D and the proportional and integral gains of PI_L
and PI_V. You can also use looptune to co-tune free parameters in both C and G.
15-3
15 Loop-Shaping Design
1 Parameterize the tunable elements of your controller. You can use predefined
structures such as tunablePID, tunableGain, and tunableTF. Or, you can create
your own structure from elementary tunable parameters (realp).
2 Use model interconnection commands such as series and connect to build a
tunable genss model representing the controller C0.
3 Create a Numeric LTI model on page 1-13 representing the plant G. For co-tuning the
plant and controller, represent the plant as a tunable genss model.
1 Use slTuner to create an interface to the Simulink model of your control system.
When you create the interface, you specify which blocks to tune in your model.
2 Use addPoint to specify the control and measurement signals that define the
boundaries between plant and controller. Use addOpening to mark optional loop-
opening or signal injection sites for specifying and assessing open-loop requirements.
The slTuner interface automatically linearizes your Simulink model. The slTuner
interface also automatically parametrizes the blocks that you specify as tunable blocks.
For more information about this linearization, see the slTuner reference page and “How
Tuned Simulink Blocks Are Parameterized” on page 14-36.
See Also
Related Examples
• “Tune MIMO Control System for Specified Bandwidth” on page 15-6
• “Tuning Feedback Loops with LOOPTUNE” on page 17-325
15-4
See Also
More About
• “Structure of Control System for Tuning With looptune” on page 15-2
15-5
15 Loop-Shaping Design
The plant, G, is a two-input, two-output model (y is a two-element vector signal). For this
example, the transfer function of G is given by:
This sample plant is based on the distillation column described in more detail in the
example “Decoupling Controller for a Distillation Column” on page 17-331.
To tune this control system, you first create a numeric model of the plant. Then you create
tunable models of the controller elements and interconnect them to build a controller
model. Then you use looptune to tune the free parameters of the controller model.
Finally, examine the performance of the tuned system to confirm that the tuned controller
yields desirable performance.
s = tf('s');
G = 1/(75*s+1)*[87.8 -86.4; 108.2 -109.6];
G.InputName = {'qL','qV'};
G.OutputName = 'y';
When you tune the control system, looptune uses the channel names G.InputName and
G.OutputName to interconnect the plant and controller. Therefore, assign these channel
names to match the illustration. When you set G.OutputName = 'y', the
G.OutputName is automatically expanded to {'y(1)';'y(2)'}. This expansion occurs
because G is a two-output system.
15-6
Tune MIMO Control System for Specified Bandwidth
D = tunableGain('Decoupler',eye(2));
D.InputName = 'e';
D.OutputName = {'pL','pV'};
PI_L = tunablePID('PI_L','pi');
PI_L.InputName = 'pL';
PI_L.OutputName = 'qL';
PI_V = tunablePID('PI_V','pi');
PI_V.InputName = 'pV';
PI_V.OutputName = 'qV';
The control system includes several tunable control elements. PI_L and PI_V are tunable
PI controllers. These elements represented by tunablePID models. The fixed control
structure also includes a decoupling gain matrix D, represented by a tunable
tunableGain model. When the control system is tuned, D ensures that each output of G
tracks the corresponding reference signal r with minimal crosstalk.
Assigning InputName and OutputName values to these control elements allows you to
interconnect them to create a tunable model of the entire controller C as shown.
When you tune the control system, looptune uses these channel names to interconnect C
and G. The controller C also includes the summing junction sum1. This a two-channel
summing junction, because r and y are vector-valued signals of dimension 2.
C0 is a tunable genss model that represents the entire controller structure. C0 stores the
tunable controller parameters and contains the initial values of those parameters.
The inputs to looptune are G and C0, the plant and initial controller models that you
created. The input wc = [0.1,1] sets the target range for the loop bandwidth. This
15-7
15 Loop-Shaping Design
input specifies that the crossover frequency of each loop in the tuned system fall between
0.1 and 1 rad/min.
wc = [0.1,1];
[G,C,gam,Info] = looptune(G,C0,wc);
The displayed Peak Gain = 0.949 indicates that looptune has found parameter
values that achieve the target loop bandwidth. looptune displays the final peak gain
value of the optimization run, which is also the output gam. If gam is less than 1, all tuning
requirements are satisfied. A value greater than 1 indicates failure to meet some
requirement. If gam exceeds 1, you can increase the target bandwidth range or relax
another tuning requirement.
looptune also returns the tuned controller model C. This model is the tuned version of
C0. It contains the PI coefficients and the decoupling matrix gain values that yield the
optimized peak gain value.
showTunable(C)
Decoupler =
D =
u1 u2
y1 2.138 -1.302
y2 -1.585 1.296
Name: Decoupler
Static gain.
-----------------------------------
PI_L =
1
Kp + Ki * ---
s
Name: PI_L
Continuous-time PI controller in parallel form.
15-8
Tune MIMO Control System for Specified Bandwidth
-----------------------------------
PI_V =
1
Kp + Ki * ---
s
Name: PI_V
Continuous-time PI controller in parallel form.
Check the time-domain response for the control system with the tuned coefficients. To
produce a plot, construct a closed-loop model of the tuned control system. Plot the step
response from reference to output.
T = connect(G,C,'r','y');
step(T)
15-9
15 Loop-Shaping Design
The decoupling matrix in the controller permits each channel of the two-channel output
signal y to track the corresponding channel of the reference signal r, with minimal
crosstalk. From the plot, you can how well this requirement is achieved when you tune
the control system for bandwidth alone. If the crosstalk still exceeds your design
requirements, you can use a TuningGoal.Gain requirement object to impose further
restrictions on tuning.
Examine the frequency-domain response of the tuned result as an alternative method for
validating the tuned controller.
figure('Position',[100,100,520,1000])
loopview(G,C,Info)
15-10
Tune MIMO Control System for Specified Bandwidth
15-11
15 Loop-Shaping Design
The first plot shows that the open-loop gain crossovers fall within the specified interval
[0.1,1]. This plot also includes the maximum and tuned values of the sensitivity
function and complementary sensitivity . The second and third
plots show that the MIMO stability margins of the tuned system (blue curve) do not
exceed the upper limit (yellow curve).
See Also
Related Examples
• “Decoupling Controller for a Distillation Column” on page 17-331
More About
• “Structure of Control System for Tuning With looptune” on page 15-2
15-12
16
Gain-Scheduled Controllers
16 Gain-Scheduled Controllers
Gain-scheduled control systems are often designed by choosing a small set of operating
points, the design points, and designing a suitable linear controller for each point. In
operation, the system switches or interpolates between these controllers according to the
current values of the scheduling variables.
Gain scheduling is most suitable when the scheduling variables are external parameters
that vary slowly compared to the control bandwidth, such as the ambient temperature of
a chemical reaction or the speed of a cruising aircraft. Gain scheduling is most
challenging when the scheduling variables depend on fast-varying states of the system.
Because local linear performance near operating points is no guarantee of global
performance in nonlinear systems, extensive simulation-based validation is required. See
[1] for an overview of gain scheduling and its challenges.
• An operating range, defined as a set of ranges within which the values of relevant
system parameters remain during operation. For instance, if your system is a cruising
aircraft, then the operating range might be an incidence angle between –20° and 20°
and airspeed in the range 200-250 m/s.
• Some measurable variables that indicate where in the operating range the system is at
a given time. These signals are the scheduling variables. For the aircraft system, the
scheduling variables might be the incidence angle and the airspeed.
• A gain schedule, which comprises the formulas or data tables that return the
appropriate controller gains for given values of the scheduling variables. For the
aircraft system, the gain schedule gives appropriate controller gains for any
combination of incidence angle and airspeed within the operating range.
16-2
See Also
with variable parameters. For instance, the Varying PID Controller block accepts PID
gains as inputs. In your model, you use blocks such as n-D Lookup Table or MATLAB
Function blocks to implement the gain schedule. For more information and examples, see
“Model Gain-Scheduled Control Systems in Simulink” on page 16-4.
References
[1] Rugh, W.J., and J.S. Shamma, “Research on Gain Scheduling”, Automatica, 36 (2000),
pp. 1401-1425.
See Also
More About
• “Model Gain-Scheduled Control Systems in Simulink” on page 16-4
• “Tune Gain Schedules in Simulink” on page 16-15
16-3
16 Gain-Scheduled Controllers
• Lookup tables — A lookup table is a list of breakpoints and corresponding gain values.
When the scheduling variables fall between breakpoints, the lookup table interpolates
between the corresponding gains. Use the following blocks to implement gain
schedules as lookup tables.
• 1-D Lookup Table, 2-D Lookup Table, n-D Lookup Table — For a scalar gain that
depends on one, two, or more scheduling variables.
• Matrix Interpolation — For a matrix-valued gain that depends on one, two, or three
scheduling variables. (This block is in the Simulink Extras library.)
16-4
Model Gain-Scheduled Control Systems in Simulink
• MATLAB Function block — When you have a functional expression relating the gains
to the scheduling variables, use a MATLAB Function block. If the expression is a
smooth function, using a MATLAB function can result in smoother gain variations than
a lookup table. Also, if you use a code-generation product such as Simulink Coderto
implement the controller in hardware, a MATLAB function can result in a more
memory-efficient implementation than a lookup table.
If you have Simulink Control Design, you can use systune to tune gain schedules
implement as either lookup tables or MATLAB functions. See “Tune Gain Schedules in
Simulink” on page 16-15.
16-5
16 Gain-Scheduled Controllers
Both the Concentration controller and Temperature controller blocks take the
CSTR plant output, Cr, as an input. This value is both the controlled variable of the system
and the scheduling variable on which the controller action depends. Double-click the
Concentration controller block.
16-6
Model Gain-Scheduled Control Systems in Simulink
This block is a PI controller in which the proportional gain Kp and integrator gain Ki are
determined by feeding the scheduling parameter Cr into a 1-D Lookup Table block.
Similarly, the Temperature controller block contains three gains implemented as
lookup tables.
16-7
16 Gain-Scheduled Controllers
Block Application
• Varying Lowpass Filter Use these blocks to implement a
• Discrete Varying Lowpass Butterworth lowpass filter in which the
cutoff frequency varies with scheduling
variables.
• Varying Notch Filter Use these blocks to implement a notch filter
• Discrete Varying Notch in which the notch frequency, width, and
depth vary with scheduling variables.
• Varying PID Controller These blocks are preconfigured versions of
• Discrete Varying PID the PID Controller and PID Controller
(2DOF) blocks. Use them to implement PID
• Varying 2DOF PID controllers in which the PID gains vary with
• Discrete Varying 2DOF PID scheduling variables.
• Varying Transfer Function Use these blocks to implement a transfer
• Discrete Varying Transfer Function function of any order in which the
polynomial coefficients of the numerator
and denominator vary with scheduling
variables.
• Varying State Space Use these blocks to implement a state-
• Discrete Varying State Space space controller in which the A, B, C, and D
matrices vary with the scheduling
variables.
• Varying Observer Form Use these blocks to implement a gain-
• Discrete Varying Observer Form scheduled observer-form state-space
controller, such as an LQG controller. In
such a controller, the A, B, C, D matrices
and the state-feedback and state-observer
gain matrices vary with the scheduling
variables.
For example, the subsystem in the following illustration uses a Varying Notch Filter block
to implement a filter whose notch frequency varies as a function of two scheduling
variables. The relationship between the notch frequency and the scheduling variables is
implemented in a MATLAB function.
16-8
Model Gain-Scheduled Control Systems in Simulink
Gain-Scheduled PI Controller
16-9
16 Gain-Scheduled Controllers
You can also implement matrix-valued gain schedules Simulink. A matrix-valued gain
schedule takes one or more scheduling variables and returns a matrix rather than a scalar
value. For instance, suppose that you want to implement a time-varying LQG controller of
the form:
In your Simulink model, you can implement matrix-valued gain schedules using:
• MATLAB Function block — Specify a MATLAB function that takes scheduling variables
and returns matrix values.
• Matrix Interpolation block — Specify a lookup table to associate a matrix value with
each scheduling-variable breakpoint. Between breakpoints, the block interpolates the
matrix elements. (This block is in the Simulink Extras library.)
For the LQG controller, use either MATLAB Function blocks or Matrix Interpolation blocks
to implement the time-varying matrices as inputs to a Varying Observer Form block. For
example:
16-10
Model Gain-Scheduled Control Systems in Simulink
If you have Simulink Control Design, you can tune matrix-valued gain schedules
implemented as either MATLAB Function blocks or as Matrix Interpolation blocks.
However, to tune a Matrix Interpolation block, you must set Simulate using to
Interpreted execution. See the Matrix Interpolation block reference page for
information about simulation modes.
16-11
16 Gain-Scheduled Controllers
Here, the overall gain Kt, the zero location a, and the pole location b are each
implemented as a 1-D lookup table that takes the scheduling variable as input. The lookup
tables feed directly into product blocks.
16-12
Model Gain-Scheduled Control Systems in Simulink
There can be one or more of the following blocks between the lookup table or MATLAB
Function block and the Product block or parameter-varying block:
• Gain
• Bias
• Blocks that are equivalent to a unit gain in the linear domain, including:
• Switch
• Multiport Switch
• Manual Switch
Inserting such blocks can be useful, for example, to constrain the gain value to a certain
range, or to specify how often the gain schedule is updated.
16-13
16 Gain-Scheduled Controllers
See Also
Related Examples
• “Tune Gain Schedules in Simulink” on page 16-15
• “Gain-Scheduled Control of a Chemical Reactor” on page 17-291
16-14
Tune Gain Schedules in Simulink
If you have Simulink Control Design, you can use systune to tune these gain schedules
so that the full nonlinear system meets your design requirements. Tuning gain schedules
amounts to identifying appropriate values for lookup-table data or finding the right
function to embed in a MATLAB Function block. For systune, you parameterize the gain
schedules as functions of the scheduling variables with tunable coefficients.
1 Select a set of design points that adequately covers the operating range over which
you are tuning. A design point is a set of scheduling-variable values that describe a
particular operating condition. The set of design points can be a regular grid of
values or a scattered set. Typically, you start with a few design points. If the
performance that your tuned system achieves at the design points is not maintained
between design points, add more design points and retune.
2 Obtain a collection of linear models describing the linearized plant dynamics at the
selected design points. Ways to obtain the array of linear models include:
For more information, see “Plant Models for Gain-Scheduled Controller Tuning” on
page 16-18.
3 Create an slTuner interface for tuning the Simulink. When you do so, you substitute
the array of linear models for the plant, so that the slTuner interface contains a set
16-15
16 Gain-Scheduled Controllers
K (s ) = K0 + K1 F1 ( n (s ) ) + … + K M FM ( n ( s ) ) .
n(σ) is a normalization function. For tuning with systune, you use tunableSurface
to represent the parametric gain surface K(σ). In the slTuner interface you create
for tuning, use setBlockParam to associate the resulting gain surface with the block
that represents the gain schedule. systune tunes the coefficients K0,...,KM over all
the design points.
For information about specifying tuning goals that vary with design point, see
“Change Requirements with Operating Condition” on page 16-41.
For information about specifying tuning goals generally, see “Tuning Goals”.
6 Use systune to tune the control system. systune tunes the set of parameters,
K0,...,KM, against all plant models in the design grid simultaneously (multimodel
tuning).
7 Validate the tuning results. You can examine the tuned gain surfaces and validate the
performance of the linearized system at each design point. However, local linear
performance does not guarantee global performance in nonlinear systems. Therefore,
it is important to perform simulation-based validation using the tuned gain schedules.
For more information, see “Validate Gain-Scheduled Control Systems” on page 16-
45.
16-16
See Also
See Also
More About
• “Model Gain-Scheduled Control Systems in Simulink” on page 16-4
• “Gain-Scheduled Control of a Chemical Reactor” on page 17-291
• “Tuning of Gain-Scheduled Three-Loop Autopilot” on page 17-309
16-17
16 Gain-Scheduled Controllers
x& = f ( x, u,s )
y = g ( x, u,s ) .
Here, x is the state vector, u is the plant input, and y is the plant output. These nonlinear
differential equations can be known explicitly for a particular system. More commonly,
they are specified implicitly, such as by a Simulink model.
You can convert these nonlinear dynamics into a family of linear models that describe the
local behavior of the plant around a family of operating points (x(σ),u(σ)), parameterized
by the scheduling variables, σ. Deviations from the nominal operating condition are
defined as:
d x = x - x (s ) , d u = u - u ( s ) .
d& x = A ( s ) d x + B( s ) d u, d y = C (s ) d x + D (s ) d u,
∂f ∂f
A (s ) =
∂x
( x (s ) ,u (s )) B (s ) =
∂u
( x (s ), u (s ))
∂g ∂g
C (s ) =
∂x
( x (s ), u (s )) D(s ) =
∂u
( x (s ), u (s )).
This continuum of linear approximations to the nonlinear dynamics is called a linear
parameter-varying (LPV) model:
dx
= A (s ) x + B ( s ) u
dt
y = C (s ) x + D ( s ) u.
16-18
Plant Models for Gain-Scheduled Controller Tuning
The LPV model describes how the linearized plant dynamics vary with time, operating
condition, or any other scheduling variable. For example, the pitch axis dynamics of an
aircraft can be approximated by an LPV model that depends on incidence angle, α, air
speed, V, and altitude, h.
In practice, you replace this continuum of plant models by a finite set of linear models
obtained for a suitable grid of σ values This replacement amounts to sampling the LPV
dynamics over the operating range and selecting a representative set of σ values, your
design points.
Gain-scheduled controllers yield best results when the plant dynamics vary smoothly
between design points.
16-19
16 Gain-Scheduled Controllers
• If you have a Simulink model, trim and linearize the model at the design points on
page 16-20.
• Linearize the Simulink model using parameter variation on page 16-23.
• If the scheduling variable is time, linearize the model at a series of simulation
snapshots on page 16-23.
• If you have nonlinear differential equations that describe the plant, linearize them at
the design points.
For tuning gain schedules, after you obtain the family of linear models, you must
associate it with an slTuner interface to build a family of tunable closed-loop models. To
do so, use block substitution, as described in “Multiple Design Points in slTuner
Interface” on page 16-26.
mdl = 'rct_CSTR';
open_system(mdl)
16-20
Plant Models for Gain-Scheduled Controller Tuning
mdl_OL = 'rct_CSTR_OL';
open_system(mdl_OL)
16-21
16 Gain-Scheduled Controllers
Suppose that you want to control this plant at a range of Cr values from 4 to 8. Trim the
model to find steady-state operating points for a set of values in this range. These values
are the design points for tuning.
Cr = (4:8)'; % concentrations
for k=1:length(Cr)
opspec = operspec(mdl_OL);
% Set desired residual concentration
opspec.Outputs(1).y = Cr(k);
opspec.Outputs(1).Known = true;
% Compute equilibrium condition
[op(k),report(k)] = findop(mdl_OL,opspec,findopOptions('DisplayReport','off'));
end
Linearizing the plant model using op returns an array of LTI models, each linearized at
the corresponding design point.
G = linearize(mdl_OL,'rct_CSTR_OL/CSTR',op);
16-22
Plant Models for Gain-Scheduled Controller Tuning
To tune the control system rct_CSTR, create an slTuner interface that linearizes the
system at those design points. Use block substitution to replace the plant in rct_CSTR
with the linearized plant-model array G.
blocksub.Name = 'rct_CSTR/CSTR';
blocksub.Value = G;
tunedblocks = {'Kp','Ki'};
ST0 = slTuner(mdl,tunedblocks,blocksub);
For this example, only the PI coefficients in the Concentration controller are
designated as tuned blocks. In general, however, tunedblocks lists all the blocks to
tune.
For more information about using block substitution to configure an slTuner interface
for gain-scheduled controller tuning, see “Multiple Design Points in slTuner Interface” on
page 16-26.
For another example that illustrates using trimming and linearization to generate a family
of linear models for gain-scheduled controller tuning, see “Trimming and Linearization of
the HL-20 Airframe”.
16-23
16 Gain-Scheduled Controllers
To set up such a model for tuning, create a grid of parameter values. For this example, let
Ks vary from 1 – 5, and let Bs vary from 0.6 – 0.9.
Ks = 1:5;
Bs = [0.6:0.1:0.9];
[Ksgrid,Bsgrid] = ndgrid(Ks,Bs);
These values are the design points at which to sample and tune the system. For example,
create an slTuner interface to the model, assuming one tunable block, a Lookup Table
block named K that models the parameter-dependent gain.
params(1) = struct('Name','Ks','Value',Ksgrid);
params(2) = struct('Name','Bs','Value',Bsgrid);
STO = slTuner('suspension_gs','K',params);
Next, use the same design points to create a tunable gain surface for parameterizing K.
design = struct('Ks',Ksgrid,'Bs',Bsgrid);
shapefcn = @(Ks,Bs)[Ks,Bs,Ks*Bs];
K = tunableSurface('K',1,design,shapefcn);
setBlockParam(ST0,'K',K);
After you parameterize all the scheduled gains, you can create your tuning goals and tune
the system with systune.
There are other tools for controlling which models contribute to design and analysis. For
instance, you might want to:
• Keep a model in the grid for analysis, but exclude it from tuning.
• Keep a model in the grid for tuning, but exclude it from a particular design goal.
16-24
See Also
For more information, see “Change Requirements with Operating Condition” on page 16-
41.
See Also
findop | slTuner | voidModel
Related Examples
• “Parameterize Gain Schedules” on page 16-31
• “Tune Gain Schedules in Simulink” on page 16-15
• “Multiple Design Points in slTuner Interface” on page 16-26
16-25
16 Gain-Scheduled Controllers
• The linear models in the array correspond exactly to the plant subsystem in your
model.
• Other than the elements you want to tune, nothing else in the model varies with the
scheduling variables.
For a Simulink model mdl containing plant subsystem G, and a linear model array Garr
that represents the plant at a grid of design points, the following commands create an
slTuner interface:
BlockSubs = struct('Name','mdl/G','Value',Garr);
st0 = slTuner('mdl',{'Kp','Ki'},BlockSubs);
st0 contains a family of closed-loop linear models, each linearized at a design point, and
each with the corresponding linear plant inserted for G. If 'Kp'and 'Ki' are the gain
schedules you want to tune (such as lookup tables), you can parameterize them with
tunable gain surfaces, as described in “Parameterize Gain Schedules” on page 16-31,
and tune them.
16-26
Multiple Design Points in slTuner Interface
This model has an inner loop with a proportional-only gain-scheduled controller. The
controller is represented by the lookup table Kp_in and the product block prod. The
outer loop includes a PI controller with gain-scheduled proportional and integral
coefficients represented by the lookup tables Kp and Ki. All the gain schedules depend on
the same scheduling variable alpha.
Suppose you want to tune the inner-loop gain schedule Kp_in with the outer loop open.
To that end, you obtain an array of linear models G_in from input u to outputs
{q,alpha}. This model array has the wrong I/O dimensions to use as a block substitution
for G. Therefore, you must "pad" G_in with an extra output dimension.
In addition, you can remove all effect of the outer loop by replacing the Varying PID
Controller block with a system that linearizes to zero at all operating conditions. Because
this block has three inputs, replace it with a 3-input, one-output zero system.
BlockSubs2 = struct('Name','mdl/Varying PID Controller','Value',ss([0 0 0]));
16-27
16 Gain-Scheduled Controllers
With those block substitutions, the following commands create an slTuner interface that
you might use to tune the inner-loop gain schedule.
st0 = slTuner('mdl','Kp_in');
st0.BlockSubstitutions = [BlockSubs1; BlockSubs2];
See the example “Angular Rate Control in the HL-20 Autopilot” for a another case in
which several elements other than the plant itself are replaced by block substitution.
st0 = slTuner('mdl',{'Kp','Ki'});
st0.BlockSubstitutions = [BlockSubs1; BlockSubs2];
For another example that shows this kind of substitution for a previously-tuned lookup
table, see “Attitude Control in the HL-20 Autopilot - SISO Design”.
The following illustration of a portion of a model highlights another scenario in which you
might need to replace blocks that vary with the scheduling variable. Suppose the
scheduling variable is alpha, and somewhere in your model, an signal u gets divided by
alpha.
16-28
Multiple Design Points in slTuner Interface
To ensure that slTuner linearizes this block correctly at all values of alpha in the design
grid, you must replace it by an array of linear models, one for each alpha value. This
block is equivalent to sending u through a gain of 1/alpha:
Therefore, you can use the following block substitution in your slTuner interface, where
alphagrid is an array of alpha values at your design points.
divsub = ss[(1/alphagrid), 0]
BlockSubs = struct('Name','mdl/div-by-alpha','Value',divsub);
st0.BlockSubstitutions = [st0.BlockSubstitutions; BlockSubs]
Each entry in model array divsub divides its first input by the corresponding entry in
alphagrid, and zeros out its second input. Thus, this substitution gives the desired
result y = u/alpha.
16-29
16 Gain-Scheduled Controllers
Suppose you have an array of linearized models Garr corresponding to G. You can
configure a block substitution for the entire subsystem G_full by constructing a
substitution model that reproduces the effect of averaging the three inputs, as follows:
Sometimes, you can resolve a mismatch in I/O dimensions by padding inputs or outputs
with zeros, as shown in “Multiple Block Substitutions” on page 16-26. In still other cases,
you might need to perform other model arithmetic, using commands like series,
feedback, or connect to build a suitable replacement.
BlockSubs = struct('Name','mdl/LPVPlant','Value',PlantArray);
See Also
slTuner
More About
• “Tune Gain Schedules in Simulink” on page 16-15
• “Plant Models for Gain-Scheduled Controller Tuning” on page 16-18
• “Parameterize Gain Schedules” on page 16-31
16-30
Parameterize Gain Schedules
Here, k0,...,k3 are tunable coefficients. When you parameterize scheduled gains in this
way, systune can tune the gain-surface coefficients to meet your control objectives at a
representative set of operating conditions. For applications where gains vary smoothly
with the scheduling variables, this approach provides explicit formulas for the gains,
which the software can write directly to MATLAB Function blocks. When you use lookup
tables, this approach lets you tune a few coefficients rather than many individual lookup-
table entries, drastically reducing the number of parameters and ensuring smooth
transitions between operating points.
K i (s )
C ( s, s ) = K p (s ) + .
s
Tuning this controller requires determining the functional forms Kp(σ) and Ki(σ) that yield
the best system performance over the operating range of σ values. However, tuning
arbitrary functions is difficult. Therefore, it is necessary either to consider the function
values at only a finite set of points, or restrict the generality of the functions themselves.
In the first approach, you choose a collection of design points, σ, and tune the gains Kp
and Ki independently at each design point. The resulting set of gain values is stored in a
lookup table driven by the scheduling variables, σ. A drawback of this approach is that
tuning might yield substantially different values for neighboring design points, causing
undesirable jumps when transitioning from one operating point to another.
Alternatively, you can model the gains as smooth functions of σ, but restrict the generality
of such functions by using specific basis function expansions. For example, suppose σ is a
scalar variable. You can model Kp(σ) as a quadratic function of σ:
16-31
16 Gain-Scheduled Controllers
K p (s ) = k0 + k1s + k2s 2 .
After tuning, this parametric gain might have a profile such as the following (the specific
shape of the curve depends on the tuned coefficient values and range of σ):
Or, suppose that σ consists of two scheduling variables, α and V. Then, you can model
Kp(σ) as a bilinear function of α and V:
16-32
Parameterize Gain Schedules
After tuning, this parametric gain might have a profile such as the following. Here too,
the specific shape of the curve depends on the tuned coefficient values and ranges of σ
values:
For tuning gain schedules with systune, you use a parametric gain surface that is a
particular expansion of the gain in basis functions of σ:
K (s ) = K0 + K1 F1 ( n (s ) ) + … + K M FM ( n ( s ) ) .
The basis functions F1,...,FM are user-selected and fixed. These functions operate on n(σ),
where n is a function that scales and normalizes the scheduling variables to the interval [–
1,1] (or an interval you specify). The coefficients of the expansion, K0,...,KM, are the
16-33
16 Gain-Scheduled Controllers
K p (a , V ) = K 0 + K1a + K2 V + K3a V .
Suppose that α is an angle of incidence that ranges from 0° to 15°, and V is a speed that
ranges from 300 m/s to 700 m/s. Create a grid of design points that span these ranges.
These design points must match the parameter values at which you sample your varying
or nonlinear plant. (See “Plant Models for Gain-Scheduled Controller Tuning” on page 16-
18.)
[alpha,V] = ndgrid(0:5:15,300:100:700);
domain = struct('alpha',alpha,'V',V);
Specify the basis functions for the parameterization of this surface, α, V, and αV. The
tunableSurface command expects the basis functions to be arranged as a vector of
functions of two input variables. You can use an anonymous function to express the basis
functions.
shapefcn = @(alpha,V)[alpha,V,alpha*V];
Create the tunable surface using the design points and basis functions.
Kp = tunableSurface('Kp',1,domain,shapefcn);
K p (a , V ) = K 0 + K1a + K 2V + K3a V ,
where
16-34
Parameterize Gain Schedules
a - 7.5 V - 500
a = , V = .
7.5 200
2
The surface is expressed in terms of the normalized variables, a , V Œ [ -1,1] rather than
in terms of α and V. This normalization, which tunableSurface performs by default,
improves the conditioning of the optimization performed by systune. If needed, you can
change the default scaling and normalization. (See tunableSurface).
The second input argument to tunableSurface specifies the initial value of the constant
coefficient, K0. By default, K0 is the gain when all the scheduling variables are at the
center of their ranges. tunableSurface takes the I/O dimensions of the gain surface
from K0. Therefore, you can create array-valued tunable gains by providing an array for
that input.
Karr = tunableSurface('Karr',ones(2),domain,shapefcn);
Karr is a 2-by-2 matrix in which each entry is a bilinear function of the scheduling
variables with independent coefficients.
Create a grid of design points, , that are linearly spaced in and V. These design
points are the scheduling-variable values used for tuning the gain-surface coefficients.
They must correspond to parameter values at which you have sampled the plant.
16-35
16 Gain-Scheduled Controllers
[alpha,V] = ndgrid(0:3:15,300:50:600);
These arrays, alpha and V, represent the independent variation of the two scheduling
variables, each across its full range. Put them into a structure to define the design points
for the tunable surface.
domain = struct('alpha',alpha,'V',V);
K = tunableSurface('K',1,domain,shapefcn);
You can use the tunable surface as the parameterization for a lookup table block or a
MATLAB Function block in a Simulink model. Or, use model interconnection commands to
incorporate it as a tunable element in a control system modeled in MATLAB. After you
tune the coefficients, you can examine the resulting gain surface using the viewSurf
command. For this example, instead of tuning, manually set the coefficients to non-zero
values and view the resulting gain.
Ktuned = setData(K,[100,28,40,10]);
viewSurf(Ktuned)
16-36
Parameterize Gain Schedules
viewSurf displays the gain surface as a function of the scheduling variables, for the
ranges of values specified by domain and stored in the SamplingGrid property of the
gain surface.
16-37
16 Gain-Scheduled Controllers
To tune the lookup tables Kp and Ki, create a tunable surface for each one. Suppose that
CrEQ is the vector of design points, and that you expect the gains to vary quadratically
with Cr.
TuningGrid = struct('Cr',CrEQ);
ShapeFcn = @(Cr) [Cr , Cr^2];
Kp = tunableSurface('Kp',0,TuningGrid,ShapeFcn);
Ki = tunableSurface('Ki',-2,TuningGrid,ShapeFcn);
Suppose that you have an array Gd of linearizations of the plant subsystem, CSTR, at each
of the design points in CrEQ. (See “Plant Models for Gain-Scheduled Controller Tuning”
on page 16-18). Create an slTuner interface that substitutes this array for the plant
subsystem and designates the two lookup-table blocks for tuning.
16-38
Parameterize Gain Schedules
BlockSubs = struct('Name','rct_CSTR/CSTR','Value',Gd);
ST0 = slTuner('rct_CSTR',{'Kp','Ki'},BlockSubs);
ST0.setBlockParam('Kp',Kp);
ST0.setBlockParam('Ki',Ki);
When you tune STO, systune tunes the coefficients of the tunable surfaces Kp and Ki, so
that each tunable surface represents the tuned relationship between Cr and the gain.
When you write the tuned values back to the block for validation, setBlockParam
automatically generates tuned lookup-table data by evaluating the tunable surfaces at the
breakpoints you specify in the corresponding blocks.
For more details about this example, see “Gain-Scheduled Control of a Chemical Reactor”
on page 17-291.
C0 = pid(Kp,Ki);
Similarly, suppose that you create four matrix-valued gain surfaces A, B, C, D. The
following command constructs a tunable gain-scheduled state-space controller.
C1 = ss(A,B,C,D);
You then incorporate the gain-scheduled controller into a generalized model of your
entire control system. For example, suppose G is an array of models of your plant sampled
at the design points that are specified in Kp and Ki. Then, the following command builds
a tunable model of a gain-scheduled single-loop PID control system.
T0 = feedback(G*C0,1);
When you interconnect a tunable surface with other LTI models, the resulting model is an
array of tunable generalized genss models. The design points in the tunable surface
determine the dimensions of the array. Thus, each entry in the array represents the
16-39
16 Gain-Scheduled Controllers
T0 = feedback(G*Kp,1)
T0 =
Type "ss(T0)" to see the current value, "get(T0)" to see all properties, and
"T0.Blocks" to interact with the blocks.
The resulting generalized model has tunable blocks corresponding to the gain surfaces
used to create the model. In this example, the system has one gain surface, Kp, which has
the four tunable coefficients corresponding to K0, K1, K2, and K3. Therefore, the tunable
block is a vector-valued realp parameter with four entries.
When you tune the control system with systune, the software tunes the coefficients for
each of the design points specified in the tunable surface.
For an example illustrating the entire workflow in MATLAB, see the section “Controller
Tuning in MATLAB” in “Gain-Scheduled Control of a Chemical Reactor” on page 17-291.
See Also
tunableSurface
Related Examples
• “Model Gain-Scheduled Control Systems in Simulink” on page 16-4
• “Multiple Design Points in slTuner Interface” on page 16-26
• “Tune Gain Schedules in Simulink” on page 16-15
16-40
Change Requirements with Operating Condition
• Specify a variable tuning goal that depends explicitly or implicitly on the design point.
• Enforce a tuning goal at a subset of design points, but ignore it at other design points.
• Exclude a design point from a particular run of systune, but retain it for analysis or
other tuning operations.
• Eliminate a design point from all stages of design and analysis.
The varyingGoal command lets you construct tuning goals that depend implicitly or
explicitly on the design point.
For example, create a tuning goal that specifies variable gain and phase margins across a
grid of design points. Suppose that you use the following 5-by-5 grid of design points to
tune your controller.
[alpha,V] = ndgrid(linspace(0,20,5),linspace(700,1300,5));
Suppose further that you have 5-by-5 arrays of target gain margins and target phase
margins corresponding to each of the design points, such as the following.
[GM,PM] = ndgrid(linspace(7,20,5),linspace(45,70,5));
To enforce the specified margins at each design point, first create a template for the
margins goal. The template is a function that takes gain and phase margin values and
returns a TuningGoal.Margins object with those margins.
FH = @(gm,pm) TuningGoal.Margins('u',gm,pm);
Use the template and the margin arrays to create the varying goal.
VG = varyingGoal(FH,GM,PM);
16-41
16 Gain-Scheduled Controllers
To make it easier to trace which goal applies to which design point, use the
SamplingGrid property to attach the design-point information to VG.
VG.SamplingGrid = struct('alpha',alpha,'V',V);
Use VG with systune as you would use any other tuning goal. Use viewGoal to visualize
the tuning goal and identify design points that fail to meet the target margins. For varying
tuning goals, the viewGoal plot includes sliders that let you examine the goal and system
performance for particular design points. See “Validate Gain-Scheduled Control Systems”
on page 16-45.
The template function allows great flexibility in constructing the design goals. For
example, you can write a function, goalspec(a,b), that constructs the target overshoot
as a nontrivial function of the parameters (a,b), and save the function in a MATLAB file.
Your template function then calls goalspec:
FH = @(a,b) TuningGoal.Overshoot('r',y',goalspec(a,b));
For more information about configuring varying goals, see the varyingGoal reference
page.
Another way to enforce a requirement that varies with design point is to create a separate
instance of the requirement for each design point. This approach can be useful when you
have a goal that only applies to a few of models in the design array. For example, suppose
that you want to enforce a 1/s loop shape on the first five design points only, with a
crossover frequency that depends on the scheduling variables. Suppose also that you
have created a vector, wc, that contains the target bandwidth for each design point. Then
you can construct one TuningGoal.LoopShape requirement for each design point.
Associate each TuningGoal.LoopShape requirement with the corresponding design
point using the Models property of the requirement.
for ct = 1:length(wc)
R(ct) = TuningGoal.LoopShape('u',wc(ct));
R(ct).Model = ct;
end
If wc covers all the design points in your grid, this approach is equivalent to using a
varyingGoal object. It is a useful alternative to varyingGoal when you only want to
constrain a few design points.
16-42
Change Requirements with Operating Condition
Instead of creating varying requirements, you can incorporate the varying portion of the
requirement into the closed-loop model of the control system. This approach is a form of
goal normalization that makes it possible to cover all design points with a single uniform
goal.
For example, suppose that you want to limit the gain from d to y to a quantity that
depends on the scheduling variables. Suppose that T0 is an array of models of the closed-
loop system at each design point. Suppose further that you have created a table, gmax, of
the maximum gain values for each design point, σ. Then you can add another output ys =
y/gmax to the closed-loop model, as follows.
The maximum gain changes at each design point according to the table gmax. You can
then use a single requirement that limits to 1 the gain from d to the scaled output ys.
R = TuningGoal.Gain('d','ys',1);
Such effective normalization of requirements moves the requirement variability from the
requirement object, R, to the closed-loop model, T0.
In Simulink, you can use a similar approach by feeding the relevant model inputs and
outputs through a gain block. Then, when you linearize the model, change the gain value
of the block with the operating condition. For example, set the gain to a MATLAB
variable, and use the Parameters property in slLinearizer to change the variable
value with each linearization condition.
Req.Models = [1,9];
16-43
16 Gain-Scheduled Controllers
When you call systune with Req as a hard or soft goal, systune enforces Req for these
models and ignores it for the rest of the grid.
The SkipModels option of systuneOptions lets you specify models in the design grid
to exclude from tuning. Specify models by their linear index in the model array. For
instance, configure systuneOptions to skip the first and last models in a 3-by-3 design
grid.
opt = systuneOptions;
opt.SkipModels = [1,9];
When you call systune with opt, the tuning algorithm ignores these models.
As an alternative, you can eliminate design points from the model grid entirely, so that
they do not contribute to any stage of tuning or analysis. To do so, use voidModel, which
replaces specified models in a model array with NaN. This option is useful when your
sampling grid includes points that represent irrelevant or unphysical design points. Using
voidModel lets you design over a grid of design points that is almost regular.
See Also
systuneOptions | varyingGoal | viewGoal
More About
• “Validate Gain-Scheduled Control Systems” on page 16-45
• “Tune Gain Schedules in Simulink” on page 16-15
16-44
Validate Gain-Scheduled Control Systems
• Examine tuned gain surfaces to make sure that they are smooth and well-behaved.
• Visualize tuning goals against system responses at all design points.
• Check linear performance of the tuned control system between design points.
• Validate gain schedules in simulation of the full nonlinear system.
Check linear performance on a denser grid of σ values than you used for design. If
adequate linear performance is not maintained between design points, you can add more
design points and retune.
Perform nonlinear simulations that drive the closed-loop system through its entire
operating range. Pay special attention to maneuvers that cause rapid variations of the
scheduling variables.
For general information about using tuning-goal plots, see “Visualize Tuning Goals” on
page 14-189. For gain-scheduled control systems, the tuning-goal plots you generate with
viewGoal provide additional information that helps you evaluate how each tuning goal
contributes to the result.
16-45
16 Gain-Scheduled Controllers
For fixed tuning goals that apply to multiple design points, viewGoal plots the relevant
system response at all those design points. For instance, suppose that you tune an
slTuner interface, ST, for the rct_CSTR model described in “Gain-Scheduled Control of
a Chemical Reactor” on page 17-291. You can use viewGoal to see how well each of the
five design points of that example satisfies the gain goal R3. The resulting plot shows the
relevant gain profile at all five design points. Click any of the gain lines for a display that
shows the corresponding value of the scheduling variable Cr.
viewGoal(R3,ST)
16-46
Validate Gain-Scheduled Control Systems
Varying goals that you create using varyingGoal apply a different target response at
each design point. When you use viewGoal to examine a varying goal, the plot initially
displays the target and tuned responses at the first design point in the design grid. For
instance, suppose that you tune a control system ST over a design grid of two scheduling
variables, using a varying goal Rv that varies across the entire grid. After tuning, examine
Rv.
viewGoal(Rv,ST)
Click CHANGE to open sliders that let you select a design point at which to view the
target and tuned responses.
16-47
16 Gain-Scheduled Controllers
16-48
See Also
Lookup Tables
If you have retuned a subset of design points, you can use writeLookupTableData to
update a portion of the lookup-table data while leaving the rest intact.
References
[1] Rugh, W.J., and J.S. Shamma, “Research on Gain Scheduling”, Automatica, 36 (2000),
pp. 1401-1425.
See Also
codegen | viewGoal | viewSurf | writeBlockValue | writeLookupTableData
16-49
16 Gain-Scheduled Controllers
Related Examples
• “Tuning of Gain-Scheduled Three-Loop Autopilot” on page 17-309
• “Gain-Scheduled Control of a Chemical Reactor” on page 17-291
• “Validate Tuned Control System” on page 14-227
16-50
17
17-2
Tuning Multiloop Control Systems
Cascade control is often used to achieve smooth tracking with fast disturbance rejection.
The simplest cascade architecture involves two control loops (inner and outer) as shown
in the block diagram below. The inner loop is typically faster than the outer loop to reject
disturbances before they propagate to the outer loop.
open_system('rct_cascade')
17-3
17 Control System Tuning Examples
G2 = zpk([],-2,3);
G1 = zpk([],[-1 -1 -1],10);
We use a PI controller in the inner loop and a PID controller in the outer loop. The outer
loop must have a bandwidth of at least 0.2 rad/s and the inner loop bandwidth should be
ten times larger for adequate disturbance rejection.
When the control system is modeled in Simulink, use the slTuner interface in Simulink
Control Design™ to set up the tuning task. List the tunable blocks, mark the signals r and
d2 as inputs of interest, and mark the signals y1 and y2 as locations where to measure
open-loop transfers and specify loop shapes.
ST0 = slTuner('rct_cascade',{'C1','C2'});
addPoint(ST0,{'r','d2','y1','y2'})
You can query the current values of C1 and C2 in the Simulink model using
showTunable. The control system is unstable for these initial values as confirmed by
simulating the Simulink model.
showTunable(ST0)
Block 1: rct_cascade/C1 =
1
Kp + Ki * ---
s
Name: C1
Continuous-time PI controller in parallel form.
-----------------------------------
Block 2: rct_cascade/C2 =
1
Kp + Ki * ---
s
17-4
Tuning Multiloop Control Systems
Name: C2
Continuous-time PI controller in parallel form.
Next use "LoopShape" requirements to specify the desired bandwidths for the inner and
outer loops. Use as the target loop shape for the outer loop to enforce integral
action with a gain crossover frequency at 0.2 rad/s:
Use for the inner loop to make it ten times faster (higher bandwidth) than the outer
loop. To constrain the inner loop transfer, make sure to open the outer loop by specifying
y1 as a loop opening:
You can now tune the PID gains in C1 and C2 with systune:
ST = systune(ST0,[Req1,Req2]);
showTunable(ST)
Block 1: rct_cascade/C1 =
1 s
Kp + Ki * --- + Kd * --------
s Tf*s+1
Name: C1
Continuous-time PIDF controller in parallel form.
17-5
17 Control System Tuning Examples
-----------------------------------
Block 2: rct_cascade/C2 =
1
Kp + Ki * ---
s
Name: C2
Continuous-time PI controller in parallel form.
The final value is less than 1 which means that systune successfully met both loop shape
requirements. Confirm this by inspecting the tuned control system ST with viewGoal
viewGoal([Req1,Req2],ST)
17-6
Tuning Multiloop Control Systems
Note that the inner and outer loops have the desired gain crossover frequencies. To
further validate the design, plot the tuned responses to a step command r and step
disturbance d2:
17-7
17 Control System Tuning Examples
17-8
Tuning Multiloop Control Systems
Once you are satisfied with the linear analysis results, use writeBlockValue to write
the tuned PID gains back to the Simulink blocks. You can then conduct a more thorough
validation in Simulink.
writeBlockValue(ST)
If you do not have a Simulink model of the control system, you can perform the same
steps using LTI models of the plant and Control Design blocks to model the tunable
elements.
17-9
17 Control System Tuning Examples
C1 = tunablePID('C1','pid');
C2 = tunablePID('C2','pi');
Then use "analysis point" blocks to mark the loop opening locations y1 and y2.
LS1 = AnalysisPoint('y1');
LS2 = AnalysisPoint('y2');
Finally, create a closed-loop model T0 of the overall control system by closing each
feedback loop. The result is a generalized state-space model depending on the tunable
elements C1 and C2.
InnerCL = feedback(LS2*G2*C2,1);
T0 = feedback(G1*InnerCL*C1,LS1);
T0.InputName = 'r';
T0.OutputName = 'y1';
You can now tune the PID gains in C1 and C2 with systune.
T = systune(T0,[Req1,Req2]);
As before, use getIOTransfer to compute and plot the tuned responses to a step
command r and step disturbance entering at the location y2:
17-10
Tuning Multiloop Control Systems
17-11
17 Control System Tuning Examples
You can also plot the open-loop gains for the inner and outer loops to validate the
bandwidth requirements. Note the -1 sign to compute the negative-feedback open-loop
transfer:
17-12
See Also
See Also
slTuner | systune (slTuner)
Related Examples
• “PID Tuning for Setpoint Tracking vs. Disturbance Rejection” on page 17-14
17-13
17 Control System Tuning Examples
When tuning 1-DOF PID controllers, it is often impossible to achieve good tracking and
fast disturbance rejection at the same time. Assuming the control bandwidth is fixed,
faster disturbance rejection requires more gain inside the bandwidth, which can only be
achieved by increasing the slope near the crossover frequency. Because a larger slope
means a smaller phase margin, this typically comes at the expense of more overshoot in
the response to setpoint changes.
This example uses systune to explore this trade-off and find the right compromise for
your application. See also pidtool for a more direct way to make such trade-off (see
"Design Focus" under Controller Options).
17-14
PID Tuning for Setpoint Tracking vs. Disturbance Rejection
Tuning Setup
Consider the PID loop of Figure 2 with a load disturbance at the plant input.
The target control bandwidth is 10 rad/s. Create a tunable PID controller and fix its
derivative filter time constant to (10 times the bandwidth) so that there are
only three gains to tune (proportional, integral, and derivative gains).
G = zpk(-5,[-1 -2 -10],10);
C = tunablePID('C','pid');
C.Tf.Value = 0.01; C.Tf.Free = false; % fix Tf=0.01
The gain of the open-loop response is a key indicator of the feedback loop
behavior. The open-loop gain should be high (greater than one) inside the control
bandwidth to ensure good disturbance rejection, and should be low (less than one)
outside the control bandwidth to be insensitive to measurement noise and unmodeled
plant dynamics. Accordingly, use three requirements to express the control objectives:
17-15
17 Control System Tuning Examples
s = tf('s');
wc = 10; % target crossover frequency
% Tracking
R1 = TuningGoal.Tracking('r','y',2/wc);
% Disturbance rejection
R3 = TuningGoal.MinLoopGain('u',wc/s);
R3.Focus = [0 0.1];
Use systune to tune the PID gains to meet these requirements. Treat the bandwidth and
disturbance rejection goals as hard constraints and optimize tracking subject to these
constraints.
T1 = systune(T0,R1,[R2 R3]);
Verify that all three requirements are nearly met. The blue curves are the achieved values
and the yellow patches highlight regions where the requirements are violated.
figure('Position',[100,100,560,580])
viewGoal([R1 R2 R3],T1)
17-16
PID Tuning for Setpoint Tracking vs. Disturbance Rejection
17-17
17 Control System Tuning Examples
To gain insight into the trade-off between tracking and disturbance rejection, increase the
minimum loop gain in the frequency band [0,0.1] rad/s by a factor . Re-tune the PID
gains for the values .
Compare the responses to a step command r and to a step disturbance d entering at the
plant input u.
figure, step(T1,T2,T3,3)
title('Setpoint tracking')
legend('\alpha = 1','\alpha = 2','\alpha = 4')
17-18
PID Tuning for Setpoint Tracking vs. Disturbance Rejection
17-19
17 Control System Tuning Examples
Note how disturbance rejection improves as alpha increases, but at the expense of
increased overshoot in setpoint tracking. Plot the open-loop responses for the three
designs, and note how the slope before crossover (0dB) increases with alpha.
L1 = getLoopTransfer(T1,'u');
L2 = getLoopTransfer(T2,'u');
L3 = getLoopTransfer(T3,'u');
bodemag(L1,L2,L3,{1e-2,1e2}), grid
title('Open-loop response')
legend('\alpha = 1','\alpha = 2','\alpha = 4')
17-20
PID Tuning for Setpoint Tracking vs. Disturbance Rejection
Which design is most suitable depends on the primary purpose of the feedback loop you
are tuning.
17-21
17 Control System Tuning Examples
Use the tunablePID2 object to parameterize the 2-DOF PID controller and construct a
tunable model T0 of the closed-loop system in Figure 3.
C = tunablePID2('C','pid');
C.Tf.Value = 0.01; C.Tf.Free = false; % fix Tf=0.01
T0 = feedback(G*LS*C,1,2,1,+1);
T0 = T0(:,1);
T0.u = 'r'; T0.y = 'y';
Next tune the 2-DOF PI controller for the largest loop gain tried earlier ( ).
Compare the setpoint tracking and disturbance rejection properties of the 1-DOF and 2-
DOF designs for .
clf, step(T3,'b',T4,'g--',4)
title('Setpoint tracking')
legend('1-DOF','2-DOF')
17-22
PID Tuning for Setpoint Tracking vs. Disturbance Rejection
D4 = getIOTransfer(T4,'u','y');
step(D3,'b',D4,'g--',4)
title('Disturbance rejection')
legend('1-DOF','2-DOF')
17-23
17 Control System Tuning Examples
The responses to a step disturbance are similar but the 2-DOF controller eliminates the
overshoot in the response to a setpoint change. You can use showTunable to compare
the tuned gains in the 1-DOF and 2-DOF controllers.
showTunable(T3) % 1-DOF PI
C =
1 s
Kp + Ki * --- + Kd * --------
s Tf*s+1
17-24
See Also
Name: C
Continuous-time PIDF controller in parallel form.
showTunable(T4) % 2-DOF PI
C =
1 s
u = Kp (b*r-y) + Ki --- (r-y) + Kd -------- (c*r-y)
s Tf*s+1
Name: C
Continuous-time 2-DOF PIDF controller in parallel form.
See Also
systune
Related Examples
• “Multi-Loop PI Control of a Robotic Arm”
17-25
17 Control System Tuning Examples
Time-Domain Specifications
This example gives a tour of available time-domain requirements for control system
tuning with systune or looptune.
Background
The systune and looptune commands tune the parameters of fixed-structure control
systems subject to a variety of time- and frequency-domain requirements. The
TuningGoal package is the repository for such design requirements.
R1 = TuningGoal.StepTracking('r','y',0.5);
stipulates that the closed-loop response from r to y should behave like a first-order
system with time constant 0.5, while
R2 = TuningGoal.StepTracking('r','y',zpk(2,[-1 -2],-1));
viewGoal(R2)
17-26
Time-Domain Specifications
This requirement can be used to tune both SISO and MIMO step responses. In the MIMO
case, the requirement ensures that each output tracks the corresponding input with
minimum cross-couplings.
limits the amplitude of to 0.3, the settling time to 2 time units, and the damping ratio
to a minimum of 0.5. Use viewGoal to see the corresponding time response.
17-27
17 Control System Tuning Examples
viewGoal(R1)
You can also use a "reference model" to specify the desired response. Note that the actual
and specified responses may differ substantially when better disturbance rejection is
possible. Use the TuningGoal.Transient requirement when a close match is desired.
For best results, adjust the gain of the reference model so that the actual and specified
responses have similar peak amplitudes (see TuningGoal.StepRejection
documentation for details).
17-28
Time-Domain Specifications
R1 = TuningGoal.Transient('r','y',tf(1,[1 1 1]),'impulse');
requires that the tuned response from to look like the impulse response of the
reference model .
viewGoal(R1)
The input signal can be an impulse, a step, a ramp, or a more general signal modeled as
the impulse response of some input shaping filter. For example, a sine wave with
frequency can be modeled as the impulse response of .
w0 = 2;
F = tf(w0^2,[1 0 w0^2]); % input shaping filter
17-29
17 Control System Tuning Examples
R2 = TuningGoal.Transient('r','y',tf(1,[1 1 1]),F);
viewGoal(R2)
LQG Design
17-30
See Also
To regulate around zero, you can use the following LQG criterion:
The first term in the integral penalizes the deviation of from zero, and the second
term penalizes the control effort. Using systune, you can tune the PID controller to
minimize the cost . To do this, use the LQG requirement
See Also
TuningGoal.LQG | TuningGoal.StepRejection | TuningGoal.StepTracking |
TuningGoal.Transient
Related Examples
• “Frequency-Domain Specifications” on page 17-32
17-31
17 Control System Tuning Examples
Frequency-Domain Specifications
This example gives a tour of available frequency-domain requirements for control system
tuning with systune or looptune.
Background
The systune and looptune commands tune the parameters of fixed-structure control
systems subject to a variety of time- and frequency-domain requirements. The
TuningGoal package is the repository for such design requirements.
Gain Limit
s = tf('s');
R1 = TuningGoal.Gain('d','y',s/(s+1)^2);
specifies that the gain from d to y should not exceed the magnitude of the transfer
function .
viewGoal(R1)
17-32
Frequency-Domain Specifications
It is often convenient to just sketch the asymptotes of the desired gain profile. For
example, instead of the transfer function , we could just specify gain values of
0.01,1,0.01 at the frequencies 0.01,1,100, the point (1,1) being the breakpoint of the two
asymptotes and .
Asymptotes = frd([0.01,1,0.01],[0.01,1,100]);
R2 = TuningGoal.Gain('d','y',Asymptotes);
The requirement object automatically turns this discrete gain profile into a gain limit
defined at all frequencies.
bodemag(Asymptotes,R2.MaxGain)
legend('Specified','Interpolated')
17-33
17 Control System Tuning Examples
Variance Amplification
R = TuningGoal.Variance('n','y',0.1);
17-34
Frequency-Domain Specifications
R1 = TuningGoal.Tracking('r','y',2);
specifies that the output y should track the reference r with a two-second response time.
Similarly
R2 = TuningGoal.Tracking({'Vsp','wsp'},{'V','w'},2);
specifies that V should track Vsp and w should track wsp with minimum cross-coupling
between the two responses. Tracking requirements are converted into frequency-domain
constraints on the tracking error as a function of frequency. For the first requirement R1,
for example, the gain from r to the tracking error e = r-y should be small at low
frequency and approach 1 (100%) at frequencies greater than 1 rad/s (bandwidth for a
two-second response time). You can use viewGoal to visualize this frequency-domain
constraint. Note that the yellow region indicates where the requirement is violated.
viewGoal(R1)
17-35
17 Control System Tuning Examples
R3 = TuningGoal.Overshoot('r','y',10);
Disturbance Rejection
In feedback loops such as the one shown in Figure 1, the open- and closed-loop responses
from disturbance to output are related by
17-36
Frequency-Domain Specifications
where is the loop transfer function measured at the disturbance entry point. The
gain of is the disturbance attenuation factor, the ratio between the open- and
closed-loop sensitivities to the disturbance. Its reciprocal is the sensitivity
at the disturbance input.
R1 = TuningGoal.Rejection('u',10);
R1.Focus = [0 1];
specifies that a disturbance entering at the plant input "u" should be attenuated by a
factor 10 in the frequency band from 0 to 1 rad/s.
viewGoal(R1)
17-37
17 Control System Tuning Examples
More generally, you can specify a frequency-dependent attenuation profile, for example
s = tf('s');
R2 = TuningGoal.Rejection('u',(s+10)/(s+0.1));
specifies an attenuation factor of 100 below 0.1 rad/s gradually decreasing to 1 (no
attenuation) after 10 rad/s.
viewGoal(R2)
17-38
Frequency-Domain Specifications
R3 = TuningGoal.Sensitivity('u',(s+0.1)/(s+10));
is equivalent to the rejection requirement R2 above. The sensitivity increases from 0.01
(1%) below 0.1 rad/s to 1 (100%) above 10 rad/s.
viewGoal(R3)
17-39
17 Control System Tuning Examples
WL = blkdiag(1/(s+0.001),s/(0.001*s+1));
WR = [];
R = TuningGoal.WeightedGain('r',{'e','y'},WL,[]);
17-40
See Also
Note that this is a normalized gain constraint (unit bound across frequency).
viewGoal(R)
See Also
TuningGoal.Gain | TuningGoal.Overshoot | TuningGoal.Rejection |
TuningGoal.Sensitivity | TuningGoal.Tracking | TuningGoal.Variance |
TuningGoal.WeightedGain | TuningGoal.WeightedVariance
17-41
17 Control System Tuning Examples
Related Examples
• “Time-Domain Specifications” on page 17-26
• “Loop Shape and Stability Margin Specifications” on page 17-43
17-42
Loop Shape and Stability Margin Specifications
Background
The systune and looptune commands tune the parameters of fixed-structure control
systems subject to a variety of time- and frequency-domain requirements. The
TuningGoal package is the repository for such design requirements.
Loop Shape
s = tf('s');
R1 = TuningGoal.LoopShape('u',1/s);
specifies that the open-loop response measured at the location "u" should look like a pure
integrator (as far as its gain is concerned). In MATLAB, use an AnalysisPoint block to
mark the location "u", see the "Building Tunable Models" example for details. In Simulink,
use the addPoint method of the slTuner interface to mark "u" as a point of interest.
As with other gain specifications, you can just specify the asymptotes of the desired loop
shape using a few frequency points. For example, to specify a loop shape with gain
crossover at 1 rad/s, -20 dB/decade slope before 1 rad/s, and -40 dB/decade slope after 1
rad/s, just specify that the gain at the frequencies 0.1,1,10 should be 10,1,0.01,
respectively.
LS = frd([10,1,0.01],[0.1,1,10]);
R2 = TuningGoal.LoopShape('u',LS);
bodemag(LS,R2.LoopGain)
legend('Specified','Interpolated')
17-43
17 Control System Tuning Examples
Loop shape requirements are constraints on the open-loop response . For tuning
purposes, they are converted into closed-loop gain constraints on the sensitivity function
and complementary sensitivity function . Use viewGoal to
visualize the target loop shape and corresponding gain bounds on (green) and (red).
viewGoal(R2)
17-44
Loop Shape and Stability Margin Specifications
17-45
17 Control System Tuning Examples
MaxLG.Focus = [1 Inf];
viewGoal([MinLG MaxLG])
The TuningGoal.MaxLoopGain requirement rests on the fact that the open- and closed-
loop gains are comparable when the loop gain is small ( ). As a result, it can be
ineffective at keeping the loop gain below some value close to 1. For example, suppose
that flexible modes cause gain spikes beyond the crossover frequency and that you need
to keep these spikes below 0.5 (-6 dB). Instead of using TuningGoal.MaxLoopGain, you
can directly constrain the gain of using TuningGoal.Gain with a loop opening at "u".
MaxLG = TuningGoal.Gain('u','u',0.5);
MaxLG.Opening = 'u';
17-46
Loop Shape and Stability Margin Specifications
If the open-loop response is unstable, make sure to further disable the implicit stability
constraint associated with this requirement.
MaxLG.Stabilize = false;
Figure 1 shows this requirement evaluated for an open-loop response with flexible modes.
Stability Margins
17-47
17 Control System Tuning Examples
enforces dB of gain margin and 45 degrees of phase margin at the location "u". In
MATLAB, use a AnalysisPoint block to mark the location "u", see the "Building
Tunable Models" example for details. In Simulink, use the addPoint method of the
slTuner interface to mark "u" as a point of interest. Stability margins are typically
measured at the plant inputs or plant outputs or both.
The target gain and phase margin values are converted into a normalized gain constraint
on some appropriate closed-loop transfer function. The desired margins are achieved at
frequencies where the gain is less than 1.
viewGoal(R)
17-48
See Also
See Also
TuningGoal.LoopShape | TuningGoal.Margins | TuningGoal.MaxLoopGain |
TuningGoal.MinLoopGain
Related Examples
• “Stability Margins in Control System Tuning” on page 14-218
• “Frequency-Domain Specifications” on page 17-32
17-49
17 Control System Tuning Examples
Background
The systune and looptune commands tune the parameters of fixed-structure control
systems subject to a variety of time- and frequency-domain requirements. The
TuningGoal package is the repository for such design requirements.
Closed-Loop Poles
The TuningGoal.Poles goal constrains the location of the closed-loop poles. You can
enforce some minimum decay rate
For example
MinDecay = 0.5;
MinDamping = 0.7;
MaxFrequency = 10;
R = TuningGoal.Poles(MinDecay,MinDamping,MaxFrequency);
viewGoal(R)
17-50
System Dynamics Specifications
Increasing the MinDecay value results in faster transients. Increasing the MinDamping
value results in better damped transients. Decreasing the MaxFrequency value prevents
fast dynamics.
Controller Poles
17-51
17 Control System Tuning Examples
MinDecay = 0;
R = TuningGoal.ControllerPoles('C',MinDecay);
See Also
TuningGoal.ControllerPoles | TuningGoal.Poles
Related Examples
• “Loop Shape and Stability Margin Specifications” on page 17-43
17-52
Tuning Control Systems with SYSTUNE
This example uses a 9th-order model of the head-disk assembly (HDA) in a hard-disk
drive. This model captures the first few flexible modes in the HDA.
load rctExamples G
bode(G), grid
17-53
17 Control System Tuning Examples
We use the feedback loop shown below to position the head on the correct track. This
control structure consists of a PI controller and a low-pass filter in the return path. The
head position y should track a step change r with a response time of about one
millisecond, little or no overshoot, and no steady-state error.
You can use systune to directly tune the PI gains and filter coefficient subject to a
variety of time- and frequency-domain requirements.
There are two tunable elements in the control structure of Figure 1: the PI controller
and the low-pass filter
C0 = tunablePID('C','pi'); % tunable PI
To parameterize the lowpass filter , create a tunable real parameter and construct a
first-order transfer function with numerator and denominator :
See the "Building Tunable Models" example for an overview of available tunable
elements.
17-54
Tuning Control Systems with SYSTUNE
Next build a closed-loop model of the feedback loop in Figure 1. To facilitate open-loop
analysis and specify open-loop requirements such as desired stability margins, add an
analysis point at the plant input u:
AP = AnalysisPoint('u');
Use feedback to build a model of the closed-loop transfer from reference r to head
position y:
The result T0 is a generalized state-space model (genss) that depends on the tunable
elements and .
17-55
17 Control System Tuning Examples
You can now use systune to tune the PI gain and filter coefficient . This function takes
the tunable closed-loop model T0 and the requirements Req1,Req2. Use a few
randomized starting points to improve the chances of getting a globally optimal design.
rng('default')
Options = systuneOptions('RandomStart',3);
[T,fSoft] = systune(T0,[Req1,Req2],Options);
All requirements are normalized so a requirement is satisfied when its value is less than
1. Here the final value is slightly greater than 1, indicating that the requirements are
nearly satisfied. Use the output fSoft to see the tuned value of each requirement. Here
we see that the first requirement (tracking) is slightly violated while the second
requirement (margins) is satisfied.
fSoft
fSoft =
1.3461 0.6326
The first output T of systune is the "tuned" closed-loop model. Use showTunable or
getBlockValue to access the tuned values of the PI gains and filter coefficient:
getBlockValue(T,'C') % tuned value of PI controller
ans =
17-56
Tuning Control Systems with SYSTUNE
1
Kp + Ki * ---
s
Name: C
Continuous-time PI controller in parallel form.
C =
1
Kp + Ki * ---
s
Name: C
Continuous-time PI controller in parallel form.
-----------------------------------
a = 3.19e+03
Validating Results
First use viewGoal to inspect how the tuned system does against each requirement. The
first plot shows the tracking error as a function of frequency, and the second plot shows
the normalized disk margins as a function of frequency (see loopmargin). See the
"Creating Design Requirements" example for details.
17-57
17 Control System Tuning Examples
Next plot the closed-loop step response from reference r to head position y. The response
has no overshoot but wobbles a little.
clf, step(T)
17-58
Tuning Control Systems with SYSTUNE
To investigate further, use getLoopTransfer to get the open-loop response at the plant
input.
L = getLoopTransfer(T,'u');
bode(L,{1e3,1e6}), grid
title('Open-loop response')
17-59
17 Control System Tuning Examples
The wobble is due to the first resonance after the gain crossover. To eliminate it, you
could add a notch filter to the feedback loop and tune its coefficients along with the
lowpass coefficient and PI gains using systune.
See Also
TuningGoal.Margins | TuningGoal.Tracking | systune
Related Examples
• “Building Tunable Models” on page 17-71
• “Tune Control Systems in Simulink”
17-60
Tune Control Systems in Simulink
For this example we use the following model of an engine speed control system:
open_system('rct_engine_speed')
The control system consists of a single PID loop and the PID controller gains must be
tuned to adequately respond to step changes in the desired speed. Specifically, we want
the response to settle in less than 5 seconds with little or no overshoot. While pidtune is
a faster alternative for tuning a single PID controller, this simple example is well suited
for an introduction to the systune and looptune workflows in Simulink.
The slTuner interface provides a convenient gateway to systune for control systems
modeled in Simulink. This interface lets you specify which blocks in the Simulink model
are tunable and what signals are of interest for open- or closed-loop validation. Create an
slTuner instance for the rct_engine_speed model and list the "PID Controller" block
(highlighted in orange) as tunable. Note that all Linear Analysis points in the model
(signals "Ref" and "Speed" here) are automatically available as points of interest for
tuning.
17-61
17 Control System Tuning Examples
The PID block is initialized with its value in the Simulink model, which you can access
using getBlockValue. Note that the proportional and derivative gains are initialized to
zero.
getBlockValue(ST0,'PID Controller')
ans =
1
Ki * ---
s
with Ki = 0.01
Name: PID_Controller
Continuous-time I-only controller.
Next create a step tracking requirement to capture the target settling time of 5 seconds.
Use the signal names in the Simulink model to refer to the reference and output signals,
and specify the target response as a first-order response with time constant of 1 second.
TrackReq = TuningGoal.StepTracking('Ref','Speed',1);
You can now tune the control system ST0 subject to the requirement TrackReq.
ST1 = systune(ST0,TrackReq);
The final value is close to 1 indicating that the tracking requirement is met. systune
returns a "tuned" version ST1 of the control system described by ST0. Again use
getBlockValue to access the tuned values of the PID gains:
getBlockValue(ST1,'PID Controller')
ans =
1 s
Kp + Ki * --- + Kd * --------
s Tf*s+1
17-62
Tune Control Systems in Simulink
Name: PID_Controller
Continuous-time PIDF controller in parallel form.
To simulate the closed-loop response to a step command in speed, get the initial and
tuned transfer functions from speed command "Ref" to "Speed" output and plot their step
responses:
T0 = getIOTransfer(ST0,'Ref','Speed');
T1 = getIOTransfer(ST1,'Ref','Speed');
step(T0,T1)
legend('Initial','Tuned')
17-63
17 Control System Tuning Examples
You can also use looptune to tune control systems modeled in Simulink. The looptune
workflow is very similar to the systune workflow. One difference is that looptune needs
to know the boundary between the plant and controller, which is specified in terms of
controls and measurements signals. For a single loop the performance is essentially
captured by the response time, or equivalently by the open-loop crossover frequency.
Based on first-order characteristics the crossover frequency should exceed 1 rad/s for the
closed-loop response to settle in less than 5 seconds. You can therefore tune the PID loop
using 1 rad/s as target 0-dB crossover frequency.
Again the final value is close to 1, indicating that the target control bandwidth was
achieved. As with systune, use getIOTransfer to compute and plot the closed-loop
response from speed command to actual speed. The result is very similar to that obtained
with systune.
T0 = getIOTransfer(ST0,'Ref','Speed');
T1 = getIOTransfer(ST1,'Ref','Speed');
step(T0,T1)
legend('Initial','Tuned')
17-64
Tune Control Systems in Simulink
You can also perform open-loop analysis, for example, compute the gain and phase
margins at the plant input u.
margin(L), grid
17-65
17 Control System Tuning Examples
Validation in Simulink
Once you are satisfied with the systune or looptune results, you can upload the tuned
controller parameters to Simulink for further validation with the nonlinear model.
writeBlockValue(ST1)
You can now simulate the engine response with the tuned PID controller.
17-66
Tune Control Systems in Simulink
The nonlinear simulation results closely match the linear responses obtained in MATLAB.
It is often useful to constrain the range of tuned parameters to weed out undesirable
solutions. For example, you may require that the proportional and derivative gains of the
PID controller be nonnegative. To do this, access the tuned block parameterization.
C = getBlockParam(ST0,'PID Controller')
C =
1 s
Kp + Ki * --- + Kd * --------
s Tf*s+1
Type "pid(C)" to see the current value and "get(C)" to see all properties.
17-67
17 Control System Tuning Examples
Retune the PID gains and verify that the proportional and derivative gains are indeed
nonnegative.
ST1 = looptune(ST0,Control,Measurement,wc);
showTunable(ST1)
1 s
Kp + Ki * --- + Kd * --------
s Tf*s+1
Name: PID_Controller
Continuous-time PIDF controller in parallel form.
Closer inspection of the tuned PID gains suggests that the contribution of the derivative
term is minor. This suggests using a simpler PI controller instead. To do this, override the
default parameterization for the "PID Controller" block:
setBlockParam(ST0,'PID Controller',tunablePID('C','pi'))
This specifies that the "PID Controller" block should now be parameterized as a mere PI
controller. Next re-tune the control system for this simpler controller:
ST2 = looptune(ST0,Control,Measurement,wc);
17-68
See Also
Again the final value is less than one indicating success. Compare the closed-loop
response with the previous ones:
T2 = getIOTransfer(ST2,'Ref','Speed');
step(T0,T1,T2,'r--')
legend('Initial','PID','PI')
See Also
TuningGoal.Tracking | slTuner | systune (slTuner)
17-69
17 Control System Tuning Examples
Related Examples
• “Create and Configure slTuner Interface to Simulink Model” on page 14-212
17-70
Building Tunable Models
Background
You can tune the gains and parameters of your control system with systune or
looptune. To use these commands, you need to construct a tunable model of the control
system that identifies and parameterizes its tunable elements. This is done by combining
numeric LTI models of the fixed elements with parametric models of the tunable
elements.
You can use one of the following "parametric" blocks to model commonly encountered
tunable elements:
17-71
17 Control System Tuning Examples
First model each block in the block diagram, using suitable parametric blocks for and
.
G = tf(1,[1 1]);
C = tunablePID('C','pid'); % tunable PID block
F = tunableTF('F',0,1); % tunable first-order transfer function
Then use connect to build a model of the overall block diagram. To specify how the
blocks are connected, label the inputs and outputs of each block and model the summing
junctions using sumblk.
% Summing junctions
S1 = sumblk('e = r-y');
S2 = sumblk('u = uF + uC');
T = connect(G,C,F,S1,S2,'r','y')
T =
Type "ss(T)" to see the current value, "get(T)" to see all properties, and "T.Blocks" t
This creates a generalized state-space model T of the closed-loop transfer function from r
to y. This model depends on the tunable blocks C and F. You can use systune to
automatically tune the PID gains and the feedforward coefficients a,b subject to your
performance requirements. Use showTunable to see the current value of the tunable
blocks.
showTunable(T)
C =
1
Ki * ---
s
17-72
Building Tunable Models
with Ki = 0.001
Name: C
Continuous-time I-only controller.
-----------------------------------
F =
10
------
s + 10
Name: F
Continuous-time transfer function.
You can adjust the parameterization of the tunable elements and by interacting with
the objects C and F. Use get to see their list of properties.
get(C)
A PID controller has four tunable parameters Kp,Ki,Kd,Tf. The tunable block C contains
a description of each of these parameters. Parameter attributes include current value,
minimum and maximum values, and whether the parameter is free or fixed.
C.Kp
17-73
17 Control System Tuning Examples
ans =
Name: 'Kp'
Value: 0
Minimum: -Inf
Maximum: Inf
Free: 1
Scale: 1
Info: [1x1 struct]
1x1 param.Continuous
Set the corresponding attributes to override defaults. For example, you can fix the time
constant Tf to the value 0.1 by
C.Tf.Value = 0.1;
C.Tf.Free = false;
For tunable elements not covered by the pre-defined blocks listed above, you can create
your own parameterization in terms of elementary real parameters (realp). Consider the
low-pass filter
where the coefficient is tunable. To model this tunable element, create a real parameter
and define as a transfer function whose numerator and denominator are functions of
. This creates a generalized state-space model F of the low-pass filter parameterized by
the tunable scalar a.
F =
17-74
Building Tunable Models
Type "ss(F)" to see the current value, "get(F)" to see all properties, and "F.Blocks" t
Similarly, you can use real parameters to model the notch filter
wn = realp('wn',100);
zeta1 = realp('zeta1',1); zeta1.Maximum = 1; % zeta1 <= 1
zeta2 = realp('zeta2',1); zeta2.Maximum = 1; % zeta2 <= 1
N = tf([1 2*zeta1*wn wn^2],[1 2*zeta2*wn wn^2]); % tunable notch filter
You can also create tunable elements with matrix-valued parameters. For example, model
the observer-based controller with equations
K = realp('K',zeros(2,6));
L = realp('L',zeros(6,3));
C = ss(A-B*K-L*C,L,-K,0)
C =
Type "ss(C)" to see the current value, "get(C)" to see all properties, and "C.Blocks" t
17-75
17 Control System Tuning Examples
The systune command takes a closed-loop model of the overall control system, like the
tunable model T built at the beginning of this example. Such models do not readily
support open-loop analysis or open-loop specifications such as loop shapes and stability
margins. To gain access to open-loop responses, insert an AnalysisPoint block as
shown in Figure 2.
The AnalysisPoint block can be used to mark internal signals of interest as well as
locations where to open feedback loops and measure open-loop responses. This block
evaluates to a unit gain and has no impact on the model responses. For example,
construct a closed-loop model T of the feedback loop of Figure 2 where is a tunable
PID.
G = tf(1,[1 1]);
C = tunablePID('C','pid');
AP = AnalysisPoint('X');
T = feedback(G*C,AP);
You can now use getLoopTransfer to compute the (negative-feedback) loop transfer
function measured at the location "X". Note that this loop transfer function is for
the feedback loop of Figure 2.
17-76
Building Tunable Models
You can also refer to the location "X" when specifying target loop shapes or stability
margins for systune. The requirement then applies to the loop transfer measured at this
location.
% Target loop shape for loop transfer at "X"
Req1 = TuningGoal.LoopShape('X',tf(5,[1 0]));
17-77
17 Control System Tuning Examples
You can override the default location names and use more descriptive names by modifying
the Location property.
See Also
AnalysisPoint
Related Examples
• “Generalized Models” on page 1-16
• “Models with Tunable Coefficients” on page 1-19
• “Mark Signals of Interest for Control System Analysis and Design” (Simulink Control
Design)
17-78
Tune a Control System Using Control System Tuner
Control System Tuner lets you model any control architecture and specify the structure of
controller components, such as PID controllers, gains, and other elements. You specify
which blocks in the model are tunable. Control System Tuner parameterizes those blocks
and tunes the free parameters system to meet design requirements that you specify, such
as setpoint tracking, disturbance rejection, and stability margins.
This example uses the Simulink model rct_helico. Open the model.
open_system('rct_helico')
17-79
17 Control System Tuning Examples
The control system of the model has two feedback loops. The inner loop provides static
output feedback for stability augmentation and decoupling, represented in the model by
the gain block SOF. The outer loop has a PI controller for each of the three attitude
angles. The controller generates commands ds,dc,dT in degrees for the longitudinal
cyclic, lateral cyclic, and tail rotor collective using measurements of theta, phi, p, q,
and r. This loop provides the desired setpoint tracking for the three angles.
• Track setpoint changes in theta, phi, and r with zero steady-state error, rise times of
about 2 seconds, minimal overshoot, and minimal cross-coupling.
• Limit the control bandwidth to guard against neglected high-frequency rotor dynamics
and measurement noise. (The model contains low-pass filters that partially enforce this
objective.)
• Provide strong multivariable gain and phase margins. (Multivariable margins measure
robustness to simultaneous gain or phase variations at the plant inputs and outputs.
See the loopmargin reference page for details.)
Using Control System Tuner, you can jointly tune the inner and outer loops to meet all the
design requirements. To set up the model for tuning, open the app and specify which
blocks of the Simulink model you want to tune.
In the Simulink model window, in the Analysis menu, select Control Design > Control
System Tuner.
17-80
Tune a Control System Using Control System Tuner
In Control System Tuner, on the Tuning tab, click Select Blocks. Use the Select tuned
blocks dialog box to specify the blocks to tune.
17-81
17 Control System Tuning Examples
Click Add Blocks. Control System Tuner analyzes your model to find blocks that can be
tuned. For this example, the controller blocks to tune are the three PI controllers and the
gain block. Check the corresponding blocks PI1, PI2, PI3, and SOF.
17-82
Tune a Control System Using Control System Tuner
Click OK. The Select tuned blocks dialog box now reflects the blocks you added.
17-83
17 Control System Tuning Examples
When you select a block to tune, Control System Tuner automatically parameterizes the
block according to its type and initializes the parameterization with the block value in the
Simulink model. In this example, the PI controllers are initialized to and the static
output-feedback gain is initialized to zero on all channels. Simulating the model shows
that the control system is unstable for these initial values.
17-84
Tune a Control System Using Control System Tuner
The design requirements for this system, discussed previously, include setpoint tracking,
minimum stability margins, and a limit on fast dynamics. In Control System Tuner, you
capture design requirements using tuning goals.
First, create a tuning goal for the setpoint-tracking requirement on theta, phi, and r.
On the Tuning tab, in the New Goal drop-down list, select Tracking of step
commands.
17-85
17 Control System Tuning Examples
17-86
Tune a Control System Using Control System Tuner
In the Step Tracking Goal dialog, specify the reference signals for tracking. Under
Specify step-response inputs, click Add signal to list. Then click Select signal from
model.
In the Simulink model editor, select the reference signals theta_ref, phi_ref, and
r_ref. These signals appear in the Select signals dialog box. Click Add Signal(s) to add
them to the step tracking goal.
Next, specify the outputs that you want to track those references. Under Specify step-
response outputs, add the outputs theta, phi, and r.
The requirement is that the responses at the outputs track the reference commands with
a first-order response that has a one-second time constant. Enter these values in the
17-87
17 Control System Tuning Examples
Desired Response section of the dialog box. Also, for this example set Keep mismatch
below to 20. This value sets a 20% relative mismatch between the target first-order
response and the tuned response.
This figure shows the configuration of the Step Tracking Goal dialog box. Click OK to
save the tuning goal.
17-88
Tune a Control System Using Control System Tuner
17-89
17 Control System Tuning Examples
Next, create tuning goals for the desired stability margin requirements. For this example,
the multivariable gain and phase margins at the plant inputs u and plant outputs y must
be at least 5 dB and 40 degrees. Create separate tuning goals for the input and output
margin constraints. In the New Goal drop-down list, select Minimum stability
margins. In the Margins Goal dialog box, add the input signal u under Measure
stability margins at the following locations. Also, enter the gain and phase values 5
and 40 in the Desired Margins section of the dialog box. Click OK to save the input
stability margin goal.
17-90
Tune a Control System Using Control System Tuner
Create another Margins Goal for the output stability margin. Specify the output signal y
and the target margins, as shown, and save the output stability margin goal.
17-91
17 Control System Tuning Examples
The last requirement is to limit fast dynamics and jerky transients. To achieve this, create
a tuning goal that constrains the magnitude of the closed-loop poles to less than 25 rad/s.
In the New Goal drop-down list, select Constraint on closed-loop dynamics. In the
17-92
Tune a Control System Using Control System Tuner
Poles Goal dialog box, specify the maximum natural frequency of 25, and click OK to
save the tuning goal.
17-93
17 Control System Tuning Examples
As you create each tuning goal, Control System Tuner creates a new figure that displays a
graphical representation of the tuning goal. When you tune your control system, you can
refer to this figure for a graphical representation of how closely the tuned system satisfies
the tuning goal.
Tune the control system to meet the design requirements you have specified.
On the Tuning tab, click Tune. Control System Tuner adjusts the tunable parameters to
values that best meet those requirements.
17-94
Tune a Control System Using Control System Tuner
Control System Tuner automatically updates the tuning-goal plots to reflect the tuned
parameter values. Examine these plots to see how well the requirements are satisfied by
the design. For instance, examine the tuned step responses of tracking requirements.
The blue line shows that the tuned response is very close to the target response, in pink.
The rise time is about two seconds, and there is no overshoot and little cross-coupling.
17-95
17 Control System Tuning Examples
You can also view a numeric report of the tuning results. Click the Tuning Report at the
bottom right of Control System Tuner.
17-96
Tune a Control System Using Control System Tuner
When you tune the model, Control System Tuner converts each tuning goal to a function
of the tunable parameters of the system and adjusts the parameters to minimize the value
of those functions. For this example, the tuning report shows that the final values for all
tuning goals are close to 1, which indicates that all the requirements are nearly met.
Control System Tuner tunes the parameters for a linearization of the control system.
Therefore, it is important to validate the design on the full nonlinear Simulink model.
17-97
17 Control System Tuning Examples
Write the tuned parameter values back to the Simulink model. On the Control System
tab, click Update Blocks. In the Simulink model window, simulate the model with the
new parameter values. Observe the response to the step changes in setpoint commands,
theta-ref, phi-ref, and r-ref at 0, 3, and 6 seconds respectively.
The responses of the nonlinear system are satisfactory. The rise time of each response is
about 2 seconds with no overshoot, no steady-state error, and minimal cross-coupling, as
specified in the design requirements.
See Also
Control System Tuner
17-98
See Also
Related Examples
• “Specify Operating Points for Tuning in Control System Tuner” on page 14-15
• “Tuning for Multiple Values of Plant Parameters”
17-99
17 Control System Tuning Examples
Background
Both systune and looptune use local optimization methods for tuning the control
architecture at hand. To mitigate the risk of ending up with a locally optimal but globally
poor design, it is recommended to run several optimizations starting from different
randomly generated initial points. If you have a multi-core machine or have access to
distributed computing resources, you can significantly speed up this process using the
Parallel Computing Toolbox.
This example shows how to parallelize the tuning of an airframe autopilot with looptune.
See the example "Tuning of a Two-Loop Autopilot" for more details about this application
of looptune.
Autopilot Tuning
open_system('rct_airframe1')
17-100
Using Parallel Computing to Accelerate Tuning
The autopilot consists of two cascaded loops whose tunable elements include two PI
controller gains ("az Control" block) and one gain in the pitch-rate loop ("q Gain" block).
The vertical acceleration az should track the command azref with a 1 second response
time. Use slTuner to configure this tuning task (see "Tuning of a Two-Loop Autopilot"
example for details):
% Design requirements
wc = [3,12]; % bandwidth
TrackReq = TuningGoal.Tracking('az ref','az',1); % tracking
We are ready to tune the autopilot gains with looptune. To minimize the risk of getting a
poor-quality local minimum, run 30 optimizations starting from 30 randomly generated
values of the three gains. Configure the looptune options to enable parallel processing
of these 30 runs:
17-101
17 Control System Tuning Examples
rng('default')
Options = looptuneOptions('RandomStart',30,'UseParallel',true);
Next call looptune to launch the tuning algorithm. The 30 runs are automatically
distributed across available computing resources:
Starting parallel pool (parpool) using the 'local' profile ... connected to 6 workers.
Final: Failed to enforce closed-loop stability (max Re(s) = 0.042)
Final: Failed to enforce closed-loop stability (max Re(s) = 0.039)
Final: Failed to enforce closed-loop stability (max Re(s) = 0.041)
Final: Failed to enforce closed-loop stability (max Re(s) = 0.041)
Final: Failed to enforce closed-loop stability (max Re(s) = 0.041)
Final: Failed to enforce closed-loop stability (max Re(s) = 0.082)
Final: Failed to enforce closed-loop stability (max Re(s) = 0.041)
Final: Peak gain = 1.23, Iterations = 53
Final: Peak gain = 62, Iterations = 92
Some closed-loop poles are marginally stable (decay rate near 1e-07)
Final: Peak gain = 62, Iterations = 128
Some closed-loop poles are marginally stable (decay rate near 1e-07)
Final: Peak gain = 1.23, Iterations = 128
Final: Failed to enforce closed-loop stability (max Re(s) = 0.041)
Final: Peak gain = 1.23, Iterations = 130
Final: Failed to enforce closed-loop stability (max Re(s) = 0.041)
Final: Failed to enforce closed-loop stability (max Re(s) = 0.041)
Final: Failed to enforce closed-loop stability (max Re(s) = 0.04)
Final: Failed to enforce closed-loop stability (max Re(s) = 0.041)
Final: Failed to enforce closed-loop stability (max Re(s) = 0.082)
Final: Failed to enforce closed-loop stability (max Re(s) = 0.041)
Final: Peak gain = 1.23, Iterations = 98
Final: Peak gain = 61.9, Iterations = 79
Final: Failed to enforce closed-loop stability (max Re(s) = 0.039)
Final: Failed to enforce closed-loop stability (max Re(s) = 0.041)
Final: Failed to enforce closed-loop stability (max Re(s) = 0.041)
Final: Failed to enforce closed-loop stability (max Re(s) = 0.041)
Final: Failed to enforce closed-loop stability (max Re(s) = 0.041)
Final: Failed to enforce closed-loop stability (max Re(s) = 0.082)
Final: Failed to enforce closed-loop stability (max Re(s) = 0.051)
Final: Failed to enforce closed-loop stability (max Re(s) = 0.041)
Final: Failed to enforce closed-loop stability (max Re(s) = 0.041)
Final: Peak gain = 1.23, Iterations = 42
17-102
Using Parallel Computing to Accelerate Tuning
Most runs return 1.23 as optimal gain value, suggesting that this local minimum has a
wide region of attraction and is likely to be the global optimum. Use showBlockValue to
see the corresponding gain values:
showBlockValue(ST)
AnalysisPoints_ =
D =
u1 u2 u3 u4
y1 1 0 0 0
y2 0 1 0 0
y3 0 0 1 0
y4 0 0 0 1
Name: AnalysisPoints_
Static gain.
-----------------------------------
az_Control =
1
Kp + Ki * ---
s
Name: az_Control
Continuous-time PI controller in parallel form.
-----------------------------------
q_Gain =
D =
u1
y1 1.985
Name: q_Gain
Static gain.
T = getIOTransfer(ST,'az ref','az');
step(T,5)
17-103
17 Control System Tuning Examples
See Also
slTuner | systune | systune (slTuner)
17-104
Control of a Linear Electric Actuator
The electrical and mechanical components are modeled using Simscape Electronics and
Simscape Multibody. The control system consists of two cascaded feedback loops
controlling the driving current and angular speed of the DC motor.
17-105
17 Control System Tuning Examples
Note that the inner-loop (current) controller is a proportional gain while the outer-loop
(speed) controller has proportional and integral actions. The output of both controllers is
limited to plus/minus 5.
Design Specifications
We need to tune the proportional and integral gains to respond to a 2000 rpm speed
demand in about 0.1 seconds with minimum overshoot. The initial gain settings in the
model are P=50 and PI(s)=0.2+0.1/s and the corresponding response is shown in Figure
2. This response is too slow and too sensitive to load disturbances.
17-106
Control of a Linear Electric Actuator
You can use systune to jointly tune both feedback loops. To set up the design, create an
instance of the slTuner interface with the list of tuned blocks. All blocks and signals are
specified by their names in the model. The model is linearized at t=0.5 to avoid
discontinuities in some derivatives at t=0.
The data structure ST0 contains a description of the control system and its tunable
elements. Next specify that the DC motor should follow a 2000 rpm speed demand in 0.1
seconds:
You can now tune the proportional and integral gains with looptune:
ST1 = systune(ST0,TR);
17-107
17 Control System Tuning Examples
This returns an updated description ST1 containing the tuned gain values. To validate this
design, plot the closed-loop response from speed demand to speed:
The response looks good in the linear domain so push the tuned gain values to Simulink
and further validate the design in the nonlinear model.
writeBlockValue(ST1)
17-108
Control of a Linear Electric Actuator
The nonlinear simulation results appear in Figure 3. The nonlinear behavior is far worse
than the linear approximation, a discrepancy that can be traced to saturations in the
inner loop (see Figure 4).
17-109
17 Control System Tuning Examples
Preventing Saturations
So far we have only specified a desired response time for the outer (speed) loop. This
leaves systune free to allocate the control effort between the inner and outer loops.
Saturations in the inner loop suggest that the proportional gain is too high and that some
rebalancing is needed. One possible remedy is to explicitly limit the gain from the speed
command to the outputs of the P and PI controllers. For a speed reference of 2000 rpm
and saturation limits of plus/minus 5, the average gain should not exceed 5/2000 =
0.0025. To be conservative, we can try to keep the gain from speed reference to controller
outputs below 0.001. To do this, add two gain requirements and retune the controller
gains with all three requirements in place.
The final gain 1.39 indicates that the requirements are nearly but not exactly met (all
requirements are met when the final gain is less than 1). Use viewGoal to inspect how
the tuned controllers fare against each requirement.
figure('Position',[100,100,560,550])
viewGoal([TR,MG1,MG2],ST2)
17-110
Control of a Linear Electric Actuator
17-111
17 Control System Tuning Examples
step(T1,'b',T2,'g--')
legend('Initial tuning','Tuning with Gain Constraints')
The second design is less aggressive but still meets the response time requirement.
Finally, push the new tuned gain values to the Simulink model and simulate the response
to a 2000 rpm speed demand and 500 N load disturbance. The simulation results appear
in Figure 5 and the current controller output is shown in Figure 6.
writeBlockValue(ST2)
17-112
Control of a Linear Electric Actuator
17-113
17 Control System Tuning Examples
The nonlinear responses are now satisfactory and the current loop is no longer
saturating. The additional gain constraints have forced systune to re-distribute the
control effort between the inner and outer loops so as to avoid saturation.
See Also
TuningGoal.Gain | TuningGoal.Tracking | slTuner | systune (slTuner) |
writeBlockValue
Related Examples
• “Control of a Linear Electric Actuator Using Control System Tuner” on page 17-115
• “Tuning Control Systems with SYSTUNE”
• “Tune Control Systems in Simulink”
17-114
Control of a Linear Electric Actuator Using Control System Tuner
open_system('rct_linact')
The electrical and mechanical components are modeled using Simscape Electronics and
Simscape Multibody. The control system consists of two cascaded feedback loops
controlling the driving current and angular speed of the DC motor.
17-115
17 Control System Tuning Examples
Note that the inner-loop (current) controller is a proportional gain while the outer-loop
(speed) controller has proportional and integral actions. The output of both controllers is
limited to plus/minus 5.
Design Specifications
We need to tune the proportional and integral gains to respond to a 2000 rpm speed
demand in about 0.1 seconds with minimum overshoot. The initial gain settings in the
model are P=50 and PI(s)=0.2+0.1/s and the corresponding response is shown in Figure
2. This response is too slow and too sensitive to load disturbances.
17-116
Control of a Linear Electric Actuator Using Control System Tuner
You can use Control System Tuner to jointly tune both feedback loops. First, open Control
System Tuner from Simulink Analysis Menu.
17-117
17 Control System Tuning Examples
17-118
Control of a Linear Electric Actuator Using Control System Tuner
You linearize the model at t=0.5 to avoid discontinuities in some derivatives at t=0. You
can set the operating point in Linearize At....
17-119
17 Control System Tuning Examples
17-120
Control of a Linear Electric Actuator Using Control System Tuner
In order to set the tuned blocks of the control system, open Select Blocks from
Tuning tab.
17-121
17 Control System Tuning Examples
This shows the editor for tuned blocks where you can Add Blocks.
17-122
Control of a Linear Electric Actuator Using Control System Tuner
Set the tuned blocks Current PID and Speed PID by navigating through the tree on
the left.
17-123
17 Control System Tuning Examples
17-124
Control of a Linear Electric Actuator Using Control System Tuner
Selected tuned blocks Current PID and Speed PID show in the editor for tuned blocks.
17-125
17 Control System Tuning Examples
They also appear in the Tuned Blocks section of Data Browser on the left side of
Control System Tuner.
17-126
Control of a Linear Electric Actuator Using Control System Tuner
Next specify the tracking goal that the DC motor should follow a 2000 rpm speed demand
in 0.1 seconds. See different types of goals under New Goal and select Reference
Tracking.
17-127
17 Control System Tuning Examples
17-128
Control of a Linear Electric Actuator Using Control System Tuner
Name the tracking goal as TR, specify the tracking goal from the reference input
rct_linact/Speed Demand(rpm)/1 to the reference-tracking output rct_linact/
Hall Effect Sensor/1[rpm] with the response time 0.1 seconds.
17-129
17 Control System Tuning Examples
17-130
Control of a Linear Electric Actuator Using Control System Tuner
The plot for specified tracking goal appears in Control System Tuner and Tuning Goals
section of Data Browser on the left side is updated.
You can now tune the proportional and integral gains with Control System Tuner from
clicking Tune button. The plot for tracking goal is updated
17-131
17 Control System Tuning Examples
Figure 16: Updated Tracking Goal Plot with Tuned Blocks in Control System
Tuner.
Tuned blocks are updated with the tuned gain values. To validate this design, plot the
closed-loop response from speed demand to speed from New Plot of Control System
Tab.
17-132
Control of a Linear Electric Actuator Using Control System Tuner
Specify the closed-loop response from speed demand to speed by the step plot dialog.
17-133
17 Control System Tuning Examples
You see the step plot of the response in Control System Tuner.
17-134
Control of a Linear Electric Actuator Using Control System Tuner
The response looks good in the linear domain so first store the current design by clicking
Store and push the tuned gain values to Simulink by clicking Update Blocks and
further validate the design in the nonlinear model.
17-135
17 Control System Tuning Examples
The nonlinear simulation results appear in Figure 21. The nonlinear behavior is far worse
than the linear approximation, a discrepancy that can be traced to saturations in the
inner loop (see Figure 22).
17-136
Control of a Linear Electric Actuator Using Control System Tuner
Preventing Saturations
So far we have only specified a desired response time for the outer (speed) loop. This
leaves systune free to allocate the control effort between the inner and outer loops.
17-137
17 Control System Tuning Examples
Saturations in the inner loop suggest that the proportional gain is too high and that some
rebalancing is needed. One possible remedy is to explicitly limit the gain from the speed
command to the outputs of the P and PI controllers. For a speed reference of 2000 rpm
and saturation limits of plus/minus 5, the average gain should not exceed 5/2000 =
0.0025. To be conservative, we can try to keep the gain from speed reference to controller
outputs below 0.001. To do this, add two gain requirements and retune the controller
gains with all three requirements in place.
Limit gain from speed demand to control signals to avoid saturation by specifying two
new goals from Tuning tab. You need to select control signals from Simulink model since
they are not defined previously.
17-138
Control of a Linear Electric Actuator Using Control System Tuner
Figure 23: Gain Goal Dialog from Speed Demand to Control Signal of Speed PID.
17-139
17 Control System Tuning Examples
17-140
Control of a Linear Electric Actuator Using Control System Tuner
Figure 24: Gain Goal Dialog from Speed Demand to Control Signal of Current
PID.
New gain goals appear in Tuning Goals section of Control System Tuner.
Retune with these additional requirements. Tuning Report accessed at the bottom right of
the tool shows the worst gain 1.39 indicating that the requirements are nearly but not
exactly met (all requirements are met when the final gain is less than 1).
17-141
17 Control System Tuning Examples
Next compare the two designs in the linear domain by clicking Compare in Control
System tab.
17-142
Control of a Linear Electric Actuator Using Control System Tuner
The second design is less aggressive but still meets the response time requirement.
17-143
17 Control System Tuning Examples
Finally, push the new tuned gain values to the Simulink model by Update Blocks and
simulate the response to a 2000 rpm speed demand and 500 N load disturbance. The
simulation results appear in Figure 29 and the current controller output is shown in
Figure 30.
17-144
Control of a Linear Electric Actuator Using Control System Tuner
17-145
17 Control System Tuning Examples
The nonlinear responses are now satisfactory and the current loop is no longer
saturating. The additional gain constraints have forced systune to re-distribute the
control effort between the inner and outer loops so as to avoid saturation.
See Also
Control System Tuner
Related Examples
• “Control of a Linear Electric Actuator” on page 17-105
17-146
PID Tuning for Setpoint Tracking vs. Disturbance Rejection
When tuning 1-DOF PID controllers, it is often impossible to achieve good tracking and
fast disturbance rejection at the same time. Assuming the control bandwidth is fixed,
faster disturbance rejection requires more gain inside the bandwidth, which can only be
achieved by increasing the slope near the crossover frequency. Because a larger slope
means a smaller phase margin, this typically comes at the expense of more overshoot in
the response to setpoint changes.
This example uses systune to explore this trade-off and find the right compromise for
your application. See also pidtool for a more direct way to make such trade-off (see
"Design Focus" under Controller Options).
17-147
17 Control System Tuning Examples
Tuning Setup
Consider the PID loop of Figure 2 with a load disturbance at the plant input.
The target control bandwidth is 10 rad/s. Create a tunable PID controller and fix its
derivative filter time constant to (10 times the bandwidth) so that there are
only three gains to tune (proportional, integral, and derivative gains).
G = zpk(-5,[-1 -2 -10],10);
C = tunablePID('C','pid');
C.Tf.Value = 0.01; C.Tf.Free = false; % fix Tf=0.01
The gain of the open-loop response is a key indicator of the feedback loop
behavior. The open-loop gain should be high (greater than one) inside the control
bandwidth to ensure good disturbance rejection, and should be low (less than one)
outside the control bandwidth to be insensitive to measurement noise and unmodeled
plant dynamics. Accordingly, use three requirements to express the control objectives:
17-148
PID Tuning for Setpoint Tracking vs. Disturbance Rejection
s = tf('s');
wc = 10; % target crossover frequency
% Tracking
R1 = TuningGoal.Tracking('r','y',2/wc);
% Disturbance rejection
R3 = TuningGoal.MinLoopGain('u',wc/s);
R3.Focus = [0 0.1];
Use systune to tune the PID gains to meet these requirements. Treat the bandwidth and
disturbance rejection goals as hard constraints and optimize tracking subject to these
constraints.
T1 = systune(T0,R1,[R2 R3]);
Verify that all three requirements are nearly met. The blue curves are the achieved values
and the yellow patches highlight regions where the requirements are violated.
figure('Position',[100,100,560,580])
viewGoal([R1 R2 R3],T1)
17-149
17 Control System Tuning Examples
17-150
PID Tuning for Setpoint Tracking vs. Disturbance Rejection
To gain insight into the trade-off between tracking and disturbance rejection, increase the
minimum loop gain in the frequency band [0,0.1] rad/s by a factor . Re-tune the PID
gains for the values .
Compare the responses to a step command r and to a step disturbance d entering at the
plant input u.
figure, step(T1,T2,T3,3)
title('Setpoint tracking')
legend('\alpha = 1','\alpha = 2','\alpha = 4')
17-151
17 Control System Tuning Examples
17-152
PID Tuning for Setpoint Tracking vs. Disturbance Rejection
Note how disturbance rejection improves as alpha increases, but at the expense of
increased overshoot in setpoint tracking. Plot the open-loop responses for the three
designs, and note how the slope before crossover (0dB) increases with alpha.
L1 = getLoopTransfer(T1,'u');
L2 = getLoopTransfer(T2,'u');
L3 = getLoopTransfer(T3,'u');
bodemag(L1,L2,L3,{1e-2,1e2}), grid
title('Open-loop response')
legend('\alpha = 1','\alpha = 2','\alpha = 4')
17-153
17 Control System Tuning Examples
Which design is most suitable depends on the primary purpose of the feedback loop you
are tuning.
17-154
PID Tuning for Setpoint Tracking vs. Disturbance Rejection
Use the tunablePID2 object to parameterize the 2-DOF PID controller and construct a
tunable model T0 of the closed-loop system in Figure 3.
C = tunablePID2('C','pid');
C.Tf.Value = 0.01; C.Tf.Free = false; % fix Tf=0.01
T0 = feedback(G*LS*C,1,2,1,+1);
T0 = T0(:,1);
T0.u = 'r'; T0.y = 'y';
Next tune the 2-DOF PI controller for the largest loop gain tried earlier ( ).
Compare the setpoint tracking and disturbance rejection properties of the 1-DOF and 2-
DOF designs for .
clf, step(T3,'b',T4,'g--',4)
title('Setpoint tracking')
legend('1-DOF','2-DOF')
17-155
17 Control System Tuning Examples
D4 = getIOTransfer(T4,'u','y');
step(D3,'b',D4,'g--',4)
title('Disturbance rejection')
legend('1-DOF','2-DOF')
17-156
PID Tuning for Setpoint Tracking vs. Disturbance Rejection
The responses to a step disturbance are similar but the 2-DOF controller eliminates the
overshoot in the response to a setpoint change. You can use showTunable to compare
the tuned gains in the 1-DOF and 2-DOF controllers.
showTunable(T3) % 1-DOF PI
C =
1 s
Kp + Ki * --- + Kd * --------
s Tf*s+1
17-157
17 Control System Tuning Examples
Name: C
Continuous-time PIDF controller in parallel form.
showTunable(T4) % 2-DOF PI
C =
1 s
u = Kp (b*r-y) + Ki --- (r-y) + Kd -------- (c*r-y)
s Tf*s+1
Name: C
Continuous-time 2-DOF PIDF controller in parallel form.
See Also
TuningGoal.MaxLoopGain | TuningGoal.MinLoopGain | TuningGoal.Tracking |
systune
Related Examples
• “Active Vibration Control in Three-Story Building” on page 17-159
17-158
Active Vibration Control in Three-Story Building
Background
This example considers an Active Mass Driver (AMD) control system for vibration
isolation in a three-story experimental structure. This setup is used to assess control
design techniques for increasing safety of civil engineering structures during
earthquakes. The structure consists of three stories with an active mass driver on the top
floor which is used to attenuate ground disturbances. This application is borrowed from
"Benchmark Problems in Structural Control: Part I - Active Mass Driver System," B.F.
Spencer Jr., S.J. Dyke, and H.S. Deoskar, Earthquake Engineering and Structural
Dynamics, 27(11), 1998, pp. 1127-1139.
17-159
17 Control System Tuning Examples
The inputs are the ground acceleration xag (in g) and the control signal u. We use 1 g =
981 cm/s^2.
load ThreeStoryData
size(P)
The earthquake acceleration is modeled as a white noise process filtered through a Kanai-
Tajimi filter.
zg = 0.3;
wg = 37.3;
S0 = 0.03*zg/(pi*wg*(4*zg^2+1));
Numerator = sqrt(S0)*[2*zg*wg wg^2];
Denominator = [1 2*zg*wg wg^2];
F = sqrt(2*pi)*tf(Numerator,Denominator);
F.InputName = 'n'; % white noise input
bodemag(F)
grid
title('Kanai-Tajimi filter')
17-160
Active Vibration Control in Three-Story Building
Open-Loop Characteristics
17-161
17 Control System Tuning Examples
CV = covar(PF('xa','n'),1);
xa0 = sqrt(diag(CV));
17-162
Active Vibration Control in Three-Story Building
The controller uses measurements yxa and yxam of xa and xam to generate the
control signal u. Physically, the control u is an electrical current driving an hydraulic
actuator that moves the masses of the AMD. The design requirements involve:
17-163
17 Control System Tuning Examples
TuningGoal.Variance('n','xa(3)',xa0(3))];
Controller Tuning
systune lets you tune virtually any controller structure subject to these requirements.
The controller complexity can be adjusted by trial-and-error, starting with sufficiently
high order to gauge the limits of performance, then reducing the order until you observe
a noticeable performance degradation. For this example, start with a 5th-order controller
with no feedthrough term.
C = tunableSS('C',5,1,4);
C.D.Value = 0;
C.D.Free = false; % Fix feedthrough to zero
Construct a tunable model T0 of the closed-loop system of Figure 2 and tune the
controller parameters with systune.
Validation
Compute the standard deviations of the drifts and accelerations for the controlled
structure and compare with the uncontrolled results. The AMD control system yields
significant reduction of both drift and acceleration.
17-164
Active Vibration Control in Three-Story Building
17-165
17 Control System Tuning Examples
% Open-loop simulation
ysimOL = lsim(PF(:,1), n , t);
% Closed-loop simulation
ysimCL = lsim(T, n , t);
% Drifts
clf
subplot(3,1,1)
plot(t,ysimOL(:,13),'b',t,ysimCL(:,13),'r')
grid
title('Inter-story drift d(1) (blue=open loop, red=closed loop)')
ylabel('cm')
subplot(3,1,2)
plot(t,ysimOL(:,14),'b',t,ysimCL(:,14),'r')
grid
title('Inter-story drift d(2)')
ylabel('cm')
subplot(3,1,3)
plot(t,ysimOL(:,15),'b',t,ysimCL(:,15),'r')
grid
title('Inter-story drift d(3)')
ylabel('cm')
17-166
Active Vibration Control in Three-Story Building
Accelerations
clf
subplot(3,1,1)
plot(t,ysimOL(:,9),'b',t,ysimCL(:,9),'r')
grid
title('Acceleration of 1st floor xa(1) (blue=open loop, red=closed loop)')
ylabel('g')
subplot(3,1,2)
plot(t,ysimOL(:,10),'b',t,ysimCL(:,10),'r')
grid
title('Acceleration of 2nd floor xa(2)')
ylabel('g')
subplot(3,1,3)
17-167
17 Control System Tuning Examples
plot(t,ysimOL(:,11),'b',t,ysimCL(:,11),'r')
grid
title('Acceleration of 3rd floor xa(3)')
ylabel('g')
Control variables
clf
subplot(3,1,1)
plot(t,ysimCL(:,4),'r')
grid
title('AMD position xm')
ylabel('cm')
subplot(3,1,2)
17-168
Active Vibration Control in Three-Story Building
plot(t,ysimCL(:,12),'r')
grid
title('AMD acceleration xam')
ylabel('g')
subplot(3,1,3)
plot(t,ysimCL(:,16),'r')
grid
title('Control signal u')
Plot the root-mean-square (RMS) of the simulated signals for both the controlled and
uncontrolled scenarios. Assuming ergodicity, the RMS performance can be estimated
from a single sufficiently long simulation of the process and coincides with the standard
deviations computed earlier. Indeed the RMS plot closely matches the standard deviation
plot obtained earlier.
17-169
17 Control System Tuning Examples
clf
bar([std(ysimOL(:,13:15)) std(ysimOL(:,9:11)) ; ...
std(ysimCL(:,13:15)) std(ysimCL(:,9:11))]')
title('Drifts and accelerations')
ylabel('Simulated RMS values')
set(gca,'XTickLabel',{'d(1)','d(2)','d(3)','xa(1)','xa(2)','xa(3)'})
legend('Uncontrolled','Controlled','location','NorthWest')
17-170
See Also
Overall, the controller achieves significant reduction of ground vibration both in terms of
drift and acceleration for all stories while meeting the hard constraints on control effort
and mass displacement.
See Also
TuningGoal.Variance | isPassive | systune
Related Examples
• “Vibration Control in Flexible Beam” on page 17-269
17-171
17 Control System Tuning Examples
We use Simulink to model the voltage controller in the power stage for an electronic
device:
open_system('rct_powerstage')
The power stage amplifier is modeled as a second-order linear system with the following
frequency response:
bode(psmodel)
grid
17-172
Digital Control of Power Stage Voltage
The controller must regulate the voltage Vchip delivered to the device to track the
setpoint Vcmd and be insensitive to variations in load current iLoad. The control
structure consists of a feedback compensator and a disturbance feedforward
compensator. The voltage Vin going into the amplifier is limited to . The
controller sampling rate is 10 MHz (sample time Tm is 1e-7 seconds).
Performance Requirements
This application is challenging because the controller bandwidth must approach the
Nyquist frequency pi/Tm = 31.4 MHz. To avoid aliasing troubles when discretizing
continuous-time controllers, it is preferable to tune the controller directly in discrete
time.
17-173
17 Control System Tuning Examples
The power stage should respond to a setpoint change in desired voltage Vcmd in about 5
sampling periods with a peak error (across frequency) of 50%. Use a tracking
requirement to capture this objective.
Req1 = TuningGoal.Tracking('Vcmd','Vchip',5*Tm,0,1.5);
Req1.Name = 'Setpoint change';
viewGoal(Req1)
The power stage should also quickly reject load disturbances iLoad. Express this
requirement in terms of gain from iLoad to Vchip. This gain should be low at low
frequency for good disturbance rejection.
17-174
Digital Control of Power Stage Voltage
s = tf('s');
nf = pi/Tm; % Nyquist frequency
High-performance demands may lead to high control effort and saturation. For the ramp
profile vcmd specified in the Simulink model (from 0 to 1 in about 250 sampling periods),
we want to avoid hitting the saturation constraint . Use a rate-limiting filter to
model the ramp command, and require that the gain from the rate-limiter input to be
less than .
RateLimiter = 1/(250*Tm*s); % models ramp command in Simulink
To ensure adequate robustness, require at least 7 dB gain margin and 45 degrees phase
margin at the plant input.
Req4 = TuningGoal.Margins('Vin',7,45);
Req4.Name = 'Margins';
Finally, the feedback compensator has a tendency to cancel the plant resonance by
notching it out. Such plant inversion may lead to poor results when the resonant
frequency is not exactly known or subject to variations. To prevent this, impose a
minimum closed-loop damping of 0.5 to actively damp of the plant's resonant mode.
Req5 = TuningGoal.Poles(0,0.5,3*nf);
Req5.Name = 'Damping';
Tuning
Next use systune to tune the controller parameters subject to the requirements defined
above. First use the slTuner interface to configure the Simulink model for tuning. In
particular, specify that there are two tunable blocks and that the model should be
linearized and tuned at the sample time Tm.
TunedBlocks = {'compensator','FIR'};
ST0 = slTuner('rct_powerstage',TunedBlocks);
ST0.Ts = Tm;
17-175
17 Control System Tuning Examples
FIR = tunableTF('FIR',1,1,Tm);
% Fix denominator to z^n
FIR.Denominator.Value = [1 0];
FIR.Denominator.Free = false;
setBlockParam(ST0,'FIR',FIR);
rng(0)
topt = systuneOptions('RandomStart',6);
ST = systune(ST0,[Req1 Req2 Req3],[Req4 Req5],topt);
The best design satisfies the hard constraints (Hard less than 1) and nearly satisfies the
other constraints (Soft close to 1). Verify this graphically by plotting the tuned responses
for each requirement.
figure('Position',[10,10,1071,714])
viewGoal([Req1 Req2 Req3 Req4 Req5],ST)
17-176
Digital Control of Power Stage Voltage
Validation
First validate the design in the linear domain using the slTuner interface. Plot the
closed-loop response to a step command Vcmd and a step disturbance iLoad.
figure('Position',[100,100,560,500])
subplot(2,1,1)
step(getIOTransfer(ST,'Vcmd','Vchip'),20*Tm)
title('Response to step command in voltage')
subplot(2,1,2)
step(getIOTransfer(ST,'iLoad','Vchip'),20*Tm)
title('Rejection of step disturbance in load current')
17-177
17 Control System Tuning Examples
Use getLoopTransfer to compute the open-loop response at the plant input and
superimpose the plant and feedback compensator responses.
clf
L = getLoopTransfer(ST,'Vin',-1);
C = getBlockValue(ST,'compensator');
bodeplot(L,psmodel(2),C(2),{1e-3/Tm pi/Tm})
17-178
Digital Control of Power Stage Voltage
grid
legend('Open-loop response','Plant','Compensator')
The controller achieves the desired bandwidth and the responses are fast enough. Apply
the tuned parameter values to the Simulink model and simulate the tuned responses.
writeBlockValue(ST)
17-179
17 Control System Tuning Examples
The results from the nonlinear simulation appear below. Note that the control signal Vin
remains approximately within saturation bounds for the setpoint tracking portion
of the simulation.
17-180
See Also
See Also
TuningGoal.Gain | TuningGoal.Margins | TuningGoal.Tracking | slTuner |
systune (slTuner)
17-181
17 Control System Tuning Examples
Related Examples
• “MIMO Control of Diesel Engine” on page 17-183
17-182
MIMO Control of Diesel Engine
Modern Diesel engines use a variable geometry turbocharger (VGT) and exhaust gas
recirculation (EGR) to reduce emissions. Tight control of the VGT boost pressure and EGR
massflow is necessary to meet strict emission targets. This example shows how to design
and tune a MIMO controller that regulates these two variables when the engine operates
at 2100 rpm with a fuel mass of 12 mg per injection-cylinder.
open_system('rct_diesel')
The VGT/EGR control system is modeled in Simulink. The controller adjusts the positions
EGRLIFT and VGTPOS of the EGR and VGT valves. It has access to the boost pressure and
EGR massflow targets and measured values, as well as fuel mass and engine speed
measurements. Both valves have rate and saturation limits. The plant model is sampled
every 0.1 seconds and the control signals EGRLIFT and VGTPOS are refreshed every 0.2
seconds. This example considers step changes of +10 KPa in boost pressure and +3 g/s in
EGR massflow, and disturbances of +5 mg in fuel mass and -200 rpm in speed.
17-183
17 Control System Tuning Examples
For the operating condition under consideration, we used System Identification to derive
a linear model of the engine from experimental data. The frequency response from the
manipulated variables EGRLIFT and VGTPOS to the controlled variables BOOST and EGR
MF appears below. Note that the plant is ill conditioned at low frequency which makes
independent control of boost pressure and EGR massflow difficult.
sigma(Plant(:,1:2)), grid
title('Frequency response of the linearized engine dynamics')
Control Objectives
17-184
MIMO Control of Diesel Engine
1 Respond to step changes in boost pressure and EGR massflow in about 5 seconds
with minimum cross-coupling
2 Be insensitive to (small) variations in speed and fuel mass.
Use a tracking requirement for the first objective. Specify the amplitudes of the step
changes to ensure that cross-couplings are small relative to these changes.
For the second objective, treat the speed and fuel mass variations as step disturbances
and specify the peak amplitude and settling time of the resulting variations in boost
pressure and EGR massflow. Also specify the signal amplitudes to properly reflect the
relative contribution of each disturbance.
To provide adequate robustness to unmodeled dynamics and aliasing, limit the control
bandwidth and impose sufficient stability margins at both the plant inputs and outputs.
Because we are dealing with a 2-by-2 MIMO feedback loops, these stability margins are
interpreted as disk margins (see loopmargin and TuningGoal.Margins for details).
Without a-priori knowledge of a suitable control structure, first try "blackbox" state-space
controllers of various orders. The plant model has four states, so try a controller of order
17-185
17 Control System Tuning Examples
four or less. Here we tune a second-order controller since the "SS2" block in the Simulink
model has two states.
Use the slTuner interface to configure the Simulink model for tuning. Mark the block
"SS2" as tunable, register the locations where to assess margins and loop shapes, and
specify that linearization and tuning should be performed at the controller sampling rate.
ST0 = slTuner('rct_diesel','SS2');
ST0.Ts = 0.2;
addPoint(ST0,{'EGRLIFT','VGTPOS','DIESEL ENGINE'})
Now use systune to tune the state-space controller subject to our control objectives.
Treat the stability margins and roll-off target as hard constraints and try to best meet the
remaining objectives (soft goals). Randomize the starting point to reduce exposure to
undesirable local minima.
Opt = systuneOptions('RandomStart',2);
rng(0), ST1 = systune(ST0,[TR DR],[M1 M2 RO],Opt);
17-186
MIMO Control of Diesel Engine
All requirements are nearly met (a requirement is satisfied when its normalized value is
less than 1). Verify this graphically.
figure('Position',[10,10,1071,714])
viewGoal([TR DR RO M1 M2],ST1)
Plot the setpoint tracking and disturbance rejection responses. Scale by the signal
amplitudes to show normalized effects (boost pressure changes by +10 KPa, EGR
massflow by +3 g/s, fuel mass by +5 mg, and speed by -200 rpm).
figure('Position',[100,100,560,500])
T1 = getIOTransfer(ST1,{'BOOST REF';'EGRMF REF'},{'BOOST','EGRMF','EGRLIFT','VGTPOS'});
T1 = diag([1/10 1/3 1 1]) * T1 * diag([10 3]);
subplot(211), step(T1(1:2,:),15), title('Setpoint tracking')
subplot(212), step(T1(3:4,:),15), title('Control effort')
17-187
17 Control System Tuning Examples
D1 = getIOTransfer(ST1,{'FUELMASS';'SPEED'},{'BOOST','EGRMF','EGRLIFT','VGTPOS'});
D1 = diag([1/10 1/3 1 1]) * D1 * diag([5 -200]);
subplot(211), step(D1(1:2,:),15), title('Disturbance rejection')
subplot(212), step(D1(3:4,:),15), title('Control effort')
17-188
MIMO Control of Diesel Engine
The controller responds in less than 5 seconds with minimum cross-coupling between the
BOOST and EGRMF variables.
The state-space controller could be implemented as is, but it is often desirable to boil it
down to a simpler, more familiar structure. To do this, get the tuned controller and
inspect its frequency response
17-189
17 Control System Tuning Examples
C = getBlockValue(ST1,'SS2');
clf
bode(C(:,1:2),C(:,3:4),{.02 20}), grid
legend('REF to U','Y to U')
bodemag(C(:,5:6)), grid
title('Bode response from FUELMASS/SPEED to EGRLIFT/VGTPOS')
17-190
MIMO Control of Diesel Engine
The first plot suggests that the controller essentially behaves like a PI controller acting on
REF-Y (the difference between the target and actual values of the controlled variables).
The second plot suggests that the transfer from measured disturbance to manipulated
variables could be replaced by a gain in series with a lag network. Altogether this
suggests the following simplified control structure consisting of a MIMO PI controller
with a first-order disturbance feedforward.
17-191
17 Control System Tuning Examples
Using variant subsystems, you can implement both control structures in the same
Simulink model and use a variable to switch between them. Here setting MODE=2 selects
the MIMO PI structure. As before, use systune to tune the three 2-by-2 gain matrices
Kp, Ki, Kff in the simplified control structure.
17-192
MIMO Control of Diesel Engine
Again all requirements are nearly met. Plot the closed-loop responses and compare with
the state-space design.
clf
T2 = getIOTransfer(ST2,{'BOOST REF';'EGRMF REF'},{'BOOST','EGRMF','EGRLIFT','VGTPOS'});
T2 = diag([1/10 1/3 1 1]) * T2 * diag([10 3]);
subplot(211), step(T1(1:2,:),T2(1:2,:),15), title('Setpoint tracking')
legend('SS2','PI+FF')
subplot(212), step(T1(3:4,:),T2(3:4,:),15), title('Control effort')
17-193
17 Control System Tuning Examples
D2 = getIOTransfer(ST2,{'FUELMASS';'SPEED'},{'BOOST','EGRMF','EGRLIFT','VGTPOS'});
D2 = diag([1/10 1/3 1 1]) * D2 * diag([5 -200]);
subplot(211), step(D1(1:2,:),D2(1:2,:),15), title('Disturbance rejection')
legend('SS2','PI+FF')
subplot(212), step(D1(3:4,:),D2(3:4,:),15), title('Control effort')
17-194
MIMO Control of Diesel Engine
The blackbox and simplified control structures deliver similar performance. Inspect the
tuned values of the PI and feedforward gains.
showTunable(ST2)
D =
17-195
17 Control System Tuning Examples
u1 u2
y1 -0.007975 -0.0008055
y2 -0.02041 0.01453
Name: Kp
Static gain.
-----------------------------------
D =
u1 u2
y1 -0.01055 -0.01428
y2 -0.03006 0.04675
Name: Ki
Static gain.
-----------------------------------
D =
u1 u2
y1 0.01406 -9.773e-05
y2 0.03206 -0.001455
Name: Kff
Static gain.
Nonlinear Validation
To validate the MIMO PI controller in the Simulink model, push the tuned controller
parameters to Simulink and run the simulation.
writeBlockValue(ST2)
The simulation results are shown below and confirm that the controller adequately tracks
setpoint changes in boost pressure and EGR massflow and quickly rejects changes in fuel
mass (at t=90) and in speed (at t=110).
17-196
See Also
See Also
TuningGoal.Margins | TuningGoal.MaxLoopGain | TuningGoal.StepRejection |
TuningGoal.Tracking | slTuner | systune (slTuner)
Related Examples
• “Digital Control of Power Stage Voltage” on page 17-172
17-197
17 Control System Tuning Examples
open_system('rct_airframe1')
The autopilot consists of two cascaded loops. The inner loop controls the pitch rate q, and
the outer loop controls the vertical acceleration az in response to the pilot stick command
azref. In this architecture, the tunable elements include the PI controller gains ("az
Control" block) and the pitch-rate gain ("q Gain" block). The autopilot must be tuned to
respond to a step command azref in about 1 second with minimal overshoot. In this
example, we tune the autopilot gains for one flight condition corresponding to zero
incidence and a speed of 984 m/s.
17-198
Tuning of a Two-Loop Autopilot
To analyze the airframe dynamics, trim the airframe for and . The trim
condition corresponds to zero normal acceleration and pitching moment ( and steady).
Use findop to compute the corresponding closed-loop operating condition. Note that we
added a "delta trim" input port so that findop can adjust the fin deflection to produce the
desired equilibrium of forces and moments.
opspec = operspec('rct_airframe1');
op = findop('rct_airframe1',opspec);
17-199
17 Control System Tuning Examples
Inputs:
----------
(1.) rct_airframe1/delta trim
u: 0.000708 [-Inf Inf]
Outputs: None
----------
Linearize the "Airframe Model" block for the computed trim condition op and plot the
gains from the fin deflection delta to az and q:
G = linearize('rct_airframe1','rct_airframe1/Airframe Model',op);
G.InputName = 'delta';
G.OutputName = {'az','q'};
bodemag(G), grid
17-200
Tuning of a Two-Loop Autopilot
pole(G)
ans =
-0.0320
-0.0255
0.1253
-29.4685
17-201
17 Control System Tuning Examples
You can use the looptune function to automatically tune multi-loop control systems
subject to basic requirements such as integral action, adequate stability margins, and
desired bandwidth. To apply looptune to the autopilot model, create an instance of the
slTuner interface and designate the Simulink blocks "az Control" and "q Gain" as
tunable. Also specify the trim condition op to correctly linearize the airframe dynamics.
Mark the reference, control, and measurement signals as points of interest for analysis
and tuning.
Finally, tune the control system parameters to meet the 1 second response time
requirement. In the frequency domain, this roughly corresponds to a gain crossover
frequency wc = 5 rad/s for the open-loop response at the plant input "delta fin".
wc = 5;
Controls = 'delta fin';
Measurements = {'az','q'};
[ST,gam,Info] = looptune(ST0,Controls,Measurements,wc);
The requirements are normalized so a final value near 1 means that all requirements are
met. Confirm this by graphically validating the design.
figure('Position',[100,100,560,714])
loopview(ST,Info)
17-202
Tuning of a Two-Loop Autopilot
17-203
17 Control System Tuning Examples
The first plot confirms that the open-loop response has integral action and the desired
gain crossover frequency while the second plot shows that the MIMO stability margins
are satisfactory (the blue curve should remain below the yellow bound). Next check the
response from the step command azref to the vertical acceleration az:
T = getIOTransfer(ST,'az ref','az');
figure
step(T,5)
The acceleration az does not track azref despite the presence of an integrator in the
loop. This is because the feedback loop acts on the two variables az and q and we have
not specified which one should track azref.
17-204
Tuning of a Two-Loop Autopilot
To remedy this issue, add an explicit requirement that az should follow the step command
azref with a 1 second response time. Also relax the gain crossover requirement to the
interval [3,12] to let the tuner find the appropriate gain crossover frequency.
17-205
17 Control System Tuning Examples
Also check the disturbance rejection characteristics by looking at the responses from a
disturbance entering at the plant input
17-206
Tuning of a Two-Loop Autopilot
step(Td1,5)
grid
title('Disturbance rejection')
17-207
17 Control System Tuning Examples
Use showBlockValue to see the tuned values of the PI controller and inner-loop gain
showBlockValue(ST)
AnalysisPoints_ =
D =
u1 u2 u3 u4
y1 1 0 0 0
y2 0 1 0 0
y3 0 0 1 0
y4 0 0 0 1
Name: AnalysisPoints_
17-208
Tuning of a Two-Loop Autopilot
Static gain.
-----------------------------------
az_Control =
1
Kp + Ki * ---
s
Name: az_Control
Continuous-time PI controller in parallel form.
-----------------------------------
q_Gain =
D =
u1
y1 1.985
Name: q_Gain
Static gain.
If this design is satisfactory, use writeBlockValue to apply the tuned values to the
Simulink model and simulate the tuned controller in Simulink.
writeBlockValue(ST)
Cascaded loops are commonly used for autopilots. Yet one may wonder how a single
MIMO controller that uses both az and q to generate the actuator command delta fin
would compare with the two-loop architecture. Trying new control architectures is easy
with systune or looptune. For variety, we now use systune to tune the following
MIMO architecture.
open_system('rct_airframe2')
17-209
17 Control System Tuning Examples
opspec = operspec('rct_airframe2');
op = findop('rct_airframe2',opspec);
17-210
Tuning of a Two-Loop Autopilot
Inputs:
----------
(1.) rct_airframe2/delta trim
u: 0.000436 [-Inf Inf]
Outputs: None
----------
As with looptune, use the slTuner interface to configure the Simulink model for tuning.
Note that the signals of interest are already marked as Linear Analysis points in the
Simulink model.
ST0 = slTuner('rct_airframe2','MIMO Controller',op);
Try a second-order MIMO controller with zero feedthrough from e to delta fin. To do
this, create the desired controller parameterization and associate it with the "MIMO
Controller" block using setBlockParam:
C0 = tunableSS('C',2,1,2); % Second-order controller
C0.D.Value(1) = 0; % Fix D(1) to zero
17-211
17 Control System Tuning Examples
C0.D.Free(1) = false;
setBlockParam(ST0,'MIMO Controller',C0)
Next create the tuning requirements. Here we use the following four requirements:
% Tracking
Req1 = TuningGoal.Tracking('az ref','az',1);
% Margins
Req3 = TuningGoal.Margins('delta fin',7,45);
% Disturbance rejection
% Use an FRD model to sketch the desired attenuation profile with a few points
Freqs = [0 0.001 1];
MinAtt = [100 100 40]; % in dB
Req4 = TuningGoal.Rejection('delta fin',frd(db2mag(MinAtt),Freqs));
Req4.Focus = [0 1];
You can now use systune to tune the controller parameters subject to these
requirements.
rng(0)
[ST,fSoft] = systune(ST0,AllReqs,Opt);
17-212
Tuning of a Two-Loop Autopilot
The best design has an overall objective value close to 1, indicating that all four
requirements are nearly met. Use viewGoal to inspect each requirement for the best
design.
figure('Position',[100,100,987,474])
viewGoal(AllReqs,ST)
Compute the closed-loop responses and compare with the two-loop design.
figure
step(Tr1,'b',T(1),'r',5)
title('Tracking')
legend('Cascade','2 dof')
17-213
17 Control System Tuning Examples
step(Td1,'b',T(2),'r',5)
title('Disturbance rejection')
legend('Cascade','2 dof')
17-214
See Also
The tracking performance is similar but the second design has better disturbance
rejection properties.
See Also
looptune (slTuner) | slTuner
Related Examples
• “PID Tuning for Setpoint Tracking vs. Disturbance Rejection” on page 17-147
• “Decoupling Controller for a Distillation Column” on page 17-331
17-215
17 Control System Tuning Examples
Helicopter Model
This example uses an 8-state helicopter model at the hovering trim condition. The state
vector x = [u,w,q,theta,v,p,phi,r] consists of
The controller generates commands ds,dc,dT in degrees for the longitudinal cyclic,
lateral cyclic, and tail rotor collective using measurements of theta, phi, p, q, and r.
Control Architecture
open_system('rct_helico')
17-216
Multiloop Control of a Helicopter
The control system consists of two feedback loops. The inner loop (static output feedback)
provides stability augmentation and decoupling. The outer loop (PI controllers) provides
the desired setpoint tracking performance. The main control objectives are as follows:
• Track setpoint changes in theta, phi, and r with zero steady-state error, rise times of
about 2 seconds, minimal overshoot, and minimal cross-coupling
• Limit the control bandwidth to guard against neglected high-frequency rotor dynamics
and measurement noise
• Provide strong multivariable gain and phase margins (robustness to simultaneous
gain/phase variations at the plant inputs and outputs, see loopmargin for details).
We use lowpass filters with cutoff at 40 rad/s to partially enforce the second objective.
Controller Tuning
You can jointly tune the inner and outer loops with the systune command. This command
only requires models of the plant and controller along with the desired bandwidth (which
is function of the desired response time). When the control system is modeled in Simulink,
you can use the slTuner interface to quickly set up the tuning task. Create an instance
of this interface with the list of blocks to be tuned.
ST0 = slTuner('rct_helico',{'PI1','PI2','PI3','SOF'});
17-217
17 Control System Tuning Examples
Each tunable block is automatically parameterized according to its type and initialized
with its value in the Simulink model ( for the PI controllers and zero for the static
output-feedback gain). Simulating the model shows that the control system is unstable for
these initial values:
Mark the I/O signals of interest for setpoint tracking, and identify the plant inputs and
outputs (control and measurement signals) where the stability margin are measured.
17-218
Multiloop Control of a Helicopter
Finally, capture the design requirements using TuningGoal objects. We use the following
requirements for this example:
You can now use systune to jointly tune all controller parameters. This returns the tuned
version ST1 of the control system ST0.
AllReqs = [TrackReq,MarginReq1,MarginReq2,PoleReq];
ST1 = systune(ST0,AllReqs);
The final value is close to 1 so the requirements are nearly met. Plot the tuned responses
to step commands in theta, phi, r:
T1 = getIOTransfer(ST1,{'theta-ref','phi-ref','r-ref'},{'theta','phi','r'});
step(T1,5)
17-219
17 Control System Tuning Examples
The rise time is about two seconds with no overshoot and little cross-coupling. You can
use viewGoal for a more thorough validation of each requirement, including a visual
assessment of the multivariable stability margins (see loopmargin for details):
figure('Position',[100,100,900,474])
viewGoal(AllReqs,ST1)
17-220
Multiloop Control of a Helicopter
Inspect the tuned values of the PI controllers and static output-feedback gain.
showTunable(ST1)
Block 1: rct_helico/PI1 =
1
Kp + Ki * ---
s
Name: PI1
Continuous-time PI controller in parallel form.
-----------------------------------
Block 2: rct_helico/PI2 =
17-221
17 Control System Tuning Examples
Kp + Ki * ---
s
Name: PI2
Continuous-time PI controller in parallel form.
-----------------------------------
Block 3: rct_helico/PI3 =
1
Kp + Ki * ---
s
Name: PI3
Continuous-time PI controller in parallel form.
-----------------------------------
Block 4: rct_helico/SOF =
D =
u1 u2 u3 u4 u5
y1 2.352 -0.3525 -0.001746 0.8092 -0.02051
y2 -0.1574 -1.157 0.03837 -0.05233 -0.1059
y3 -0.02594 -0.004309 -1.998 -0.05038 0.0429
Name: SOF
Static gain.
You may wonder whether the static output feedback is necessary and whether PID
controllers aren't enough to control the helicopter. This question is easily answered by re-
tuning the controller with the inner loop open. First break the inner loop by adding a loop
opening after the SOF block:
addOpening(ST0,'SOF')
17-222
Multiloop Control of a Helicopter
Then remove the SOF block from the tunable block list and re-parameterize the PI blocks
as full-blown PIDs with the correct loop signs (as inferred from the first design).
removeBlock(ST0,'SOF');
setBlockParam(ST0,...
'PI1',tunablePID('C1',PID),...
'PI2',tunablePID('C2',-PID),...
'PI3',tunablePID('C3',-PID));
Re-tune the three PID controllers and plot the closed-loop step responses.
ST2 = systune(ST0,AllReqs);
T2 = getIOTransfer(ST2,{'theta-ref','phi-ref','r-ref'},{'theta','phi','r'});
figure, step(T2,5)
17-223
17 Control System Tuning Examples
The final value is no longer close to 1 and the step responses confirm the poorer
performance with regard to rise time, overshoot, and decoupling. This suggests that the
inner loop has an important stabilizing effect that should be preserved.
See Also
TuningGoal.Margins | TuningGoal.Poles | TuningGoal.StepTracking | slTuner
| systune (slTuner)
Related Examples
• “Fixed-Structure Autopilot for a Passenger Jet” on page 17-225
17-224
Fixed-Structure Autopilot for a Passenger Jet
The longitudinal autopilot for a supersonic passenger jet flying at Mach 0.7 and 5000 ft is
depicted in Figure 1. The autopilot main purpose is to follow vertical acceleration
commands issued by the pilot. The feedback structure consists of an inner loop
controlling the pitch rate and an outer loop controlling the vertical acceleration . The
autopilot also includes a feedforward component and a reference model that
specifies the desired response to a step command . Finally, the second-order roll-off
filter
is used to attenuate noise and limit the control bandwidth as a safeguard against
unmodeled dynamics. The tunable components are highlighted in orange.
17-225
17 Control System Tuning Examples
The aircraft model is a 5-state model, the state variables being the aerodynamic
speed (m/s), the climb angle (rad), the angle of attack (rad), the pitch rate (rad/s),
and the altitude (m). The elevator deflection (rad) is used to control the vertical load
factor . The open-loop dynamics include the oscillation with frequency and damping
ratio = 1.7 (rad/s) and = 0.33, the phugoid mode = 0.64 (rad/s) and = 0.06, and
the slow altitude mode = -0.0026.
load ConcordeData G
bode(G,{1e-3,1e2}), grid
title('Aircraft Model')
17-226
Fixed-Structure Autopilot for a Passenger Jet
Note the zero at the origin in . Because of this zero, we cannot achieve zero steady-
state error and must instead focus on the transient response to acceleration commands.
Note that acceleration commands are transient in nature so steady-state behavior is not a
concern. This zero at the origin also precludes pure integral action so we use a pseudo-
integrator with = 0.001.
Tuning Setup
When the control system is modeled in Simulink, you can use the slTuner interface to
quickly set up the tuning task. Open the Simulink model of the autopilot.
open_system('rct_concorde')
17-227
17 Control System Tuning Examples
Configure the slTuner interface by listing the tuned blocks in the Simulink model
(highlighted in orange). This automatically picks all Linear Analysis points in the model as
points of interest for analysis and tuning.
ST0 = slTuner('rct_concorde',{'Ki','Kp','Kq','Kf','RollOff'});
This also parameterizes each tuned block and initializes the block parameters based on
their values in the Simulink model. Note that the four gains Ki,Kp,Kq,Kf are initialized
to zero in this example. By default the roll-off filter is parameterized as a generic
second-order transfer function. To parameterize it as
create real parameters , build the transfer function shown above, and associate it
with the RollOff block.
17-228
Fixed-Structure Autopilot for a Passenger Jet
Design Requirements
1. Setpoint tracking: The response to the command should closely match the
response of the reference model:
This reference model specifies a well-damped response with a 2 second settling time.
2. High-frequency roll-off: The closed-loop response from the noise signals to should
roll off past 8 rad/s with a slope of at least -40 dB/decade.
3. Stability margins: The stability margins at the plant input should be at least 7 dB
and 45 degrees.
For setpoint tracking, we require that the gain of the closed-loop transfer from the
command to the tracking error be small in the frequency band [0.05,5] rad/s (recall
that we cannot drive the steady-state error to zero because of the plant zero at s=0).
Using a few frequency points, sketch the maximum tracking error as a function of
frequency and use it to limit the gain from to .
The TuningGoal.Gain constructor automatically turns the maximum error sketch into a
smooth weighting function. Use viewGoal to graphically verify the desired error profile.
viewGoal(Req1)
17-229
17 Control System Tuning Examples
Repeat the same process to limit the high-frequency gain from the noise inputs to and
enforce a -40 dB/decade slope in the frequency band from 8 to 800 rad/s
viewGoal(Req2)
17-230
Fixed-Structure Autopilot for a Passenger Jet
Finally, register the plant input as a site for open-loop analysis and use
TuningGoal.Margins to capture the stability margin requirement.
addPoint(ST0,'delta_m')
Req3 = TuningGoal.Margins('delta_m',7,45);
Autopilot Tuning
We are now ready to tune the autopilot parameters with systune. This command takes
the untuned configuration ST0 and the three design requirements and returns the tuned
version ST of ST0. All requirements are satisfied when the final value is less than one.
[ST,fSoft] = systune(ST0,[Req1 Req2 Req3]);
17-231
17 Control System Tuning Examples
showTunable(ST)
Block 1: rct_concorde/Ki =
D =
u1
y1 -0.02981
Name: Ki
Static gain.
-----------------------------------
Block 2: rct_concorde/Kp =
D =
u1
y1 -0.009814
Name: Kp
Static gain.
-----------------------------------
Block 3: rct_concorde/Kq =
D =
u1
y1 -0.2855
Name: Kq
Static gain.
-----------------------------------
Block 4: rct_concorde/Kf =
D =
u1
y1 -0.02248
17-232
Fixed-Structure Autopilot for a Passenger Jet
Name: Kf
Static gain.
-----------------------------------
wn = 4.81
-----------------------------------
zeta = 0.512
To get the tuned value of , use getBlockValue to evaluate Fro for the tuned
parameter values in ST:
Fro = getBlockValue(ST,'RollOff');
tf(Fro)
ans =
23.13
---------------------
s^2 + 4.922 s + 23.13
Finally, use viewGoal to graphically verify that all requirements are satisfied.
figure('Position',[100,100,550,710])
viewGoal([Req1 Req2 Req3],ST)
17-233
17 Control System Tuning Examples
17-234
Fixed-Structure Autopilot for a Passenger Jet
Closed-Loop Simulations
We now verify that the tuned autopilot satisfies the design requirements. First compare
the step response of with the step response of the reference model . Again use
getIOTransfer to compute the tuned closed-loop transfer from Nzc to Nz:
17-235
17 Control System Tuning Examples
Also plot the deflection and the respective contributions of the feedforward and
feedback paths:
step(T,'b',Tff,'g--',T-Tff,'r-.',6), grid
ylabel('\delta_m'), legend('Total','Feedforward','Feedback')
Finally, check the roll-off and stability margin requirements by computing the open-loop
response at .
17-236
See Also
The Bode plot confirms a roll-off of -40 dB/decade past 8 rad/s and indicates gain and
phase margins in excess of 10 dB and 70 degrees.
See Also
TuningGoal.Gain | TuningGoal.Margins | slTuner | systune (slTuner)
17-237
17 Control System Tuning Examples
Related Examples
• “Fault-Tolerant Control of a Passenger Jet” on page 17-239
17-238
Fault-Tolerant Control of a Passenger Jet
Background
This example deals with fault-tolerant flight control of passenger jet undergoing outages
in the elevator and aileron actuators. The flight control system must maintain stability
and meet performance and comfort requirements in both nominal operation and degraded
conditions where some actuators are no longer effective due to control surface
impairment. Wind gusts must be alleviated in all conditions. This application is sometimes
called reliable control as aircraft safety must be maintained in extreme flight conditions.
Aircraft Model
17-239
17 Control System Tuning Examples
The aircraft is modeled as a rigid 6th-order state-space system with the following state
variables (units are mph for velocities and deg/s for angular rates):
The state vector is available for control as well as the flight-path bank angle rate mu
(deg/s), the angle of attack alpha (deg), and the sideslip angle beta (deg). The control
inputs are the deflections of the right elevator, left elevator, right aileron, left aileron, and
rudder. All deflections are in degrees. Elevators are grouped symmetrically to generate
the angle of attack. Ailerons are grouped anti-symmetrically to generate roll motion. This
leads to 3 control actions as shown in the Simulink model.
The controller consists of state-feedback control in the inner loop and MIMO integral
action in the outer loop. The gain matrices Ki and Kx are 3-by-3 and 3-by-6, respectively,
so the controller has 27 tunable parameters.
Actuator Failures
We use a 9x5 matrix to encode the nominal mode and various actuator failure modes.
Each row corresponds to one flight condition, a zero indicating outage of the
corresponding deflection surface.
OutageCases = [...
1 1 1 1 1; ... % nominal operational mode
0 1 1 1 1; ... % right elevator outage
1 0 1 1 1; ... % left elevator outage
1 1 0 1 1; ... % right aileron outage
1 1 1 0 1; ... % left aileron outage
1 0 0 1 1; ... % left elevator and right aileron outage
0 1 0 1 1; ... % right elevator and right aileron outage
0 1 1 0 1; ... % right elevator and left aileron outage
1 0 1 0 1; ... % left elevator and left aileron outage
];
Design Requirements
17-240
Fault-Tolerant Control of a Passenger Jet
1 Provide good tracking performance in mu, alpha, and beta in nominal operating mode
with adequate decoupling of the three axes
2 Maintain performance in the presence of wind gust of 10 mph
3 Limit stability and performance degradation in the face of actuator outage.
To express the first requirement, you can use an LQG-like cost function that penalizes the
integrated tracking error e and the control effort u:
The diagonal weights and are the main tuning knobs for trading responsiveness
and control effort and emphasizing some channels over others. Use the
WeightedVariance requirement to express this cost function, and relax the
performance weight by a factor 2 for the outage scenarios.
We = diag([10 20 15]); Wu = eye(3);
For wind gust alleviation, limit the variance of the error signal e due to the white noise wg
driving the wind gust model. Again use a less stringent requirement for the outage
scenarios.
% Nominal gust alleviation requirement
HardNom = TuningGoal.Variance('wg','e',0.02);
HardNom.Models = 1;
Set the wind gust speed to 10 mph and initialize the tunable state-feedback and
integrators gains of the controller.
17-241
17 Control System Tuning Examples
GustSpeed = 10;
Ki = eye(3);
Kx = zeros(3,6);
Use the slTuner interface to set up the tuning task. List the blocks to be tuned and
specify the nine flight conditions by varying the outage variable in the Simulink model.
Because you can only vary scalar parameters in slTuner, independently specify the
values taken by each entry of the outage vector.
OutageData = struct(...
'Name',{'outage(1)','outage(2)','outage(3)','outage(4)','outage(5)'},...
'Value',mat2cell(OutageCases,9,[1 1 1 1 1]));
ST0 = slTuner('faultTolerantAircraft',{'Ki','Kx'},OutageData);
Use systune to tune the controller gains subject to the nominal requirements. Treat the
wind gust alleviation as a hard constraint.
[ST,fSoft,gHard] = systune(ST0,SoftNom,HardNom);
Retrieve the gain values and simulate the responses to step commands in mu, alpha,
beta for the nominal and degraded flight conditions. All simulations include wind gust
effects, and the red curve is the nominal response.
17-242
Fault-Tolerant Control of a Passenger Jet
17-243
17 Control System Tuning Examples
17-244
Fault-Tolerant Control of a Passenger Jet
The nominal responses are good but the deterioration in performance is unacceptable
when faced with actuator outage.
To improve reliability, retune the controller gains to meet the nominal requirement for the
nominal plant as well as the relaxed requirements for all eight outage scenarios.
[ST,fSoft,gHard] = systune(ST0,[SoftNom;SoftOut],[HardNom;HardOut]);
17-245
17 Control System Tuning Examples
The optimal performance (square root of LQG cost ) is only slightly worse than for the
nominal tuning (26 vs. 23). Retrieve the gain values and rerun the simulations (red curve
is the nominal response).
17-246
Fault-Tolerant Control of a Passenger Jet
17-247
17 Control System Tuning Examples
The controller now provides acceptable performance for all outage scenarios considered
in this example. The design could be further refined by adding specifications such as
minimum stability margins and gain limits to avoid actuator rate saturation.
See Also
TuningGoal.Variance | TuningGoal.WeightedVariance | slTuner | systune
(slTuner)
17-248
See Also
Related Examples
• “Fixed-Structure Autopilot for a Passenger Jet” on page 17-225
17-249
17 Control System Tuning Examples
The watertank_comp_design model, shown in the figure below, models a feedback loop for
regulating the water level in a water tank. The Controller block contains the first-order
compensator to be tuned.
mdl = 'cst_watertank_comp_design';
open_system(mdl);
The Water Tank subsystem models the water-tank dynamics. Water enters the tank from
the top at a rate proportional to the voltage, V, applied to the pump. The water leaves
through an opening in the tank base at a rate that is proportional to the square root of the
water height, H, in the tank. The presence of the square root in the water flow rate makes
the plant nonlinear.
17-250
Passive Control of Water Tank Level
where
17-251
17 Control System Tuning Examples
Passivity-Based Control
Since the water tank system is passive, it makes sense to require that the controller be
strictly passive to guarantee closed-loop stability even when the plant model is
inaccurate.
You can use the Control System Tuner app to tune the Controller block.
Step 1: Launch the Control System Tuner app from the Simulink model
17-252
Passive Control of Water Tank Level
Step 2: Launch the tuned block selector from the Select Blocks button in the Tuning tab
17-253
17 Control System Tuning Examples
Step 3: Select the Controller block and Click OK. This block now appears in the Tuned
Blocks list.
17-254
Passive Control of Water Tank Level
Step 4: Specify the tuning goals. Here there are two main goals:
Click on the New Goal dropdown list and first add a Passivity goal.
17-255
17 Control System Tuning Examples
17-256
Passive Control of Water Tank Level
Configure this goal to apply to the Controller block only. This is done by setting the input
signal to be the "Desired Water Level", the output signal to be the output of the Controller
block, and the loop opening to be at the Controller block output. Also specify minimum
passivity indices of 0.01 at the inputs and outputs to enforce strict passivity.
17-257
17 Control System Tuning Examples
Next add a Reference Tracking goal from the New Goal dropdown list. Configure this
goal for a 1 second response time.
17-258
Passive Control of Water Tank Level
17-259
17 Control System Tuning Examples
Finally, click on the Manage Goals button off the Tuning tab and mark the Passivity goal
as a hard tuning constraint.
Step 5: You are ready to tune the Controller block. Click the Tune button. You can view
the tuning results side by side by selecting Left/Right in the View tab.
17-260
Passive Control of Water Tank Level
You can further analyze these results by generating a MATLAB script that reproduces this
tuning process.
17-261
17 Control System Tuning Examples
Closed-Loop Simulation
You can view the Bode plot of the tuned controller. Click on the New Plot button off the
Control System tab. Select New Bode from dropdown list.
17-262
Passive Control of Water Tank Level
17-263
17 Control System Tuning Examples
Click on the Plot button. The bode plot is shown in the following figure.
17-264
Passive Control of Water Tank Level
You can also simulate the closed-loop nonlinear response with the tuned controller. First,
update the Controller block by clicking Update Blocks in the Control System tab.
17-265
17 Control System Tuning Examples
In the Simulink model, double click the Scope block to open the Scope window, then
simulate the model.
17-266
See Also
The nonlinear response of the tuned control system appears in the Scope window. This
simulation shows that the tracking performance is satisfactory.
See Also
Control System Tuner
17-267
17 Control System Tuning Examples
Related Examples
• “About Passivity and Passivity Indices” on page 10-2
• “Vibration Control in Flexible Beam” on page 17-269
17-268
Vibration Control in Flexible Beam
In this setup, the actuator delivering the force and the velocity sensor are collocated.
We can model the transfer function from control input to the velocity using finite-
element analysis. Keeping only the first six modes, we obtain a plant model of the form
% Parameters
xi = 0.05;
alpha = [0.09877, -0.309, -0.891, 0.5878, 0.7071, -0.8091];
w = [1, 4, 9, 16, 25, 36];
% Beam model
G = tf(alpha(1)^2*[1,0],[1, 2*xi*w(1), w(1)^2]) + ...
tf(alpha(2)^2*[1,0],[1, 2*xi*w(2), w(2)^2]) + ...
17-269
17 Control System Tuning Examples
isPassive(G)
ans =
logical
nyquist(G)
17-270
Vibration Control in Flexible Beam
LQG Controller
LQG control is a natural formulation for active vibration control. The LQG control setup is
depicted in Figure 2. The signals and are the process and measurement noise,
respectively.
17-271
17 Control System Tuning Examples
First use lqg to compute the optimal LQG controller for the objective
[a,b,c,d] = ssdata(G);
M = [c d;zeros(1,12) 1]; % [y;u] = M * [x;u]
QWV = blkdiag(b*b',1e-2);
QXU = M'*diag([1 1e-3])*M;
CLQG = lqg(ss(G),QXU,QWV);
The LQG-optimal controller CLQG is complex with 12 states and several notching zeros.
size(CLQG)
17-272
Vibration Control in Flexible Beam
Use the general-purpose tuner systune to try and simplify this controller. With systune,
you are not limited to a full-order controller and can tune controllers of any order. Here
for example, let's tune a 2nd-order state-space controller.
C = ltiblock.ss('C',2,1,1);
17-273
17 Control System Tuning Examples
Use the LQG criterion above as sole tuning goal. The LQG tuning goal lets you directly
specify the performance weights and noise covariances.
R1 = TuningGoal.LQG({'d','n'},{'y','u'},diag([1,1e-2]),diag([1 1e-3]));
[CL1,J1] = systune(CL0,R1);
The optimizer found a 2nd-order controller with . Compare with the optimal
value for CLQG:
[~,Jopt] = evalGoal(R1,replaceBlock(CL0,'C',CLQG))
Jopt =
0.4673
The performance degradation is less than 5%, and we reduced the controller complexity
from 12 to 2 states. Further compare the impulse responses from to for the two
controllers. The two responses are almost identical. You can therefore obtain near-optimal
vibration attenuation with a simple second-order controller.
T0 = feedback(G,CLQG,+1);
T1 = getIOTransfer(CL1,'d','y');
impulse(T0,T1,5)
title('Response to impulse disturbance d')
legend('LQG optimal','2nd-order LQG')
17-274
Vibration Control in Flexible Beam
We used an approximate model of the beam to design these two controllers. A priori,
there is no guarantee that these controllers will perform well on the real beam. However,
we know that the beam is a passive physical system and that the negative feedback
interconnection of passive systems is always stable. So if is passive, we can be
confident that the closed-loop system will be stable.
The optimal LQG controller is not passive. In fact, its relative passive index is infinite
because is not even minimum phase.
getPassiveIndex(-CLQG)
17-275
17 Control System Tuning Examples
ans =
Inf
nyquist(-CLQG)
Using systune, you can re-tune the second-order controller with the additional
requirement that should be passive. To do this, create a passivity tuning goal for
17-276
Vibration Control in Flexible Beam
R2 = TuningGoal.WeightedPassivity({'yn'},{'u'},-1,1);
R2.Openings = 'u';
Now re-tune the closed-loop model CL1 to minimize the LQG objective subject to
being passive. Note that the passivity goal R2 is now specified as a hard constraint.
[CL2,J2,g] = systune(CL1,R1,R2);
The tuner achieves the same value as previously, while enforcing passivity (hard
constraint less than 1). Verify that is passive.
C2 = getBlockValue(CL2,'C');
passiveplot(-C2)
17-277
17 Control System Tuning Examples
The improvement over the LQG-optimal controller is most visible in the Nyquist plot.
nyquist(-CLQG,-C2)
legend('LQG optimal','2nd-order passive LQG')
17-278
Vibration Control in Flexible Beam
T2 = getIOTransfer(CL2,'d','y');
impulse(T0,T2,5)
title('Response to impulse disturbance d')
legend('LQG optimal','2nd-order passive LQG')
17-279
17 Control System Tuning Examples
Using systune, you designed a second-order passive controller with near-optimal LQG
performance.
See Also
TuningGoal.LQG | TuningGoal.WeightedPassivity | systune
Related Examples
• “About Passivity and Passivity Indices” on page 10-2
• “Passive Control of Water Tank Level” on page 17-250
17-280
See Also
17-281
17 Control System Tuning Examples
Passivity-Based Control
load BeamControl G C
bode(G,C,{1e-2,1e4})
legend('G','C')
17-282
Passive Control with Communication Delays
The control configuration is shown below as well as the impulse response from to .
impulse(feedback(G,C))
17-283
17 Control System Tuning Examples
Now suppose there are substantial communication delays between the sensor and the
controller, and between the controller and the actuator. This situation is modeled in
Simulink as follows.
open_system('DelayedFeedback')
17-284
Passive Control with Communication Delays
T1 = 1;
T2 = 2;
Simulating this model shows that the communication delays destabilize the feedback loop.
17-285
17 Control System Tuning Examples
Scattering Transformation
To mitigate the delay effects, you can use a simple linear transformation of the signals
exchanged between the plant and controller over the network.
17-286
Passive Control with Communication Delays
or equivalently
with . Note that in the absence of delays, the two scattering transformations cancel
each other and the block diagram in Figure 1 is equivalent to the negative feedback
interconnection of and .
When delays are present, however, is no longer equal to and this scattering
transformation alters the properties of the closed-loop system. In fact, observing that
the Small Gain Theorem guarantees that the feedback interconnection of Figure 1 is
always stable no matter how large the delays. Confirm this by building a Simulink model
of the block diagram in Figure 1 for the value .
17-287
17 Control System Tuning Examples
b = 1;
open_system('ScatteringTransformation')
Simulate the impulse response of the closed-loop system as done before. The response is
now stable and similar to the delay-free response in spite of the large delays.
17-288
See Also
For more details on the scattering transformation, see T. Matiakis, S. Hirche, and M. Buss,
"Independent-of-Delay Stability of Nonlinear Networked Control Systems by Scattering
Transformation," Proceedings of the 2006 American Control Conference, 2006, pp.
2801-2806.
See Also
getPassiveIndex | isPassive
17-289
17 Control System Tuning Examples
Related Examples
• “Vibration Control in Flexible Beam” on page 17-269
More About
• “About Passivity and Passivity Indices” on page 10-2
17-290
Gain-Scheduled Control of a Chemical Reactor
The process considered here is a continuous stirred tank reactor (CSTR) during transition
from low to high conversion rate (high to low residual concentration). Because the
chemical reaction is exothermic (produces heat), the reactor temperature must be
controlled to prevent a thermal runaway. The control task is complicated by the fact that
the process dynamics are nonlinear and transition from stable to unstable and back to
stable as the conversion rate increases. The reactor dynamics are modeled in Simulink.
The controlled variables are the residual concentration Cr and the reactor temperature
Tr, and the manipulated variable is the temperature Tc of the coolant circulating in the
reactor's cooling jacket.
open_system('rct_CSTR_OL')
17-291
17 Control System Tuning Examples
17-292
Gain-Scheduled Control of a Chemical Reactor
An open-loop control strategy consists of following the coolant temperature profile above
to smoothly transition between the Cr=8.57 and Cr=2 equilibria. However, this strategy
is doomed by the fact that the reaction is unstable in the mid range and must be properly
cooled to avoid thermal runaway. This is confirmed by inspecting the poles of the
linearized models for the five equilibrium points considered above (three out of the five
models are unstable).
pole(G)
ans(:,:,1) =
-0.5225 + 0.0000i
-0.8952 + 0.0000i
17-293
17 Control System Tuning Examples
ans(:,:,2) =
0.1733 + 0.0000i
-0.8866 + 0.0000i
ans(:,:,3) =
0.5114 + 0.0000i
-0.8229 + 0.0000i
ans(:,:,4) =
0.0453 + 0.0000i
-0.4991 + 0.0000i
ans(:,:,5) =
-1.1077 + 1.0901i
-1.1077 - 1.0901i
The Bode plot further highlights the significant variations in plant dynamics while
transitioning from Cr=8.57 to Cr=2.
clf, bode(G(:,'Tc'),{0.01,10})
17-294
Gain-Scheduled Control of a Chemical Reactor
To prevent thermal runaway while ramping down the residual concentration, use
feedback control to adjust the coolant temperature Tc based on measurements of the
residual concentration Cr and reactor temperature Tr. For this application, we use a
cascade control architecture where the inner loop regulates the reactor temperature and
the outer loop tracks the concentration setpoint. Both feedback loops are digital with a
sampling period of 0.5 minutes.
open_system('rct_CSTR')
17-295
17 Control System Tuning Examples
The target concentration Cref ramps down from 8.57 kmol/m^3 at t=10 to 2 kmol/m^3
at t=36 (the transition lasts 26 minutes). The corresponding profile Tref for the reactor
temperature is obtained by interpolating the equilibrium values TrEQ from trim analysis.
The controller computes the coolant temperature adjustment dTc relative to the initial
equilibrium value TcEQ(1)=297.98 for Cr=8.57. Note that the model is set up so that
initially, the output TrSP of the "Concentration controller" block matches the reactor
temperature, the adjustment dTc is zero, and the coolant temperature Tc is at its
equilibrium value TcEQ(1).
clf
t = [0 10:36 45];
C = interp1([0 10 36 45],[8.57 8.57 2 2],t);
subplot(211), plot(t,C), grid, set(gca,'ylim',[0 10])
title('Target residual concentration'), ylabel('Cref')
17-296
Gain-Scheduled Control of a Chemical Reactor
subplot(212), plot(t,interp1(CrEQ,TrEQ,C))
title('Corresponding reactor temperature at equilibrium'), ylabel('Tref'), grid
Control Objectives
Use TuningGoal objects to capture the design requirements. First, Cr should follow
setpoints Cref with a response time of about 5 minutes.
R1 = TuningGoal.Tracking('Cref','Cr',5);
The inner loop (temperature) should stabilize the reaction dynamics with sufficient
damping and fast enough decay.
MinDecay = 0.2;
MinDamping = 0.5;
17-297
17 Control System Tuning Examples
% Constrain closed-loop poles of inner loop with the outer loop open
R2 = TuningGoal.Poles('Tc',MinDecay,MinDamping);
R2.Openings = 'TrSP';
The Rate Limit block at the controller output specifies that the coolant temperature Tc
cannot vary faster than 10 degrees per minute. This is a severe limitation on the
controller authority which, when ignored, can lead to poor performance or instability. To
take this rate limit into account, observe that Cref varies at a rate of 0.25 kmol/m^3/min.
To ensure that Tc does not vary faster than 10 degrees/min, the gain from Cref to Tc
should be less than 10/0.25=40.
R3 = TuningGoal.Gain('Cref','Tc',40);
Finally, require at least 7 dB of gain margin and 45 degrees of phase margin at the plant
input Tc.
R4 = TuningGoal.Margins('Tc',7,45);
Gain-Scheduled Controller
To achieve these requirements, we use a PI controller in the outer loop and a lead
compensator in the inner loop. Due to the slow sampling rate, the lead compensator is
needed to adequately stabilize the chemical reaction at the mid-range concentration Cr =
5.28 kmol/m^3/min. Because the reaction dynamics vary substantially with concentration,
we further schedule the controller gains as a function of concentration. This is modeled in
Simulink using Lookup Table blocks as shown in Figures 1 and 2.
17-298
Gain-Scheduled Control of a Chemical Reactor
17-299
17 Control System Tuning Examples
Tuning this gain-scheduled controller amounts to tuning the look-up table data over a
range of concentration values. Rather than tuning individual look-up table entries,
parameterize the controller gains Kp,Ki,Kt,a,b as quadratic polynomials in Cr, for
example,
Besides reducing the number of variables to tune, this approach ensures smooth gain
transitions as Cr varies. Using systune, you can automatically tune the coefficients
to meet the requirements R1-R4 at the five equilibrium points
computed above. This amounts to tuning the gain-scheduled controller at five design
17-300
Gain-Scheduled Control of a Chemical Reactor
points along the Cref trajectory. Use the tunableSurface object to parameterize each
gain as a quadratic function of Cr. The "tuning grid" is set to the five concentrations CrEQ
and the basis functions for the quadratic parameterization are . Most gains are
initialized to be identically zero.
TuningGrid = struct('Cr',CrEQ);
ShapeFcn = @(Cr) [Cr , Cr^2];
Controller Tuning
Because the target bandwidth is within a decade of the Nyquist frequency, it is easier to
tune the controller directly in the discrete domain. Discretize the linearized process
dynamics with sample time of 0.5 minutes. Use the ZOH method to reflect how the digital
controller interacts with the continuous-time plant.
Ts = 0.5;
Gd = c2d(G,Ts);
Create an slTuner interface for tuning the quadratic gain schedules introduced above.
Use block substitution to replace the nonlinear plant model by the five discretized linear
models Gd obtained at the design points CrEQ. Use setBlockParam to associate the
tunable gain functions Kp, Ki, Kt, a, b with the Lookup Table blocks of the same name.
BlockSubs = struct('Name','rct_CSTR/CSTR','Value',Gd);
ST0 = slTuner('rct_CSTR',{'Kp','Ki','Kt','a','b'},BlockSubs);
ST0.Ts = Ts; % sample time for tuning
17-301
17 Control System Tuning Examples
You can now use systune to tune the controller coefficients against the requirements
R1-R4. Make the stability margin requirement a hard constraints and optimize the
remaining requirements.
ST = systune(ST0,[R1 R2 R3],R4);
The resulting design satisfies the hard constraint (Hard<1) and nearly satisfies the
remaining requirements (Soft close to 1). To validate this design, simulate the responses
to a ramp in concentration with the same slope as Cref. Each plot shows the linear
responses at the five design points CrEQ.
t = 0:Ts:20;
uC = interp1([0 2 5 20],(-0.25)*[0 0 3 3],t);
subplot(211), lsim(getIOTransfer(ST,'Cref','Cr'),uC)
grid, set(gca,'ylim',[-1.5 0.5]), title('Residual concentration')
subplot(212), lsim(getIOTransfer(ST,'Cref','Tc'),uC)
grid, title('Coolant temperature variation')
17-302
Gain-Scheduled Control of a Chemical Reactor
Note that rate of change of the coolant temperature remains within the physical limits (10
degrees per minute or 5 degrees per sample period).
Controller Validation
17-303
17 Control System Tuning Examples
Next push the Play button to simulate the response with the tuned gain schedules. The
simulation results appear in Figure 3. The gain-scheduled controller successfully drives
the reaction through the transition with adequate response time and no saturation of the
17-304
Gain-Scheduled Control of a Chemical Reactor
rate limits (controller output du matches effective temperature variation dTc). The
reactor temperature stays close to its equilibrium value Tref, indicating that the
controller keeps the reaction near equilibrium while preventing thermal runaway.
17-305
17 Control System Tuning Examples
Alternatively, you can tune the gain schedules directly in MATLAB without using the
slTuner interface. First parameterize the gains as quadratic functions of Cr as done
above.
TuningGrid = struct('Cr',CrEQ);
ShapeFcn = @(Cr) [Cr , Cr^2];
PI = pid(Kp,Ki,'Ts',Ts,'TimeUnit','min');
PI.u = 'ECr'; PI.y = 'TrSP';
Use connect to build a closed-loop model of the overall control system at the five design
points. Mark the controller outputs TrSP and Tc as "analysis points" so that loops can be
opened and stability margins evaluated at these locations. The closed-loop model T0 is a
5-by-1 array of linear models depending on the tunable coefficients of Kp,Ki,Kt,a,b.
Each model is discrete and sampled every half minute.
Gd.TimeUnit = 'min';
S1 = sumblk('ECr = Cref - Cr');
S2 = sumblk('ETr = TrSP - Tr');
T0 = connect(Gd(:,'Tc'),LEAD,PI,S1,S2,'Cref','Cr',{'TrSP','Tc'});
T = systune(T0,[R1 R2 R3],R4);
The result is similar to the one obtained above. Confirm by plotting the gains as a function
of Cr using the tuned coefficients in T.
17-306
Gain-Scheduled Control of a Chemical Reactor
clf
subplot(321), viewSurf(setBlockValue(Kp,T)), ylabel('Kp')
subplot(322), viewSurf(setBlockValue(Ki,T)), ylabel('Ki')
subplot(323), viewSurf(setBlockValue(Kt,T)), ylabel('Kt')
subplot(324), viewSurf(setBlockValue(a,T)), ylabel('a')
subplot(325), viewSurf(setBlockValue(b,T)), ylabel('b')
17-307
17 Control System Tuning Examples
You can further validate the design by simulating the linear responses at each design
point. However, you need to return to Simulink to simulate the nonlinear response of the
gain-scheduled controller.
See Also
setBlockParam | slTuner | tunableSurface
Related Examples
• “Model Gain-Scheduled Control Systems in Simulink” on page 16-4
• “Tuning of Gain-Scheduled Three-Loop Autopilot” on page 17-309
More About
• “Parameterize Gain Schedules” on page 16-31
17-308
Tuning of Gain-Scheduled Three-Loop Autopilot
We use a classic three-loop autopilot structure to control the flight path angle . This
autopilot adjusts the flight path by delivering adequate bursts of normal acceleration
(acceleration along ). In turn, normal acceleration is produced by adjusting the elevator
deflection to cause pitching and vary the amount of lift. The autopilot uses Proportional-
17-309
17 Control System Tuning Examples
Integral (PI) control in the pitch rate loop and proportional control in the and loops.
The closed-loop system (airframe and autopilot) are modeled in Simulink.
The airframe dynamics are nonlinear and the aerodynamic forces and moments depend
on speed and incidence . To obtain suitable performance throughout the flight
envelope, the autopilot gains must be adjusted as a function of and to compensate for
changes in plant dynamics. This adjustment process is called "gain scheduling" and
are called the scheduling variables. In the Simulink model, gain schedules are
implemented as look-up tables driven by measurements of and .
Gain scheduling is a linear technique for controlling nonlinear or time-varying plants. The
idea is to compute linear approximations of the plant at various operating conditions, tune
the controller gains at each operating condition, and swap gains as a function of
operating condition during operation. Conventional gain scheduling involves three major
steps:
17-310
Tuning of Gain-Scheduled Three-Loop Autopilot
2 Tune the controller gains for the linearized dynamics at each operating condition
3 Reconcile the gain values to provide smooth transition between operating conditions.
In this example, we combine Steps 2. and 3. by parameterizing the autopilot gains as first-
order polynomials in and directly tuning the polynomial coefficients for the entire
flight envelope. This approach eliminates Step 3. and guarantees smooth gain variations
as a function of and . Moreover, the gain schedule coefficients can be automatically
tuned with systune.
Assume that the incidence varies between -20 and 20 degrees and that the speed
varies between 700 and 1400 m/s. When neglecting gravity, the airframe dynamics are
symmetric in so consider only positive values of . Use a 5-by-9 grid of linearly spaced
pairs to cover the flight envelope:
nA = 5; % number of alpha values
nV = 9; % number of V values
[alpha,V] = ndgrid(linspace(0,20,nA)*pi/180,linspace(700,1400,nV));
For each flight condition , linearize the airframe dynamics at trim (zero normal
acceleration and pitching moment). This requires computing the elevator deflection and
pitch rate that result in steady and . To do this, first isolate the airframe model in a
separate Simulink model.
open_system('rct_airframeTRIM')
17-311
17 Control System Tuning Examples
Use operspec to specify the trim condition, use findop to compute the trim values of
and , and linearize the airframe dynamics for the resulting operating point. See the
"Trimming and Linearizing an Airframe" example in Simulink Control Design for details.
Repeat these steps for the 45 flight conditions .
% TRIM
Options = findopOptions('DisplayReport','off');
op(ct) = findop('rct_airframeTRIM',opspec,Options);
end
This produces a 5-by-9 array of linearized plant models at the 45 flight conditions .
The plant dynamics vary substantially across the flight envelope.
17-312
Tuning of Gain-Scheduled Three-Loop Autopilot
This cuts the number of variables from 88 down to 4 for each lookup table. Use the
tunableSurface object to parameterize each gain surface. Note that:
17-313
17 Control System Tuning Examples
• TuningGrid specifies the "tuning grid" (design points). This grid should match the
one used for linearization but needs not match the loop-up table breakpoints
• ShapeFcn specifies the basis functions for the surface parameterization ( , , and
)
Each surface is initialized to a constant gain using the tuning results for = 10 deg and
= 1050 m/s (mid-range design).
TuningGrid = struct('alpha',alpha,'V',V);
ShapeFcn = @(alpha,V) [alpha,V,alpha*V];
Next create an slTuner interface for tuning the gain surfaces. Use block substitution to
replace the nonlinear plant model by the linearized models over the tuning grid. Use
setBlockParam to associate the tunable gain surfaces Kp, Ki, Ka, Kg with the
Interpolation blocks of the same name.
Autopilot Tuning
systune can automatically tune the gain surface coefficients for the entire flight
envelope. Use TuningGoal objects to specify the performance objectives:
• loop: Track the setpoint with a 1 second response time, less than 2% steady-state
error, and less than 30% peak error.
Req1 = TuningGoal.Tracking('gamma_ref','gamma',1,0.02,1.3);
viewGoal(Req1)
17-314
Tuning of Gain-Scheduled Three-Loop Autopilot
• loop: Ensure good disturbance rejection at low frequency (to track acceleration
demands) and past 10 rad/s (to be insensitive to measurement noise).
17-315
17 Control System Tuning Examples
17-316
Tuning of Gain-Scheduled Three-Loop Autopilot
MinDamping = 0.35;
Req4 = TuningGoal.Poles(0,MinDamping);
Using systune, tune the 16 gain surface coefficients to best meet these performance
requirements at all 45 flight conditions.
The final value of the combined objective is close to 1, indicating that all requirements are
nearly met. Visualize the resulting gain surfaces.
17-317
17 Control System Tuning Examples
17-318
Tuning of Gain-Scheduled Three-Loop Autopilot
Validation
First validate the tuned autopilot at the 45 flight conditions considered above. Plot the
response to a step change in flight path angle and the response to a step disturbance in
elevator deflection.
clf
subplot(211), step(getIOTransfer(ST,'gamma_ref','gamma'),5), grid
title('Tracking of step change in flight path angle')
subplot(212), step(getIOTransfer(ST,'delta','az'),3), grid
title('Rejection of step disturbance at plant input')
The responses are satisfactory at all flight conditions. Next validate the autopilot against
the nonlinear airframe model. First use writeBlockValue to apply the tuning results to
17-319
17 Control System Tuning Examples
the Simulink model. This evaluates each gain surface formula at the breakpoints specified
in the two Prelookup blocks and writes the result in the corresponding Interpolation
block.
writeBlockValue(ST)
Now simulate the autopilot performance for a maneuver that takes the airframe through a
large portion of its flight envelope. The code below is equivalent to pressing the Play
button in the Simulink model and inspecting the responses in the Scope blocks.
% Initial conditions
h_ini = 1000;
alpha_ini = 0;
v_ini = 700;
% Simulate
SimOut = sim('rct_airframeGS', 'ReturnWorkspaceOutputs', 'on');
17-320
Tuning of Gain-Scheduled Three-Loop Autopilot
subplot(211)
plot(t,Sim_alpha.Values.Data), grid
title('Incidence \alpha in degrees')
subplot(212)
plot(t,Sim_V.Values.Data), grid
title('Speed V in m/s')
17-321
17 Control System Tuning Examples
subplot(211)
plot(t,Sim_h.Values.Data), grid
title('Altitude h in meters')
subplot(212)
plot(t,Sim_az.Values.Data), grid
title('Normal acceleration a_z in g''s')
17-322
Tuning of Gain-Scheduled Three-Loop Autopilot
Tracking of the flight path angle profile remains good throughout the maneuver. Note that
the variations in incidence and speed cover most of the flight envelope considered
here ([-20,20] degrees for and [700,1400] for ). And while the autopilot was tuned for
a nominal altitude of 3000 m, it fares well for altitude changing from 1,000 to 10,000 m.
The nonlinear simulation results confirm that the gain-scheduled autopilot delivers
consistently high performance throughout the flight envelope. The "gain surface tuning"
procedure provides simple explicit formulas for the gain dependence on the scheduling
variables. Instead of using look-up tables, you can use these formulas directly for an more
memory-efficient hardware implementation.
17-323
17 Control System Tuning Examples
See Also
setBlockParam | slTuner | tunableSurface
Related Examples
• “Model Gain-Scheduled Control Systems in Simulink” on page 16-4
• “Gain-Scheduled Control of a Chemical Reactor” on page 17-291
More About
• “Gain Scheduling Basics” on page 16-2
• “Parameterize Gain Schedules” on page 16-31
17-324
Tuning Feedback Loops with LOOPTUNE
This example uses a simple engine speed control application as illustration. The control
system consists of a single PID loop and the PID controller gains must be tuned to
adequately respond to step changes in the desired speed. Specifically, we want the
response to settle in less than 5 seconds with little or no overshoot.
17-325
17 Control System Tuning Examples
We need to tune the four PID gains to achieve the desired performance. Use the
tunablePID class to parameterize the PID controller.
PID0 = tunablePID('SpeedController','pid')
PID0 =
Parametric continuous-time PID controller "SpeedController" with formula:
1 s
Kp + Ki * --- + Kd * --------
s Tf*s+1
17-326
Tuning Feedback Loops with LOOPTUNE
Type "pid(PID0)" to see the current value and "get(PID0)" to see all properties.
looptune tunes the generic SISO or MIMO feedback loop of Figure 2. This feedback loop
models the interaction between the plant and the controller. Note that this is a positive
feedback interconnection.
For the speed control loop, the plant is the engine model and the controller consists
of the PID and the prefilter .
To use looptune, create models for and in Figure 3. Assign names to the inputs
and outputs of each model to specify the feedback paths between plant and controller.
17-327
17 Control System Tuning Examples
Note that the controller has two inputs: the speed reference "r" and the speed
measurement "speed".
F = tf(10,[1 10]); % prefilter
G = Engine;
G.InputName = 'throttle';
G.OutputName = 'speed';
C0 = PID0 * [F , -1];
C0.InputName = {'r','speed'};
C0.OutputName = 'throttle';
Here C0 is a generalized state-space model (genss) that depends on the tunable PID
block PID0.
You can now use looptune to tune the PID gains subject to a simple control bandwidth
requirement. To achieve the 5-second settling time, the gain crossover frequency of the
open-loop response should be approximately 1 rad/s. Given this basic requirement,
looptune automatically shapes the open-loop response to provide integral action, high-
frequency roll-off, and adequate stability margins. Note that you could specify additional
requirements to further constrain the design, see "Decoupling Controller for a Distillation
Column" for an example.
wc = 1; % target gain crossover frequency
[~,C,~,Info] = looptune(G,C0,wc);
The final value is less than 1, indicating that the desired bandwidth was achieved with
adequate roll-off and stability margins. looptune returns the tuned controller C. Use
getBlockValue to retrieve the tuned value of the PID block.
PIDT = getBlockValue(C,'SpeedController')
PIDT =
1 s
Kp + Ki * --- + Kd * --------
s Tf*s+1
17-328
Tuning Feedback Loops with LOOPTUNE
Name: SpeedController
Continuous-time PIDF controller in parallel form.
Validating Results
Use loopview to validate the design and visualize the loop shaping requirements
implicitly enforced by looptune.
clf, loopview(G,C,Info)
17-329
17 Control System Tuning Examples
Next plot the closed-loop response to a step command in engine speed. The tuned
response satisfies our requirements.
17-330
Decoupling Controller for a Distillation Column
This example uses a simple model of the distillation column shown below.
In the so-called LV configuration, the controlled variables are the concentrations yD and
yB of the chemicals D (tops) and B (bottoms), and the manipulated variables are the reflux
L and boilup V. This process exhibits strong coupling and large variations in steady-state
gain for some combinations of L and V. For more details, see Skogestad and Postlethwaite,
Multivariable Feedback Control.
The plant is modeled as a first-order transfer function with inputs L,V and outputs
yD,yB:
17-331
17 Control System Tuning Examples
The unit of time is minutes (all plots are in minutes, not seconds).
s = tf('s');
G = [87.8 -86.4 ; 108.2 -109.6]/(75*s+1);
G.InputName = {'L','V'};
G.OutputName = {'yD','yB'};
Control Architecture
• Independent control of the tops and bottoms concentrations by ensuring that a change
in the tops setpoint Dsp has little impact on the bottoms concentration B and vice
versa
• Response time of about 4 minutes with less than 15% overshoot
• Fast rejection of input disturbances affecting the effective reflux L and boilup V
To achieve these objectives we use the control architecture shown below. This
architecture consists of a static decoupling matrix DM in series with two PI controllers for
the reflux L and boilup V.
open_system('rct_distillation')
17-332
Decoupling Controller for a Distillation Column
The looptune command provides a quick way to tune MIMO feedback loops. When the
control system is modeled in Simulink, you just specify the tuned blocks, the control and
measurement signals, and the desired bandwidth, and looptune automatically sets up
the problem and tunes the controller parameters. looptune shapes the open-loop
response to provide integral action, roll-off, and adequate MIMO stability margins.
Use the slTuner interface to specify the tuned blocks, the controller I/Os, and signals of
interest for closed-loop validation.
ST0 = slTuner('rct_distillation',{'PI_L','PI_V','DM'});
% Signals of interest
addPoint(ST0,{'r','dL','dV','L','V','y'})
Set the control bandwidth by specifying the gain crossover frequency for the open-loop
response. For a response time of 4 minutes, the crossover frequency should be
approximately 2/4 = 0.5 rad/min.
wc = 0.5;
Use TuningGoal objects to specify the remaining control objectives. The response to a
step command should have less than 15% overshoot. The response to a step disturbance
at the plant input should be well damped, settle in less than 20 minutes, and not exceed 4
in amplitude.
OS = TuningGoal.Overshoot('r','y',15);
DR = TuningGoal.StepRejection({'dL','dV'},'y',4,20);
Next use looptune to tune the controller blocks PI_L, PI_V, and DM subject to the
disturbance rejection requirement.
Controls = {'L','V'};
Measurements = 'y';
[ST,gam,Info] = looptune(ST0,Controls,Measurements,wc,OS,DR);
The final value is near 1 which indicates that all requirements were met. Use loopview
to check the resulting design. The responses should stay outside the shaded areas.
17-333
17 Control System Tuning Examples
figure('Position',[0,0,1000,1200])
loopview(ST,Info)
17-334
Decoupling Controller for a Distillation Column
Use getIOTransfer to access and plot the closed-loop responses from reference and
disturbance to the tops and bottoms concentrations. The tuned responses show a good
compromise between tracking and disturbance rejection.
figure
Ttrack = getIOTransfer(ST,'r','y');
step(Ttrack,40), grid, title('Setpoint tracking')
Treject = getIOTransfer(ST,{'dV','dL'},'y');
step(Treject,40), grid, title('Disturbance rejection')
17-335
17 Control System Tuning Examples
17-336
Decoupling Controller for a Distillation Column
Inspection of the controller obtained above shows that the second PI controller has
negative gains.
getBlockValue(ST,'PI_V')
ans =
1
Kp + Ki * ---
s
17-337
17 Control System Tuning Examples
Name: PI_V
Continuous-time PI controller in parallel form.
This is due to the negative signs in the second input channels of the plant . In addition,
the tunable elements are over-parameterized because multiplying DM by two and dividing
the PI gains by two does not change the overall controller. To address these issues, fix the
(1,1) entry of DM to 1 and the (2,2) entry to -1.
DM = getBlockParam(ST0,'DM');
DM.Gain.Value = diag([1 -1]);
DM.Gain.Free = [false true;true false];
setBlockParam(ST0,'DM',DM)
[ST,gam,Info] = looptune(ST0,Controls,Measurements,wc,OS,DR);
The step responses look similar but the values of DM and the PI gains are more suitable
for implementation.
figure('Position',[0,0,700,350])
subplot(121)
Ttrack = getIOTransfer(ST,'r','y');
step(Ttrack,40), grid, title('Setpoint tracking')
subplot(122)
Treject = getIOTransfer(ST,{'dV','dL'},'y');
step(Treject,40), grid, title('Disturbance rejection')
17-338
Decoupling Controller for a Distillation Column
showTunable(ST)
Block 1: rct_distillation/PI_L =
1
Kp + Ki * ---
s
Name: PI_L
Continuous-time PI controller in parallel form.
-----------------------------------
Block 2: rct_distillation/PI_V =
1
Kp + Ki * ---
s
17-339
17 Control System Tuning Examples
Name: PI_V
Continuous-time PI controller in parallel form.
-----------------------------------
Block 3: rct_distillation/DM =
D =
u1 u2
y1 1 -0.7784
y2 1.244 -1
Name: DM
Static gain.
If you do not have a Simulink model of the control system, you can use LTI objects and
Control Design blocks to create a MATLAB representation of the following block diagram.
First parameterize the tunable elements using Control Design blocks. Use the
tunableGain object to parameterize DM and fix DM(1,1)=1 and DM(2,2)=-1. This
creates a 2x2 static gain with the off-diagonal entries as tunable parameters.
DM = tunableGain('Decoupler',diag([1 -1]));
DM.Gain.Free = [false true;true false];
17-340
Decoupling Controller for a Distillation Column
PI_L = tunablePID('PI_L','pi');
PI_V = tunablePID('PI_V','pi');
% Crossover frequency
wc = 0.5;
To validate the design, close the loop with the tuned compensator C and simulate the step
responses for setpoint tracking and disturbance rejection.
Tcl = connect(G,C,{'Dsp','Bsp','L','V'},{'yD','yB'});
figure('Position',[0,0,700,350])
subplot(121)
Ttrack = Tcl(:,[1 2]);
step(Ttrack,40), grid, title('Setpoint tracking')
subplot(122)
Treject = Tcl(:,[3 4]);
Treject.InputName = {'dL','dV'};
step(Treject,40), grid, title('Disturbance rejection')
17-341
17 Control System Tuning Examples
17-342
Tuning of a Digital Motion Control System
This device could be part of some production machine and is intended to move some load
(a gripper, a tool, a nozzle, or anything else that you can imagine) from one angular
position to another and back again. This task is part of the "production cycle" that has to
be completed to create each product or batch of products.
17-343
17 Control System Tuning Examples
The digital controller must be tuned to maximize the production speed of the machine
without compromising accuracy and product quality. To do this, we first model the control
system in Simulink using a 4th-order model of the inertia and flexible shaft:
open_system('rct_dmc')
The "Tunable Digital Controller" consists of a gain in series with a lead/lag controller.
17-344
Tuning of a Digital Motion Control System
Tuning is complicated by the presence of a flexible mode near 350 rad/s in the plant:
G = linearize('rct_dmc','rct_dmc/Plant Model');
bode(G,{10,1e4}), grid
17-345
17 Control System Tuning Examples
Compensator Tuning
We are seeking a 0.5 second response time to a step command in angular position with
minimum overshoot. This corresponds to a target bandwidth of approximately 5 rad/s.
The looptune command offers a convenient way to tune fixed-structure compensators
like the one in this application. To use looptune, first instantiate the slTuner interface
to automatically acquire the control structure from Simulink. Note that the signals of
interest are already marked as Linear Analysis Points in the Simulink model.
ST0 = slTuner('rct_dmc',{'Gain','Leadlag'});
Next use looptune to tune the compensator parameters for the target gain crossover
frequency of 5 rad/s:
17-346
Tuning of a Digital Motion Control System
A final value below or near 1 indicates success. Inspect the tuned values of the gain and
lead/lag filter:
showTunable(ST1)
D =
u1
y1 1.78e-05
Name: Gain
Static gain.
-----------------------------------
4.259 s + 8.102
---------------
s + 15.76
Name: Leadlag
Continuous-time transfer function.
Design Validation
To validate the design, use the slTuner interface to quickly access the closed-loop
transfer functions of interest and compare the responses before and after tuning.
T0 = getIOTransfer(ST0,'Reference','Measured Position');
T1 = getIOTransfer(ST1,'Reference','Measured Position');
step(T0,T1), grid
legend('Original','Tuned')
17-347
17 Control System Tuning Examples
The tuned response has significantly less overshoot and satisfies the response time
requirement. However these simulations are obtained using a continuous-time lead/lag
compensator (looptune operates in continuous time) so we need to further validate the
design in Simulink using a digital implementation of the lead/lag compensator. Use
writeBlockValue to apply the tuned values to the Simulink model and automatically
discretize the lead/lag compensator to the rate specified in Simulink.
writeBlockValue(ST1)
You can now simulate the response of the continuous-time plant with the digital
controller:
sim('rct_dmc'); % angular position logged in "yout" variable
t = yout.time;
17-348
Tuning of a Digital Motion Control System
y = yout.signals.values;
step(T1), hold, plot(t,y,'r--')
legend('Continuous','Hybrid (Simulink)')
The simulations closely match and the coefficients of the digital lead/lag can be read from
the "Leadlag" block in Simulink.
Next try to increase the control bandwidth from 5 to 50 rad/s. Because of the plant
resonance near 350 rad/s, the lead/lag compensator is no longer sufficient to get
17-349
17 Control System Tuning Examples
adequate stability margins and small overshoot. One remedy is to add a notch filter as
shown in Figure 3.
To tune this modified control architecture, create an slTuner instance with the three
tunable blocks.
ST0 = slTuner('rct_dmcNotch',{'Gain','Leadlag','Notch'});
wn = realp('wn',300);
zeta1 = realp('zeta1',1);
zeta2 = realp('zeta2',1);
17-350
Tuning of a Digital Motion Control System
Then associate this parametric notch model with the "Notch" block in the Simulink model.
Because the control system is tuned in the continuous time, you can use a continuous-
time parameterization of the notch filter even though the "Notch" block itself is discrete.
setBlockParam(ST0,'Notch',N);
Next use looptune to jointly tune the "Gain", "Leadlag", and "Notch" blocks with a 50
rad/s target crossover frequency. To eliminate residual oscillations from the plant
resonance, specify a target loop shape with a -40 dB/decade roll-off past 50 rad/s.
The final gain is close to 1, indicating that all requirements are met. Compare the closed-
loop step response with the previous designs.
T2 = getIOTransfer(ST2,'Reference','Measured Position');
clf
step(T0,T1,T2,1.5), grid
legend('Original','Lead/lag','Lead/lag + notch')
17-351
17 Control System Tuning Examples
To verify that the notch filter performs as expected, evaluate the total compensator C and
the open-loop response L and compare the Bode responses of G, C, L:
% Get tuned block values (in the order blocks are listed in ST2.TunedBlocks)
[g,LL,N] = getBlockValue(ST2,'Gain','Leadlag','Notch');
C = N * LL * g;
L = getLoopTransfer(ST2,'Notch',-1);
bode(G,C,L,{1e1,1e3}), grid
legend('G','C','L')
17-352
Tuning of a Digital Motion Control System
This Bode plot confirms that the plant resonance has been correctly "notched out."
Again use writeBlockValue to discretize the tuned lead/lag and notch filters and write
their values back to Simulink. Compare the MATLAB and Simulink responses:
writeBlockValue(ST2)
sim('rct_dmcNotch');
t = yout.time;
y = yout.signals.values;
step(T2), hold, plot(t,y,'r--')
legend('Continuous','Hybrid (Simulink)')
17-353
17 Control System Tuning Examples
The Simulink response exhibits small residual oscillations. The notch filter discretization
is the likely culprit because the notch frequency is close to the Nyquist frequency pi/
0.002=1570 rad/s. By default the notch is discretized using the ZOH method. Compare
this with the Tustin method prewarped at the notch frequency:
Nd1 = c2d(N,Ts,'zoh');
Nd2 = c2d(N,Ts,'tustin',c2dOptions('PrewarpFrequency',wn(1)));
clf, bode(N,Nd1,Nd2)
17-354
Tuning of a Digital Motion Control System
The ZOH method has significant distortion and prewarped Tustin should be used instead.
To do this, specify the desired rate conversion method for the notch filter block:
setBlockRateConversion(ST2,'Notch','tustin',wn(1))
writeBlockValue(ST2)
writeBlockValue now uses Tustin prewarped at the notch frequency to discretize the
notch filter and write it back to Simulink. Verify that this gets rid of the oscillations.
sim('rct_dmcNotch');
t = yout.time;
17-355
17 Control System Tuning Examples
y = yout.signals.values;
step(T2), hold, plot(t,y,'r--')
legend('Continuous','Hybrid (Simulink)')
Alternatively, you can tune the controller directly in discrete time to avoid discretization
issues with the notch filter. To do this, specify that the Simulink model should be
linearized and tuned at the controller sample time of 0.002 seconds:
ST0 = slTuner('rct_dmcNotch',{'Gain','Leadlag','Notch'});
ST0.Ts = 0.002;
17-356
Tuning of a Digital Motion Control System
To prevent high-gain control and saturations, add a requirement that limits the gain from
reference to control signal (output of Notch block).
GL = TuningGoal.Gain('Reference','Notch',0.01);
Now retune the controller at the specified sampling rate and verify the tuned open- and
closed-loop responses.
ST2 = looptune(ST0,Control,Measurement,TLS,GL);
% Closed-loop responses
T2 = getIOTransfer(ST2,'Reference','Measured Position');
clf
step(T0,T1,T2,1.5), grid
legend('Original','Lead/lag','Lead/lag + notch')
17-357
17 Control System Tuning Examples
% Open-loop responses
[g,LL,N] = getBlockValue(ST2,'Gain','Leadlag','Notch');
C = N * LL * g;
L = getLoopTransfer(ST2,'Notch',-1);
bode(G,C,L,{1e1,2e3}), grid
legend('G','C','L')
17-358
Tuning of a Digital Motion Control System
The results are similar to those obtained when tuning the controller in continuous time.
Now validate the digital controller against the continuous-time plant in Simulink.
writeBlockValue(ST2)
sim('rct_dmcNotch');
t = yout.time;
y = yout.signals.values;
step(T2), hold, plot(t,y,'r--')
legend('Discrete','Hybrid (Simulink)')
17-359
17 Control System Tuning Examples
This time, the hybrid response closely matches its discrete-time approximation and no
further adjustment of the notch filter is required.
17-360
Customization
361
18
Preliminaries
Terminology
You can use the Control System Toolbox editors to set properties and preferences in the
Control System Designer, the Linear System Analyzer, and in any response plots that
you create from the MATLAB command line.
Properties refer to settings that are specific to an individual response plot. These include
the following:
The former are called app preferences, the latter toolbox preferences.
18-2
Property and Preferences Hierarchy
Although you can set plot properties in any response plot, you can use the Toolbox
Preferences Editor to set properties for any response plot that you generate. This figure
shows the inheritance hierarchy from toolbox preference to plot properties.
App Preferences
- Specific to app session Linear System
Control System
- Not saved to disk Analyzer
Designer
Plot Properties
- Specific to single plot Response Plot Response Plot Response Plot
- Not saved to disk
To edit:
• Toolbox preferences:
ctrlpref
18-3
18 Preliminaries
• App preferences:
18-4
Ways to Customize Plots
18-5
19
ctrlpref
19-2
Toolbox Preferences Editor
Units Pane
• Frequency
The default auto option uses rad/TimeUnit as the frequency units relative to the
system time units, where TimeUnit is the system time units specified in the
TimeUnit property of the system on frequency-domain plots. For multiple systems
with different time units, the units of the first system is used.
For the frequency axis, you can select logarithmic or linear scales.
• 'Hz'
• 'rad/s'
• 'rpm'
• 'kHz'
• 'MHz'
• 'GHz'
• 'rad/nanosecond'
• 'rad/microsecond'
• 'rad/millisecond'
19-3
19 Setting Toolbox Preferences
• 'rad/minute'
• 'rad/hour'
• 'rad/day'
• 'rad/week'
• 'rad/month'
• 'rad/year'
• 'cycles/nanosecond'
• 'cycles/microsecond'
• 'cycles/millisecond'
• 'cycles/hour'
• 'cycles/day'
• 'cycles/week'
• 'cycles/month'
• 'cycles/year'
• Magnitude — Decibels (dB) or absolute value (abs)
• Phase — Degrees or radians
• Time
The default auto option uses the time units specified in the TimeUnit property of the
system on the time- and frequency-domain plots. For multiple systems with different
time units, the units of the first system is used.
• 'nanoseconds'
• 'microseconds'
• 'milliseconds'
• 'seconds'
• 'minutes'
• 'hours'
• 'days'
• 'weeks'
19-4
Toolbox Preferences Editor
• 'months'
• 'years'
Style Pane
Use the Style pane to toggle grid visibility and set font preferences and axes foreground
colors for all plots you create. This figure shows the Style pane.
19-5
19 Setting Toolbox Preferences
• Colors — Specify the color vector to use for the axes foreground, which includes the
X-Y axes, grid lines, and tick labels. Use a three-element vector to represent red,
green, and blue (RGB) values. Vector element values can range from 0 to 1.
If you do not want to specify RGB values numerically, click the Select button to open
the Select Colors dialog box.
Options Pane
The Options pane has selections for time responses and frequency responses. This figure
shows the Options pane with default settings.
• Show settling time within xx% — Set the threshold of the settling time calculation
to any percentage from 0 to 100%. The default is 2%.
• Specify rise time from xx% to yy%— The standard definition of rise time is the time
it takes the signal to go from 10% to 90% of the final value. Specify any percentages
you like (from 0% to 100%), provided that the first value is smaller than the second.
• Only show magnitude above — Specify a lower limit for magnitude values in
response plots so that you can focus on a region of interest.
19-6
Toolbox Preferences Editor
• Wrap phase — Wrap the phase into the interval [–180º,180º). To wrap accumulated
phase at a different value, enter the value in the Branch field. For example, entering 0
causes the plot to wrap the phase into the interval [0º,360º).
K¥
(1 + Tz s) (1 + Tz s) L
1 2
(1 + Tp s) (1 + T p s)
1 2
where K is compensator DC gain, Tz1, Tz2, ..., are the zero time constants, and Tp1,
Tp2, ..., are the pole time constants.
19-7
19 Setting Toolbox Preferences
K¥
(1 + s w z ) (1 + s wz ) L
1 2
(1 + s w p ) (1 + s w p )
1 2
where K is compensator DC gain, ωz1, and ωz2, ... and ωp1, ωp2, ..., are the natural
frequencies of the zeros and poles, respectively.
( s + z1 ) ( s + z2 )
K¥
( s + p1 ) ( s + p2 )
where K is the overall compensator gain, and z1, z2, ... and p1, p2, ..., are the zero and
pole locations, respectively.
• Bode Options — By default, the Control System Designer shows the plant and
sensor poles and zeros as blue x's and o's, respectively. Clear this box to eliminate the
plant's poles and zeros from the Bode plot. Note that the compensator poles and zeros
(in red) will still appear.
19-8
20
20-2
Linear System Analyzer Preferences Editor
Units Pane
• Frequency
The default auto option uses rad/TimeUnit as the frequency units relative to the
system time units, where TimeUnit is the system time units specified in the
TimeUnit property of the system on frequency-domain plots. For multiple systems
with different time units, the units of the first system is used.
For the frequency axis, you can select logarithmic or linear scales.
• 'Hz'
• 'rad/s'
• 'rpm'
• 'kHz'
• 'MHz'
• 'GHz'
• 'rad/nanosecond'
20-3
20 Setting Tool Preferences
• 'rad/microsecond'
• 'rad/millisecond'
• 'rad/minute'
• 'rad/hour'
• 'rad/day'
• 'rad/week'
• 'rad/month'
• 'rad/year'
• 'cycles/nanosecond'
• 'cycles/microsecond'
• 'cycles/millisecond'
• 'cycles/hour'
• 'cycles/day'
• 'cycles/week'
• 'cycles/month'
• 'cycles/year'
• Magnitude — Decibels (dB) or absolute value (abs)
• Phase — Degrees or radians
• Time
The default auto option uses the time units specified in the TimeUnit property of the
system on the time- and frequency-domain plots. For multiple systems with different
time units, the units of the first system is used.
• 'nanoseconds'
• 'microseconds'
• 'milliseconds'
• 'seconds'
• 'minutes'
• 'hours'
20-4
Linear System Analyzer Preferences Editor
• 'days'
• 'weeks'
• 'months'
• 'years'
Style Pane
Use the Style pane to toggle grid visibility and set font preferences and axes foreground
colors for all plots in the Linear System Analyzer. This figure shows the Style pane.
• Grid — Activate grids for all plots in the Linear System Analyzer
• Fonts — Set the font size, weight (bold), and angle (italic). Select font sizes from the
menus or type any font-size values in the fields.
• Colors — Specify the color vector to use for the axes foreground, which includes the
X-Y axes, grid lines, and tick labels. Use a three-element vector to represent red,
green, and blue (RGB) values. Vector element values can range from 0 to 1.
• If you do not want to specify the RGB values numerically, press the Select button to
open the Select Colors window.
20-5
20 Setting Tool Preferences
Options Pane
The Options pane has selections for time responses and frequency responses.
• Show settling time within xx% — Set the threshold of the settling time calculation
to any percentage from 0 to 100%. The default is 2%.
• Specify rise time from xx% to yy%— The standard definition of rise time is the time
it takes the signal to go from 10% to 90% of the final value. Specify any percentages
you like (from 0% to 100%), provided that the first value is smaller than the second.
• Only show magnitude above — Specify a lower limit for magnitude values in
response plots so that you can focus on a region of interest.
20-6
Linear System Analyzer Preferences Editor
• Wrap phase — Wrap the phase into the interval [–180º,180º). To wrap accumulated
phase at a different value, enter the value in the Branch field. For example, entering 0
causes the plot to wrap the phase into the interval [0º,360º).
Parameters Pane
Use the Parameters pane, shown below, to specify input vectors for time and frequency
simulation.
The defaults are to generate time and frequency vectors for your plots automatically. You
can, however, override the defaults as follows:
• Time Vector:
• Define stop time — Specify the final time value for your simulation
• Define vector — Specify the time vector manually using equal-sized time steps
• Frequency Vector:
• Define range — Specify the bandwidth of your response. Whether it's in rad/sec or
Hz depends on the selection you made in the Units pane.
• Define vector — Specify the vector for your frequency values. Any real, positive,
strictly monotonically increasing vector is valid.
20-7
20 Setting Tool Preferences
See Also
Linear System Analyzer
More About
• “Linear System Analyzer Overview” on page 24-2
20-8
21
• “Customize Response Plots Using the Response Plots Property Editor” on page 21-2
• “Customizing Response Plots Using Plot Tools” on page 21-24
• “Customizing Response Plots from the Command Line” on page 21-28
• “Build GUI With Interactive Response-Plot Updates” on page 21-53
21 Customizing Response Plot Properties
Before looking at the Property Editor, open a step response plot using these commands.
load ltiexamples
step(sys_dc)
This creates a step plot. Right-click the plot, and select Properties from the context
menu. When you open the Property Editor, squares appear around the step response plot.
21-2
Customize Response Plots Using the Response Plots Property Editor
21-3
21 Customizing Response Plot Properties
In general, you can change the following properties of response plots. Only the Labels
and Limits panes are available when using the Property Editor with Simulink Design
Optimization software.
If you cannot customize units, the Property Editor displays that no units are available
for the selected plot.
• Styles in the Styles pane.
You can show a grid, adjust font properties, such as font size, bold, and italics, and
change the axes foreground color
21-4
Customize Response Plots Using the Response Plots Property Editor
These include peak response, settling time, phase and gain margins, etc. Plot options
change with each plot response type. The Property Editor displays only the options
that make sense for the selected response plot. For example, phase and gain margins
are not available for step responses.
As you make changes in the Property Editor, they display immediately in the response
plot. Conversely, if you make changes in a plot using right-click menus, the Property
Editor for that plot automatically updates. The Property Editor and its associated plot are
dynamically linked.
Labels Pane
To specify new text for plot titles and axis labels, type the new names in the field next to
the label you want to change. The label changes immediately as you type, so you can see
how the new text looks as you are typing.
21-5
21 Customizing Response Plot Properties
Limits Pane
Default values for the axes limits make sure that the maximum and minimum x and y
values are displayed. If you want to override the default settings, change the values in the
Limits fields. The Auto-Scale box automatically clears if you click a different field. The
new limits appear immediately in the response plot.
Units Pane
You can use the Units pane to change units in your response plot. The contents of this
pane depend on the response plot associated with the editor. Use the menus to toggle
between units.
21-6
Customize Response Plots Using the Response Plots Property Editor
21-7
21 Customizing Response Plot Properties
• 'Hz'
• 'rad/s'
• 'rpm'
• 'kHz'
• 'MHz'
• 'GHz'
• 'rad/nanosecond'
• 'rad/microsecond'
• 'rad/millisecond'
• 'rad/minute'
• 'rad/hour'
• 'rad/day'
• 'rad/week'
• 'rad/month'
• 'rad/year'
• 'cycles/nanosecond'
• 'cycles/microsecond'
• 'cycles/millisecond'
• 'cycles/hour'
• 'cycles/day'
• 'cycles/week'
• 'cycles/month'
21-8
Customize Response Plots Using the Response Plots Property Editor
• 'nanoseconds'
• 'microseconds'
• 'milliseconds'
• 'seconds'
• 'minutes'
• 'hours'
• 'days'
• 'weeks'
• 'months'
• 'years'
21-9
21 Customizing Response Plot Properties
• 'Hz'
• 'rad/s'
• 'rpm'
• 'kHz'
• 'MHz'
• 'GHz'
• 'rad/nanosecond'
• 'rad/microsecond'
• 'rad/millisecond'
• 'rad/minute'
• 'rad/hour'
• 'rad/day'
• 'rad/week'
• 'rad/month'
• 'rad/year'
• 'cycles/nanosecond'
• 'cycles/microsecond'
• 'cycles/millisecond'
• 'cycles/hour'
• 'cycles/day'
• 'cycles/week'
• 'cycles/month'
• 'cycles/year'
21-10
Customize Response Plots Using the Response Plots Property Editor
21-11
21 Customizing Response Plot Properties
• 'Hz'
• 'rad/s'
• 'rpm'
• 'kHz'
• 'MHz'
• 'GHz'
• 'rad/nanosecond'
• 'rad/microsecond'
• 'rad/millisecond'
• 'rad/minute'
• 'rad/hour'
• 'rad/day'
• 'rad/week'
• 'rad/month'
• 'rad/year'
• 'cycles/nanosecond'
• 'cycles/microsecond'
• 'cycles/millisecond'
• 'cycles/hour'
• 'cycles/day'
• 'cycles/week'
• 'cycles/month'
• 'cycles/year'
21-12
Customize Response Plots Using the Response Plots Property Editor
• 'nanoseconds'
• 'microseconds'
• 'milliseconds'
• 'seconds'
• 'minutes'
• 'hours'
• 'days'
• 'weeks'
• 'months'
• 'years'
• Frequency
• 'Hz'
• 'rad/s'
• 'rpm'
• 'kHz'
• 'MHz'
• 'GHz'
• 'rad/nanosecond'
• 'rad/microsecond'
21-13
21 Customizing Response Plot Properties
21-14
Customize Response Plots Using the Response Plots Property Editor
• 'Hz'
• 'rad/s'
• 'rpm'
• 'kHz'
• 'MHz'
• 'GHz'
• 'rad/nanosecond'
• 'rad/microsecond'
• 'rad/millisecond'
• 'rad/minute'
• 'rad/hour'
• 'rad/day'
• 'rad/week'
• 'rad/month'
• 'rad/year'
• 'cycles/nanosecond'
• 'cycles/microsecond'
• 'cycles/millisecond'
• 'cycles/hour'
• 'cycles/day'
• 'cycles/week'
• 'cycles/month'
• 'cycles/year'
21-15
21 Customizing Response Plot Properties
• 'nanoseconds'
• 'microseconds'
• 'milliseconds'
• 'seconds'
• 'minutes'
• 'hours'
• 'days'
• 'weeks'
• 'months'
• 'years'
Style Pane
Use the Style pane to toggle grid visibility and set font preferences and axes foreground
colors for response plots.
21-16
Customize Response Plots Using the Response Plots Property Editor
If you do not want to specify RGB values numerically, click the Select button to open
the Select Color dialog box.
21-17
21 Customizing Response Plot Properties
Options Pane
The Options pane enables you to customize response characteristics for plots. Each
response plot has its own set of characteristics and optional settings. When you change
the value in a field, press Enter on your keyboard to update the response plot.
21-18
Customize Response Plots Using the Response Plots Property Editor
21-19
21 Customizing Response Plot Properties
21-20
Customize Response Plots Using the Response Plots Property Editor
21-21
21 Customizing Response Plot Properties
subplot(2,1,1)
step(rss(2,1))
subplot(2,1,2)
impulse(rss(1,1))
After the figure window appears, double-click in the upper (step response) plot to activate
the Property Editor. A set of small squares appear around the step response, indicating
that it is the active plot for the editor. To switch to the lower (impulse response) plot, click
once in the impulse response plot region. The set of squares switches to the impulse
response, and the Property Editor updates as well.
21-22
See Also
See Also
More About
• “Ways to Customize Plots” on page 18-5
21-23
21 Customizing Response Plot Properties
Note To make other changes to response plots, see “Customize Response Plots Using the
Response Plots Property Editor” on page 21-2 and “Customizing Response Plots from the
Command Line” on page 21-28.
21-24
Customizing Response Plots Using Plot Tools
sys_mimo=rss(3,3,3);
stepplot(sys_mimo)
2 In the figure window, select View > Property Editor.
This action selects the response for the sys_mimo system and updates the Plot Tools
Property Editor to show the available editable properties for the response.
21-25
21 Customizing Response Plot Properties
Note The Plot Tools Property Editor applies changes to the response of the MIMO
system. Any change you make applies to all of the plotted lines in the figure.
Tip You can also change the properties of the response using the right-click menu
while in plot edit mode.
4 In the Property Editor – Waveform pane, select the color red.
21-26
Customizing Response Plots Using Plot Tools
This action changes the color of the response that represents the MIMO system to
red.
21-27
21 Customizing Response Plot Properties
You can customize any response plot from the command line. The command line is the
most efficient way to customize a large number of plots. For example, if you have a batch
job that produces many plots, you can change the x-axis units automatically for all the
plot with just a few lines of code.
You can use the Control System Toolbox application program interface (API) to customize
plotting options for response plots from the command line.
Note This section assumes some very basic familiarity with MATLAB graphics objects.
For more information, see “Graphics Objects” (MATLAB).
1 Obtain the plot handle, which is an identifier for the plot, using the API's plotting
syntax.
For example,
h = stepplot(sys)
For more information on obtaining plot handles, see “Obtaining Plot Handles” on
page 21-31.
2 Obtain the plot options handle, which is an identifier for all settable plot options. To
get a plot options handle for a given plot, type
p = getoptions(h);
21-28
Customizing Response Plots from the Command Line
For more information on obtaining plot options handles, see “Obtaining Plot Options
Handles” on page 21-32.
3 Use setoptions, along with the plot handle and the plot options handle, to access
and modify many plot options.
Note You can also use setoptions to customize plots using property/value pairs instead
of the plot options handle. Using property/value pairs shortens the procedure to one line
of code.
This example shows how to change the units of a Bode plot from rad/s to Hz.
Create a system and generate a Bode Plot of the system's response. The plot uses the
default units, rad/s.
21-29
21 Customizing Response Plot Properties
The bodeplot command returns a plot handle that you can use to change properties of
the plot.
p = getoptions(h);
p.FreqUnits = 'Hz';
setoptions(h,p)
21-30
Customizing Response Plots from the Command Line
For more examples of customizing plots from the command line, see “Examples of
Customizing Plots from the Command Line” on page 21-34.
21-31
21 Customizing Response Plot Properties
Function Plot
bodeplot Bode magnitude and phase
hsvplot Hankel singular values
impulseplot Impulse response
initialplot Initial condition
iopzplot Pole/zero maps for input/output pairs
lsimplot Time response to arbitrary inputs
nicholsplot Nichols chart
nyquistplot Nyquist
pzplot Pole/zero
rlocusplot Root locus
sigmaplot Singular values of the frequency response
stepplot Step response
To get a plot handle for any response plot, use the functions from the table. For example,
h = bodeplot(sys)
returns plot handle h (it also renders the Bode plot). Once you have this handle, you can
modify the plot properties using the setoptions and getoptions methods of the plot
object, in this case, a Bode plot handle.
Once you have the plot handle, you need the plot options handle, which is an identifier for
all the settable plot properties for a given response plot. There are two ways to create a
plot options handle:
21-32
Customizing Response Plots from the Command Line
Retrieving a Handle
The getoptions function retrieves a plot options handle from a plot handle.
If you specify a property name as an input argument, getoptions returns the property
value associated with the property name.
Creating a Handle
You can create a default plot options handle by using functions in the form of
<responseplot>options
For example,
p=bodeoptions;
instantiates a handle for Bode plots. See “Properties and Values Reference” on page 21-
38 for a list of default values.
If you want to set the default values to the Control System Toolbox default values, pass
cstprefs to the function. For example,
p = bodeoptions('cstprefs');
set the Bode plot property/value pairs to the Control System Toolbox default values.
This table lists the functions that create a plot options handle.
21-33
21 Customizing Response Plot Properties
Use
help <responseplot>options
to see a list of available property value pairs that you can modify. For example,
help bodeoptions
You can modify any of these parameters using setoptions. The next topic provides
examples of modifying various response plots.
See “Properties and Values Reference” on page 21-38 for a complete list of property/
value pairs for response plots.
For some examples, both dot notation and property/value pairs approaches are shown.
For all examples, use
21-34
Customizing Response Plots from the Command Line
Change the frequency units of a Bode plot from rad/s to Hz. To do so, extract the options
p from the plot handle, edit the options, and assign them back to the plot.
h = bodeplot(sys);
p = getoptions(h);
p.FreqUnits = 'Hz';
setoptions(h,p)
21-35
21 Customizing Response Plot Properties
You can use an existing plot options handle to customize a second plot:
h1 = bodeplot(sys);
p1 = getoptions(h1);
h2 = bodeplot(sys,p1);
or
h1 = bodeplot(sys);
h2 = bodeplot(sys2);
setoptions(h2,getoptions(h1))
p = bodeoptions;
p.FreqUnits ='Hz';
h = bodeplot(sys,p);
You can always use dot notation to assign values to properties, and change multiple plot
properties at once.
h1 = bodeplot(sys);
p1 = getoptions(h1);
p1.FreqUnits = 'Hz';
p1.Title.String = 'My Title';
setoptions(h1,p1)
21-36
Customizing Response Plots from the Command Line
ans =
Hz
21-37
21 Customizing Response Plot Properties
The following tables discuss property/value pairs common to all response plots.
Title
X Label
Y Label
21-38
Customizing Response Plots from the Command Line
Tick Label
21-39
21 Customizing Response Plot Properties
21-40
Customizing Response Plots from the Command Line
I/O Grouping
Input Labels
Output Labels
21-41
21 Customizing Response Plot Properties
Input/Output Visible
21-42
Customizing Response Plots from the Command Line
Bode Plots
• 'Hz'
• 'rad/s'
• 'rpm'
• 'kHz'
• 'MHz'
• 'GHz'
• 'rad/nanosecond'
• 'rad/microsecond'
• 'rad/millisecond'
• 'rad/minute'
• 'rad/hour'
• 'rad/day'
• 'rad/week'
• 'rad/month'
• 'rad/year'
• 'cycles/nanosecond'
• 'cycles/microsecond'
• 'cycles/millisecond'
• 'cycles/hour'
• 'cycles/day'
• 'cycles/week'
• 'cycles/month'
• 'cycles/year'
FreqScale log [linear | log]
MagUnits dB [db | abs]
MagScale linear [linear | log]
21-43
21 Customizing Response Plot Properties
21-44
Customizing Response Plots from the Command Line
21-45
21 Customizing Response Plot Properties
Nichols Plots
• 'Hz'
• 'rad/s'
• 'rpm'
• 'kHz'
• 'MHz'
• 'GHz'
• 'rad/nanosecond'
• 'rad/microsecond'
• 'rad/millisecond'
• 'rad/minute'
• 'rad/hour'
• 'rad/day'
• 'rad/week'
• 'rad/month'
• 'rad/year'
• 'cycles/nanosecond'
• 'cycles/microsecond'
• 'cycles/millisecond'
• 'cycles/hour'
• 'cycles/day'
• 'cycles/week'
• 'cycles/month'
• 'cycles/year'
MagUnits dB [dB | abs]
PhaseUnits deg [rad | deg]
MagLowerLimMode auto [auto | manual]
21-46
Customizing Response Plots from the Command Line
21-47
21 Customizing Response Plot Properties
Nyquist Charts
• 'Hz'
• 'rad/s'
• 'rpm'
• 'kHz'
• 'MHz'
• 'GHz'
• 'rad/nanosecond'
• 'rad/microsecond'
• 'rad/millisecond'
• 'rad/minute'
• 'rad/hour'
• 'rad/day'
• 'rad/week'
• 'rad/month'
• 'rad/year'
• 'cycles/nanosecond'
• 'cycles/microsecond'
• 'cycles/millisecond'
• 'cycles/hour'
• 'cycles/day'
• 'cycles/week'
• 'cycles/month'
• 'cycles/year'
MagUnits dB [dB | abs]
PhaseUnits deg [rad | deg]
ShowFullContour on [on | off]
21-48
Customizing Response Plots from the Command Line
Pole/Zero Maps
• 'Hz'
• 'rad/s'
• 'rpm'
• 'kHz'
• 'MHz'
• 'GHz'
• 'rad/nanosecond'
• 'rad/microsecond'
• 'rad/millisecond'
• 'rad/minute'
• 'rad/hour'
• 'rad/day'
• 'rad/week'
• 'rad/month'
• 'rad/year'
• 'cycles/nanosecond'
• 'cycles/microsecond'
• 'cycles/millisecond'
• 'cycles/hour'
• 'cycles/day'
• 'cycles/week'
• 'cycles/month'
• 'cycles/year'
21-49
21 Customizing Response Plot Properties
• 'nanoseconds'
• 'microseconds'
• 'milliseconds'
• 'seconds'
• 'minutes'
• 'hours'
• 'days'
• 'weeks'
• 'months'
• 'years'
21-50
Customizing Response Plots from the Command Line
Sigma Plots
• 'Hz'
• 'rad/s'
• 'rpm'
• 'kHz'
• 'MHz'
• 'GHz'
• 'rad/nanosecond'
• 'rad/microsecond'
• 'rad/millisecond'
• 'rad/minute'
• 'rad/hour'
• 'rad/day'
• 'rad/week'
• 'rad/month'
• 'rad/year'
• 'cycles/nanosecond'
• 'cycles/microsecond'
• 'cycles/millisecond'
• 'cycles/hour'
• 'cycles/day'
• 'cycles/week'
• 'cycles/month'
• 'cycles/year'
FreqScale log [linear | log]
MagUnits dB [dB | abs]
MagScale linear [linear | log]
21-51
21 Customizing Response Plot Properties
• 'nanoseconds'
• 'microseconds'
• 'milliseconds'
• 'seconds'
• 'minutes'
• 'hours'
• 'days'
• 'weeks'
• 'months'
• 'years'
21-52
Build GUI With Interactive Response-Plot Updates
The GUI in this example displays the step response of a second-order dynamic system of
fixed natural frequency. The GUI includes a slider that sets the system’s damping ratio. To
cause the response plot to reflect the slider setting, you must define a callback for the
slider. This callback uses the updateSystem command to update the plot with new
system data in response to changes in the slider setting.
Set the initial values of the second-order dynamic system and create the system model.
Create a figure for the GUI and configure the axes for displaying the step response.
f = figure;
ax = axes('Parent',f,'position',[0.13 0.39 0.77 0.54]);
h = stepplot(ax,sys);
setoptions(h,'XLim',[0,10],'YLim',[0,2]);
b = uicontrol('Parent',f,'Style','slider','Position',[81,54,419,23],...
'value',zeta, 'min',0, 'max',1);
bgcolor = f.Color;
bl1 = uicontrol('Parent',f,'Style','text','Position',[50,54,23,23],...
'String','0','BackgroundColor',bgcolor);
bl2 = uicontrol('Parent',f,'Style','text','Position',[500,54,23,23],...
'String','1','BackgroundColor',bgcolor);
bl3 = uicontrol('Parent',f,'Style','text','Position',[240,25,100,23],...
'String','Damping Ratio','BackgroundColor',bgcolor);
21-53
21 Customizing Response Plot Properties
Set the callback that updates the step response plot as the damping ratio slider is moved.
b.Callback = @(es,ed) updateSystem(h,tf(wn^2,[1,2*(es.Value)*wn,wn^2]));
This code sets the callback for the slider (identified as b) to an anonymous function. The
input arguments to this anonymous function, es and ed, are automatically passed to the
callback when the slider is used. es is the handle of the uicontrol that represents the
slider, and ed is the event data structure which the slider automatically passes to the
21-54
Build GUI With Interactive Response-Plot Updates
callback. You do not need to define these variables in the workspace or set their values.
(For more information about UI callbacks, see “Callback Definition” (MATLAB).)
The callback is a call to the updateSystem function, which replaces the plotted response
data with a response derived from a new transfer function. The callback uses the slider
data es.Value to define a second-order system whose damping ratio is the current value
of the slider.
Now that you have set the callback, move the slider. The displayed step response changes
as expected.
21-55
21 Customizing Response Plot Properties
See Also
uicontrol | updateSystem
21-56
See Also
Related Examples
• “Callback Definition” (MATLAB)
• “Write Callbacks for Apps Created Programmatically” (MATLAB)
21-57
22
B=[ .00729 0;
-0.475 0.00775;
0.153 0.143;
0 0];
C=[0 1 0 0;
0 0 0 1];
D=[0 0;
0 0];
sys = ss(A,B,C,D);
The following commands specify this state-space model as an LTI object and attach names
to the states, inputs, and outputs.
sys = ss(A,B,C,D,'statename',states,...
'inputname',inputs,...
'outputname',outputs);
You can display the LTI model sys by typing sys. This command produces the following
result.
22-2
Design Yaw Damper for Jet Transport
a =
beta yaw roll phi
beta -0.0558 -0.9968 0.0802 0.0415
yaw 0.598 -0.115 -0.0318 0
roll -3.05 0.388 -0.465 0
phi 0 0.0805 1 0
b =
rudder aileron
beta 0.00729 0
yaw -0.475 0.00775
roll 0.153 0.143
phi 0 0
c =
beta yaw roll phi
yaw 0 1 0 0
bank angle 0 0 0 1
d =
rudder aileron
yaw 0 0
bank angle 0 0
Continuous-time model.
The model has two inputs and two outputs. The units are radians for beta (sideslip angle)
and phi (bank angle) and radians/sec for yaw (yaw rate) and roll (roll rate). The rudder
and aileron deflections are in radians as well.
>> damp(sys)
pzmap(sys)
22-3
22 Design Case Studies
This model has one pair of lightly damped poles. They correspond to what is called the
"Dutch roll mode."
Suppose you want to design a compensator that increases the damping of these poles, so
that the resulting complex poles have a damping ratio ζ > 0.35 with natural frequency ωn
< 1 rad/sec. You can do this using the Control System Toolbox analysis tools.
Open-Loop Analysis
First, perform some open-loop analysis to determine possible control strategies. Start
with the time response (you could use step or impulse here).
impulse(sys)
22-4
Design Yaw Damper for Jet Transport
The impulse response confirms that the system is lightly damped. But the time frame is
much too long because the passengers and the pilot are more concerned about the
behavior during the first few seconds rather than the first few minutes. Next look at the
response over a smaller time frame of 20 seconds.
impulse(sys,20)
22-5
22 Design Case Studies
Look at the plot from aileron (input 2) to bank angle (output 2). To show only this plot,
right-click and choose I/O Selector, then click on the (2,2) entry. The I/O Selector should
look like this.
22-6
Design Yaw Damper for Jet Transport
The aircraft is oscillating around a nonzero bank angle. Thus, the aircraft is turning in
response to an aileron impulse. This behavior will prove important later in this case study.
Typically, yaw dampers are designed using the yaw rate as sensed output and the rudder
as control input. Look at the corresponding frequency response.
22-7
22 Design Case Studies
From this Bode diagram, you can see that the rudder has significant effect around the
lightly damped Dutch roll mode (that is, near ω = 1 rad/sec).
22-8
Design Yaw Damper for Jet Transport
This is the root locus for negative feedback and shows that the system goes unstable
almost immediately. If, instead, you use positive feedback, you may be able to keep the
system stable.
rlocus(-sys11)
sgrid
22-9
22 Design Case Studies
This looks better. By using simple feedback, you can achieve a damping ratio of ζ > 0.45.
Click on the blue curve and move the data marker to track the gain and damping values.
To achieve a 0.45 damping ratio, the gain should be about 2.85. This figure shows the
data marker with similar values.
22-10
Design Yaw Damper for Jet Transport
K = 2.85;
cl11 = feedback(sys11,-K); % Note: feedback assumes negative
% feedback by default
Plot the closed-loop impulse response for a duration of 20 seconds, and compare it to the
open-loop impulse response.
impulse(sys11,'b--',cl11,'r',20)
22-11
22 Design Case Studies
The closed-loop response settles quickly and does not oscillate much, particularly when
compared to the open-loop response.
Now close the loop on the full MIMO model and see how the response from the aileron
looks. The feedback loop involves input 1 and output 1 of the plant (use feedback with
index vectors selecting this input/output pair). At the MATLAB prompt, type
cloop = feedback(sys,-K,1,1);
damp(cloop) % closed-loop poles
impulse(sys,'b--',cloop,'r',20)
22-12
Design Yaw Damper for Jet Transport
The yaw rate response is now well damped, but look at the plot from aileron (input 2) to
bank angle (output 2). When you move the aileron, the system no longer continues to
bank like a normal aircraft. You have over-stabilized the spiral mode. The spiral mode is
typically a very slow mode and allows the aircraft to bank and turn without constant
aileron input. Pilots are used to this behavior and will not like your design if it does not
allow them to fly normally. This design has moved the spiral mode so that it has a faster
frequency.
s
H ( s) =
s +a
The washout filter places a zero at the origin, which constrains the spiral mode pole to
remain near the origin. We choose α = 0.2 for a time constant of five seconds and use the
22-13
22 Design Case Studies
root locus technique to select the filter gain H. First specify the fixed part s/(s + α) of the
washout by
H = zpk(0,-0.2,1);
Connect the washout in series with the design model sys11 (relation between input 1 and
output 1) to obtain the open-loop model
oloop = H * sys11;
rlocus(-oloop)
sgrid
Create and drag a data marker around the upper curve to locate the maximum damping,
which is about ζ = 0.3.
This figure shows a data marker at the maximum damping ratio; the gain is approximately
2.07.
22-14
Design Yaw Damper for Jet Transport
K = 2.07;
cl11 = feedback(oloop,-K);
impulse(cl11,20)
22-15
22 Design Case Studies
The response settles nicely but has less damping than your previous design. Finally, you
can verify that the washout filter has fixed the spiral mode problem. First form the
complete washout filter kH(s) (washout + gain).
WOF = -K * H;
Then close the loop around the first I/O pair of the MIMO model sys and simulate the
impulse response.
cloop = feedback(sys,WOF,1,1);
22-16
Design Yaw Damper for Jet Transport
The bank angle response (output 2) due to an aileron impulse (input 2) now has the
desired nearly constant behavior over this short time frame. To inspect the response more
closely, use the I/O Selector in the right-click menu to select the (2,2) I/O pair.
22-17
22 Design Case Studies
Although you did not quite meet the damping specification, your design has increased the
damping of the system substantially and now allows the pilot to fly the aircraft normally.
22-18
LQG Regulation: Rolling Mill Case Study
milldemo
This shape is impressed by two pairs of rolling cylinders (one per axis) positioned by
hydraulic actuators. The gap between the two cylinders is called the roll gap.
22-19
22 Design Case Studies
The objective is to maintain the beam thickness along the x- and y-axes within the quality
assurance tolerances. Variations in output thickness can arise from the following:
Feedback control is necessary to reduce the effect of these disturbances. Because the roll
gap cannot be measured close to the mill stand, the rolling force is used instead for
feedback.
The input thickness disturbance is modeled as a low pass filter driven by white noise. The
eccentricity disturbance is approximately periodic and its frequency is a function of the
rolling speed. A reasonable model for this disturbance is a second-order bandpass filter
driven by white noise.
This leads to the following generic model for each axis of the rolling process.
22-20
LQG Regulation: Rolling Mill Case Study
The measured rolling force variation f is a combination of the incremental force delivered
by the hydraulic actuator and of the disturbance forces due to eccentricity and input
thickness variation. Note that:
• The outputs of H(s), Fe(s), and Fi(s) are the incremental forces delivered by each
component.
• An increase in hydraulic or eccentricity force reduces the output thickness gap δ.
• An increase in input thickness increases this gap.
22-21
22 Design Case Studies
2.4 ¥ 108
H x ( s) =
s2 + 72 s + 902
10 4
Fix ( s) =
s + 0 .05
3 ¥ 104 s
Fex ( s) =
s2 + 0 .1 25 s + 62
gx = 10-6
7.8 ¥ 108
H y ( s) =
s2 + 71 s + 88 2
2 ¥ 104
Fiy (s) =
s + 0 .05
10 5 s
Fey ( s) =
s2 + 0 .1 9 s + 9 .4 2
g y = 0 .5 ¥ 10-6
Start with the x-axis. First specify the model components as transfer function objects.
22-22
LQG Regulation: Rolling Mill Case Study
Next build the open-loop model shown in “Process and Disturbance Models” on page 22-
19. You could use the function connect for this purpose, but it is easier to build this
model by elementary append and series connections.
Note To obtain minimal state-space realizations, always convert transfer function models
to state space before connecting them. Combining transfer functions and then converting
to state space may produce nonminimal state-space models.
The variable Px now contains an open-loop state-space model complete with input and
output names.
Px.inputname
ans =
'u-x'
'w-ex'
'w-ix'
Px.outputname
ans =
'x-gap'
'x-force'
The second output 'x-force' is the rolling force measurement. The LQG regulator will
use this measurement to drive the hydraulic actuator and reduce disturbance-induced
thickness variations δx.
22-23
22 Design Case Studies
2 Design a Kalman filter that estimates the state vector given the force measurements
'x-force'.
The performance criterion J(ux) penalizes low and high frequencies equally. Because low-
frequency variations are of primary concern, eliminate the high-frequency content of δx
with the low-pass filter 30/(s + 30) and use the filtered value in the LQ performance
criterion.
Note lqry expects all inputs to be commands and all outputs to be measurements. Here
the command 'u-x' and the measurement 'x-gap*' (filtered gap) are the first input
and first output of Pxdes. Hence, use the syntax Pxdes(1,1) to specify just the I/O
relation between 'u-x' and 'x-gap*'.
Next, design the Kalman estimator with the function kalman. The process noise
Èw ˘
wx = Í ex ˙
Î wix ˚
has unit covariance by construction. Set the measurement noise covariance to 1000 to
limit the high frequency gain, and keep only the measured output 'x-force' for
estimator design.
estx = kalman(Pxdes(2,:),eye(2),1000)
22-24
LQG Regulation: Rolling Mill Case Study
Finally, connect the state-feedback gain kx and state estimator estx to form the LQG
regulator.
Regx = lqgreg(estx,kx)
Let's look at the regulator Bode response between 0.1 and 1000 rad/sec.
h = bodeplot(Regx,{0.1 1000})
setoptions(h,'PhaseMatching','on')
The phase response has an interesting physical interpretation. First, consider an increase
in input thickness. This low-frequency disturbance boosts both output thickness and
rolling force. Because the regulator phase is approximately 0o at low frequencies, the
feedback loop then adequately reacts by increasing the hydraulic force to offset the
thickness increase. Now consider the effect of eccentricity. Eccentricity causes
fluctuations in the roll gap (gap between the rolling cylinders). When the roll gap is
minimal, the rolling force increases and the beam thickness diminishes. The hydraulic
force must then be reduced (negative force feedback) to restore the desired thickness.
22-25
22 Design Case Studies
This is exactly what the LQG regulator does as its phase drops to -180o near the natural
frequency of the eccentricity disturbance (6 rad/sec).
Next, compare the open- and closed-loop responses from disturbance to thickness gap.
Use feedback to close the loop. To help specify the feedback connection, look at the I/O
names of the plant Px and regulator Regx.
Px.inputname
ans =
'u-x'
'w-ex'
'w-ix'
Regx.outputname
ans =
'u-x'
Px.outputname
ans =
'x-gap'
'x-force'
Regx.inputname
ans =
'x-force'
This indicates that you must connect the first input and second output of Px to the
regulator.
clx = feedback(Px,Regx,1,2,+1) % Note: +1 for positive feedback
You are now ready to compare the open- and closed-loop Bode responses from
disturbance to thickness gap.
h = bodeplot(Px(1,2:3),'--',clx(1,2:3),'-',{0.1 100})
setoptions(h,'PhaseMatching','on')
22-26
LQG Regulation: Rolling Mill Case Study
The dashed lines show the open-loop response. Note that the peak gain of the
eccentricity-to-gap response and the low-frequency gain of the input-thickness-to-gap
response have been reduced by about 20 dB.
Finally, use lsim to simulate the open- and closed-loop time responses to the white noise
inputs wex and wix. Choose dt=0.01 as sample time for the simulation, and derive
equivalent discrete white noise inputs for this sampling rate.
dt = 0.01
t = 0:dt:50 % time samples
lsim(Px(1,2:3),':',clx(1,2:3),'-',wx,t)
Right-click on the plot that appears and select Show Input to turn off the display of the
input.
22-27
22 Design Case Studies
The dotted lines correspond to the open-loop response. In this simulation, the LQG
regulation reduces the peak thickness variation by a factor 4.
22-28
LQG Regulation: Rolling Mill Case Study
% Form SISO LQG regulator for y-axis and close the loop
Regy = lqgreg(esty,ky)
cly = feedback(Py,Regy,1,2,+1)
Compare the open- and closed-loop response to the white noise input disturbances.
dt = 0.01
t = 0:dt:50
wy = sqrt(1/dt) * randn(2,length(t))
lsim(Py(1,2:3),':',cly(1,2:3),'-',wy,t)
Right-click on the plot that appears and select Show Input to turn off the display of the
input.
22-29
22 Design Case Studies
The dotted lines correspond to the open-loop response. The simulation results are
comparable to those for the x-axis.
22-30
LQG Regulation: Rolling Mill Case Study
Accordingly, the thickness gaps and rolling forces are related to the outputs d x , f x ,… of
the x- and y-axis models by
22-31
22 Design Case Studies
Èd x ˘ È1 0 0 g yx g x ˘ Èd x ˘
Í ˙ Í0 1 g g ˙Í ˙
d Í 0 ˙ Íd y ˙
Í ˙= y xy y
Í f ˙ Í0 0 Í ˙
1 - g yx ˙˙ Í f x ˙
Í x˙ Í
ÍÎ f x ˙˚ ÍÎ0 0 - gxy 1 ˙ Íf ˙
14444244443˚ Î y ˚
cross-coupling matrix
Let's see how the previous "decoupled" LQG design fares when cross-coupling is taken
into account. To build the two-axes model, shown above, append the models Px and Py for
the x- and y-axes.
P = append(Px,Py)
For convenience, reorder the inputs and outputs so that the commands and thickness
gaps appear first.
P = P([1 3 2 4],[1 4 2 3 5 6])
P.outputname
ans =
'x-gap'
'y-gap'
'x-force'
'y-force'
You are now ready to simulate the open- and closed-loop responses to the driving white
noises wx (for the x-axis) and wy (for the y-axis).
wxy = [wx ; wy]
lsim(Pc(1:2,3:6),':',cl(1:2,3:6),'-',wxy,t)
22-32
LQG Regulation: Rolling Mill Case Study
Right-click on the plot that appears and select Show Input to turn off the display of the
input.
The response reveals a severe deterioration in regulation performance along the x-axis
(the peak thickness variation is about four times larger than in the simulation without
cross-coupling). Hence, designing for one loop at a time is inadequate for this level of
cross-coupling, and you must perform a joint-axis MIMO design to correctly handle
coupling effects.
ans =
'u-x'
'u-y'
'w-ex'
22-33
22 Design Case Studies
'w-ix'
'w_ey'
'w_iy'
P.outputname
ans =
'x-gap'
'y-gap'
'x-force'
'y-force'
As earlier, add low-pass filters in series with the 'x-gap' and 'y-gap' outputs to
penalize only low-frequency thickness variations.
Pdes = append(lpf,lpf,eye(2)) * Pc
Pdes.outputn = Pc.outputn
Next, design the LQ gain and state estimator as before (there are now two commands and
two measurements).
k = lqry(Pdes(1:2,1:2),eye(2),1e-4*eye(2)) % LQ gain
est = kalman(Pdes(3:4,:),eye(4),1e3*eye(2)) % Kalman estimator
The resulting LQG regulator RegMIMO has two inputs and two outputs.
RegMIMO.inputname
ans =
'x-force'
'y-force'
RegMIMO.outputname
ans =
'u-x'
'u-y'
sigma(RegMIMO)
22-34
LQG Regulation: Rolling Mill Case Study
Next, plot the open- and closed-loop time responses to the white noise inputs (using the
MIMO LQG regulator for feedback).
Right-click on the plot that appears and select Show Input to turn off the display of the
input.
22-35
22 Design Case Studies
The MIMO design is a clear improvement over the separate SISO designs for each axis. In
particular, the level of x/y thickness variation is now comparable to that obtained in the
decoupled case. This example illustrates the benefits of direct MIMO design for
multivariable systems.
References
[1] Grimble, M.J., Robust Industrial Control: Optimal Design Approach for Polynomial
Systems, Prentice Hall, 1994, p. 261 and pp. 443-456.
22-36
Kalman Filtering
Kalman Filtering
This case study illustrates Kalman filter design and simulation. Both steady-state and
time-varying Kalman filters are considered.
This case study illustrates Kalman filter design and simulation. Both steady-state and
time-varying Kalman filters are considered.
B = [-0.3832;
0.5919;
0.5191];
C = [1 0 0];
The equations of the steady-state Kalman filter for this problem are given as follows.
• Measurement update:
• Time update:
In these equations:
22-37
22 Design Case Studies
Given the current estimate , the time update predicts the state value at the next
sample n + 1 (one-step-ahead predictor). The measurement update then adjusts this
prediction based on the new measurement . The correction term is a function of
the innovation, that is, the discrepancy between the measured and predicted values of
. This discrepancy is given by:
The innovation gain M is chosen to minimize the steady-state covariance of the estimation
error, given the noise covariances:
You can combine the time and measurement update equations into one state-space model,
the Kalman filter:
This filter generates an optimal estimate of . Note that the filter state is
.
Steady-State Design
You can design the steady-state Kalman filter described above with the function kalman.
First specify the plant model with the process noise:
Here, the first expression is the state equation, and the second is the measurement
equation.
The following command specifies this plant model. The sample time is set to -1, to mark
the model as discrete without specifying a sample time.
22-38
Kalman Filtering
Q = 1;
R = 1;
[kalmf,L,P,M] = kalman(Plant,Q,R);
This command returns a state-space model kalmf of the filter, as well as the innovation
gain M.
M =
0.3798
0.0817
-0.2570
The inputs of kalmf are u and , and. The outputs are the plant output and the state
estimates, and .
Because you are interested in the output estimate , select the first output of kalmf and
discard the rest.
kalmf = kalmf(1,:);
To see how the filter works, generate some input data and random noise and compare the
filtered response with the true response y. You can either generate each response
separately, or generate both together. To simulate each response separately, use lsim
with the plant alone first, and then with the plant and filter hooked up together. The joint
simulation alternative is detailed next.
The block diagram below shows how to generate both true and filtered outputs.
22-39
22 Design Case Studies
You can construct a state-space model of this block diagram with the functions parallel
and feedback. First build a complete plant model with u, w, v as inputs, and y and
(measurements) as outputs.
a = A;
b = [B B 0*B];
c = [C;C];
d = [0 0 0;0 0 1];
P = ss(a,b,c,d,-1,'inputname',{'u' 'w' 'v'},'outputname',{'y' 'yv'});
Then use parallel to form the parallel connection of the following illustration.
sys = parallel(P,kalmf,1,1,[],[]);
Finally, close the sensor loop by connecting the plant output to filter input with
positive feedback.
22-40
Kalman Filtering
The resulting simulation model has w, v, u as inputs, and y and as outputs. View the
InputName and OutputName properties to verify.
SimModel.InputName
ans =
{'w'}
{'v'}
{'u'}
SimModel.OutputName
ans =
{'y' }
{'y_e'}
You are now ready to simulate the filter behavior. Generate a sinusoidal input u and
process and measurement noise vectors w and v.
t = [0:100]';
u = sin(t/5);
n = length(t);
rng default
w = sqrt(Q)*randn(n,1);
v = sqrt(R)*randn(n,1);
[out,x] = lsim(SimModel,[w,v,u]);
22-41
22 Design Case Studies
subplot(211), plot(t,y,'--',t,ye,'-'),
xlabel('No. of samples'), ylabel('Output')
title('Kalman filter response')
subplot(212), plot(t,y-yv,'-.',t,y-ye,'-'),
xlabel('No. of samples'), ylabel('Error')
The first plot shows the true response y (dashed line) and the filtered output (solid
line). The second plot compares the measurement error (dash-dot) with the estimation
error (solid). This plot shows that the noise level has been significantly reduced. This is
22-42
Kalman Filtering
MeasErrCov =
0.9992
EstErrCov =
0.4944
The time-varying Kalman filter is a generalization of the steady-state filter for time-
varying systems or LTI systems with nonstationary noise covariance.
• Measurement update:
• Time update:
22-43
22 Design Case Studies
For simplicity, the subscripts indicating the time dependence of the state-space matrices
have been dropped.
Given initial conditions and , you can iterate these equations to perform the
filtering. You must update both the state estimates and error covariance matrices
at each time sample.
Time-Varying Design
To implement these filter recursions, first generate noisy output measurements. Use the
process noise w and measurement noise v generated previously.
sys = ss(A,B,C,0,-1);
y = lsim(sys,u+w);
yv = y + v;
for i = 1:length(t)
% Measurement update
Mn = P*C'/(C*P*C'+R);
x = x + Mn*(yv(i)-C*x); % x[n|n]
P = (eye(3)-Mn*C)*P; % P[n|n]
ye(i) = C*x;
22-44
Kalman Filtering
errcov(i) = C*P*C';
% Time update
x = A*x + B*u(i); % x[n+1|n]
P = A*P*A' + B*Q*B'; % P[n+1|n]
end
subplot(211), plot(t,y,'--',t,ye,'-')
title('Time-varying Kalman filter response')
xlabel('No. of samples'), ylabel('Output')
subplot(212), plot(t,y-yv,'-.',t,y-ye,'-')
xlabel('No. of samples'), ylabel('Output')
22-45
22 Design Case Studies
The first plot shows the true response y (dashed line) and the filtered response (solid
line). The second plot compares the measurement error (dash-dot) with the estimation
error (solid).
The time-varying filter also estimates the covariance errcov of the estimation error
at each sample. Plot it to see if your filter reached steady state (as you expect with
stationary input noise).
subplot(211)
plot(t,errcov), ylabel('Error covar')
From this covariance plot, you can see that the output covariance did indeed reach a
steady state in about five samples. From then on, your time-varying filter has the same
performance as the steady-state version.
22-46
Kalman Filtering
Compare with the estimation error covariance derived from the experimental data:
EstErr = y - ye;
EstErrCov = sum(EstErr.*EstErr)/length(EstErr)
EstErrCov =
0.4934
This value is smaller than the theoretical value errcov and close to the value obtained
for the steady-state design.
Finally, note that the final value and the steady-state value M of the innovation gain
matrix coincide.
Mn
Mn =
0.3798
0.0817
-0.2570
M =
0.3798
0.0817
-0.2570
22-47
22 Design Case Studies
Bibliography
[1] Grimble, M.J., Robust Industrial Control: Optimal Design Approach for Polynomial
Systems, Prentice Hall, 1994, p. 261 and pp. 443-456.
See Also
More About
• “Kalman Filter Design”
22-48
23
Reliable Computations
23 Reliable Computations
Working with poorly scaled models can cause your model a severe loss of accuracy and
puzzling results. An example of a poorly scaled model is a dynamic system with two states
in the state vector that have units of light years and millimeters. Such disparate units may
introduce both very large and very small entries into the A matrix. Over the course of
computations, this mix of small and large entries in the matrix could destroy important
characteristics of the model and lead to incorrect results.
For more information on the harmful affects of a poorly scaled model, see “Scaling State-
Space Models to Maximize Accuracy”.
In general, you do not have to perform your own scaling when using the Control System
Toolbox software. The algorithms automatically scale your model to prevent loss of
accuracy. The automated scaling chooses a frequency range to maximize accuracy based
on the dominant dynamics of the model.
In most cases, automated scaling provides high accuracy without your intervention. For
some models with dynamics spanning a wide frequency range, however, it is impossible to
achieve good accuracy at all frequencies and some tradeoff of accuracy in different
frequency bands is necessary. In such cases, a warning alerts you of potential
inaccuracies. If you receive this warning, evaluate the tradeoffs and consider manually
adjusting the frequency interval where you most need high accuracy. For information on
how to manually scale your model, see “Manually Scale Your Model” on page 23-3.
23-2
Scaling State-Space Models
Note For models with satisfactory scaling, you can bypass automated scaling in the
Control System Toolbox software. To do so, set the Scaled property of your state-space
model to 1 (true). For information on how to set this property, see the set reference
page.
The prescale command includes a Scaling Tool, which you can use to visualize accuracy
tradeoffs and to adjust the frequency interval where this accuracy is maximized.
To scale your model using the Scaling Tool, perform the following steps:
For an example of using the Scaling Tool on a real model, see “Scaling State-Space
Models to Maximize Accuracy”.
For more information about scaling models from the command line, see the prescale
reference page.
To open the Scaling Tool for a state-space model named sys, type
prescale(sys)
23-3
23 Reliable Computations
• The Frequency Response Gain plot helps you determine the frequency band over
which you want to maximize scaling.
For SISO systems, this plot shows the gain of your model. For MIMO systems, the plot
shows the principle gain (largest singular value) of your model.
• The Frequency Response Accuracy plot allows you to view the accuracy tradeoffs
for your model when maximizing accuracy in a particular frequency bands.
23-4
Scaling State-Space Models
When you compute some model characteristics, such as the frequency response or the
system zeros, the software produces the exact answer for some perturbation of the
model you specified. The relative accuracy is a measure of the worst-case relative gap
between the frequency response of the original and perturbed models. The
perturbation accounts for rounding errors during calculation. Any relative accuracy
value greater than 1 implies poor accuracy.
Tip If the blue Scaled curve is close to the brown Pointwise Optimal curve in a
particular frequency band, you already have the best possible accuracy in that
frequency band.
You can change the limits of the plot axis to view a particular frequency band of interest
in the Scaling Tool. To view a particular frequency band, specify the band in the Show
response in the frequency band fields.
This action updates the frequency axis of the Scaling tool to show the specified frequency
band.
Tip To return to the default display, select the Auto check box.
To adjust the frequency band where you want maximum accuracy, set a new frequency
band in the Maximize accuracy in the frequency band fields. You can visualize
accuracy tradeoffs by trying out different frequency bands and viewing the resulting
relative accuracy across the frequency band of interest.
Note You can use the Frequency Response Gain plot, which plots the gain of your
model, to view the dynamics in your model to help determine the frequency band to
maximize accuracy.
Each time you specify a new frequency band, the Frequency Response Accuracy plot
updates with the result of the new scaling. Compare the Scaled curve (blue) to the
Pointwise Optimal curve (brown) to determine where the new scaling is nearly optimal
and where you need more accuracy.
23-5
23 Reliable Computations
Tip To return to the default scaling, select the Auto check box.
When you find a good scaling for your model, save the scaled model as follows:
2 In the Save to Workspace dialog box, verify that any of the following items you want
to save are selected, and specify variable names for these items.
• Scaled model
• Scaling information, including:
• Scaling factors
• Frequencies used to test accuracy
• Relative accuracy at each test frequency
For details about the scaling information, see the prescale reference page.
3 Click OK.
This action sets the State-Space (@ss) object Scaled property of your model to true.
When you set this property to True, the Control System Toolbox algorithms skip the
automated scaling of the model.
23-6
24
The easiest way to work with the Linear System Analyzer is to use the right-click
menus. For example, type
load ltiexamples
linearSystemAnalyzer(sys_dc)
24-2
Linear System Analyzer Overview
The Linear System Analyzer can display up to six different plot types simultaneously,
including step, impulse, Bode (magnitude and phase or magnitude only), Nyquist, Nichols,
sigma, pole/zero, and I/O pole/zero.
For examples of how to use the Linear System Analyzer, see “Linear Analysis Using the
Linear System Analyzer”. For more detailed information about Linear System Analyzer
menus and options, see:
• “Using the Right-Click Menu in the Linear System Analyzer” on page 24-4
• “Importing, Exporting, and Deleting Models in the Linear System Analyzer” on page
24-9
• “Selecting Response Types” on page 24-12
• “Analyzing MIMO Models” on page 24-17
• “Customizing the Linear System Analyzer” on page 24-22
24-3
24 Linear System Analyzer
In addition to right-click menus, all response plots include data markers. These allow you
to scan the plot data, identify key data, and determine the source system for a given plot.
The next sections describe the menu items for each of the eight plot types.
Step Response
24-4
Using the Right-Click Menu in the Linear System Analyzer
• Peak Response — The largest deviation from the steady-state value of the step
response
• Settling Time — The time required for the step response to decline and stay at 5% of
its final value
• Rise Time — The time require for the step response to rise from 10% to 90% of its
final value
• Steady-State — The final value for the step response
Note You can change the definitions of settling time and rise time using the Options
pane of the “Toolbox Preferences Editor” on page 19-2, the “Linear System Analyzer
Preferences Editor” on page 20-2, or the Property editor on page 21-2.
Impulse Response
The Linear System Analyzer can display the following information in the impulse
response:
• Peak Response — The maximum positive deviation from the steady-state value of the
impulse response
• Settling Time — The time required for the step response to decline and stay at 5% of
its final value
Bode Diagram
Bode plots the open-loop Bode phase and magnitude diagrams for the model.
24-5
24 Linear System Analyzer
The Linear System Analyzer can display the following information in the Bode diagram:
• Peak Response — The maximum value of the Bode magnitude plot over the specified
region
• Stability Margins (Minimum Crossing) — The minimum phase and gain margins.
The gain margin is defined to the gain (in dB) when the phase first crosses -180°. The
phase margin is the distance, in degrees, of the phase from -180° when the gain
magnitude is 0 dB.
• Stability Margins (All Crossings) — Display all stability margins
Bode Magnitude
Bode Magnitude plots the Bode magnitude diagram for the model.
The Linear System Analyzer can display the following information in the Bode
magnitude diagram:
• Peak Response, which is the maximum value of the Bode magnitude in decibels (dB),
over the specified range of the diagram.
• Stability (Minimum Crossing) — The minimum gain margins. The gain margin is
defined to the gain (in dB) when the phase first crosses -180°.
• Stability (All Crossings) — Display all gain stability margins
24-6
Using the Right-Click Menu in the Linear System Analyzer
Nyquist Diagrams
The Linear System Analyzer can display the following types of information in the
Nyquist diagram:
• Peak Response — The maximum value of the Nyquist diagram over the specified
region
• Stability (Minimum Crossing) — The minimum gain and phase margins for the
Nyquist diagram. The gain margin is the distance from the origin to the phase
crossover of the Nyquist curve. The phase crossover is where the curve meets the real
axis. The phase margin is the angle subtended by the real axis and the gain crossover
on the circle of radius 1.
• Stability (All Crossings) — Display all gain stability margins
Nichols Charts
The Linear System Analyzer can display the following types of information in the
Nichols chart:
• Peak Response — The maximum value of the Nichols chart in the plotted region.
• Stability (Minimum Crossing) — The minimum gain and phase margins for the
Nichols chart.
24-7
24 Linear System Analyzer
Singular Values
The Linear System Analyzer can display the Peak Response, which is the largest
magnitude of the Singular Values curve over the plotted region.
Pole/Zero plots the poles and zeros of the model with `x' for poles and `o' for zeros. I/O
Pole/Zero plots the poles and zeros of I/O pairs.
See Also
Linear System Analyzer
Related Examples
• “Joint Time-Domain and Frequency-Domain Analysis” on page 7-40
More About
• “Linear System Analyzer Overview” on page 24-2
24-8
Importing, Exporting, and Deleting Models in the Linear System Analyzer
Importing Models
To import models into the Linear System Analyzer, select File > Import. The Import
System Data dialog box opens, as shown below.
Use the Import System Data dialog box to import LTI models into or from the Linear
System Analyzer workspace.
To import a model:
• Click on the desired model in the LTI Browser List. To perform multiple selections:
Note that the LTI Browser lists only the LTI models in the MATLAB workspace.
Alternatively, you can directly import a model into the Linear System Analyzer using the
linearSystemAnalyzer function, as in
linearSystemAnalyzer({'step','bode'},modelname)
24-9
24 Linear System Analyzer
See the Linear System Analyzer reference page for more information.
Exporting Models
Use Export in the File menu to open the Linear System Analyzer Export window,
shown below.
The Linear System Analyzer Export window lists all the models with responses
currently displayed in your Linear System Analyzer. You can export models back to the
MATLAB workspace or to disk.
To export single or multiple models, follow the steps described in the importing models
section above. To save your models to disk in a MAT-file, choose Export to Disk.
Deleting Models
To remove models from the Linear System Analyzer workspace, select Edit > Delete
Systems. The Linear System Analyzer Delete dialog box opens.
24-10
See Also
To delete a model:
• Click on the desired model in the Model list. To perform multiple selections:
See Also
Linear System Analyzer
More About
• “Linear System Analyzer Overview” on page 24-2
24-11
24 Linear System Analyzer
To change the response plot, select the new plot type from the Plot Type submenu. The
Linear System Analyzer automatically displays the new response plot.
24-12
Selecting Response Types
Use the radio buttons to select the number of plots you want displayed in your Linear
System Analyzer. For each plot, select a response type from the menus located on the
right-hand side of the window.
It's possible to configure a single Linear System Analyzer to contain up to six response
plots.
24-13
24 Linear System Analyzer
Available response plots include: step, impulse, Bode (magnitude and phase, or
magnitude only), Nyquist, Nichols, sigma, pole/zero maps, and I/O pole/zero maps.
24-14
Selecting Response Types
The Line Styles editor is particularly useful when you have multiple systems imported.
You can use it change line colors, add and rearrange markers, and alter line styes (solid,
dashed, and so on).
You can use the Linestyle Preferences window to customize the appearance of the
response plots by specifying:
Each Linear System Analyzer has its own Linestyle Preferences window.
Setting Preferences
You can use the "Distinguish by" matrix (the top half of the window) to specify the line
property that will vary throughout the response plots. You can group multiple plot curves
by systems, inputs, outputs, or channels (individual input/output relationships). Note that
the Line Styles editor uses radio buttons, which means that you can only assign one
property setting for each grouping (system, input, etc.).
24-15
24 Linear System Analyzer
Ordering Properties
The Order field allows you to change the default property order used when applying the
different line properties. You can reorder the colors, markers, and linestyles (e.g., solid or
dashed).
To change any of the property orders, click the up or down arrow button to the left of the
associated property list to move the selected property up or down in the list.
See Also
Linear System Analyzer
Related Examples
• “Joint Time-Domain and Frequency-Domain Analysis” on page 7-40
More About
• “Linear System Analyzer Overview” on page 24-2
24-16
Analyzing MIMO Models
sys_mimo=stack(1,rss(3,3,3),rss(3,3,3));
linearSystemAnalyzer(sys_mimo);
A set of 9 plots appears, one from each input to each output, each showing the step
responses of the corresponding I/Os of both models in the array.
24-17
24 Linear System Analyzer
Array Selector
If you import an LTI model array into the Linear System Analyzer, Array Selector
appears as an option in the right-click menu. Selecting this option opens the Model
Selector for LTI Arrays, shown below.
You can use this window to include or exclude models within the LTI array using various
criteria.
Arrays
Select the LTI array for model selection using the Arrays list.
Selection Criteria
There are two selection criteria. The default, Index into Dimensions, allows you to
include or exclude specified indices of the LTI Array. Select systems from the Selection
Criterion Setup section of the dialog box. Then, Specify whether to show or hide the
systems using the pull-down menu below the Setup lists.
The second criterion is Bound on Characteristics. Selecting this options causes the
Model Selector to reconfigure. The reconfigured window is shown below
24-18
Analyzing MIMO Models
Use this option to select systems for inclusion or exclusion in your Linear System
Analyzer based on their time response characteristics. The panel directly above the
buttons describes how to set the inclusion or exclusion criteria based on which selection
criteria you select from the reconfigured Selection Criteria Setup panel.
For example, if you select Outputs, the step plot reconfigures into 3 plots, grouping all
the outputs together on each plot. Each plot now displays the responses from one of the
inputs to all of the MIMO system’s outputs, for all of the models in the array.
24-19
24 Linear System Analyzer
Selecting None returns to the default configuration, where all I/O pairs are displayed
individually.
24-20
See Also
This window automatically configures to the number of I/O pairs in your MIMO system.
You can select:
Using these options, you can inspect individual I/O pairs, or look at particular I/O
channels in detail.
See Also
Linear System Analyzer
More About
• “Model Arrays” on page 2-100
24-21
24 Linear System Analyzer
For more information about using the options in these panes in an instance of the Linear
System Analyzer, see “Linear System Analyzer Preferences Editor” on page 20-2.
24-22
See Also
If you want to customize the settings for all instances of Linear System Analyzer, see
“Toolbox Preferences Editor” on page 19-2.
See Also
Linear System Analyzer
More About
• “Linear System Analyzer Overview” on page 24-2
24-23