System Identification With Matlab. Linear Models
System Identification With Matlab. Linear Models
Linear Models
Marvin L.
What Are Model Objects?
In this section...
Model Objects Represent Linear Systems on page 1-3 About Model Data on page 1-3
Identified
Nonlinear Models
idnlarx
idnlgrey
idnlhw
Dynamic
Control Design Blocks
Tunable
ltiblock.tf
ltiblock.ss
ltiblock.gain
ltiblock.pid
ltiblock.pid2
Uncertain
ultidyn
udyn
Switch Block
loopswitch
Static
Control Design Blocks Tunable
realp
Uncertain
ureal
ucomplex
ucomplexm
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.
Model Type Description
tf Transfer function model in polynomial form
zpk Transfer function model in zero-pole-gain (factorized) form
ss State-space model
frd Frequency response data model pid Parallel-form PID controller
pidstd Standard-form PID controller
Nonlinear ODE (grey-box) model, with identifiable parameters Hammerstein-Wiener model, with
identifiable parameters
IDLTIH
u
G
y
WhenyousimulateanIDLTImodel,youstudytheeffectofinput u(t) (and possibly initial conditions) on the
output y(t). The noise e(t) is not considered. However, with finite-horizon prediction of the output, both
the measured and the noise components of the model contribute towards computation of the (predicted)
response.
H-1G
y_predicted
y_measured1-H-1
One-step ahead prediction model corresponding to a linear identified model (y = Gu+He)
Construction: Use idpolyto create a model using values of active polynomials as input arguments. For
example, to create an Output-Error model which usesG= B/Fas the measured component and has a
trivial noise component (H= 1). enter:
y = idpoly([],B,[],[],F)
Estimation: Use the armax, arx,or bj, specifying the orders
BC
Ay t() Fut() Det()
The autoregressive component, A, is common between
the measured and noise
components. The polynomials B and F constitute the
measured component while the polynomials C and D constitute the noise component.
of the polynomials as input arguments. For example, bj requires you to specify the orders of the B, C,
D,and F polynomials to construct a model with governing equation
BC
yt() Fut() Det()
Transfer function model
(idtf)
Represents an identified transfer function model, which has no dynamic elements to model noise
behavior. This object uses the trivial noise model H(s) = I. The governing equation is
num
yt()
denut et() ()
Process model
(idproc)
Represents a process model, which provides options to represent the noise dynamics as either first- or
second-order ARMA process (that is, H(s)= C(s)/A(s),where C(s) and A(s) are monic polynomials of
equal degree). The measured component, G(s),isrepresented Construction: Use idtfto create a model,
specifying values of the numerator
and denominator coefficients as input arguments. The numerator and denominator vectors constitute the
measured componentG= num(s)/den(s).Thenoise component is fixed toH= 1.
Estimation: Use tfest,
specifying the number of poles and zeros of the measured component G.
For process (and grey-box) models, the noise component is often treated as an on-demand
extensiontoanotherwise measured component-centric representation. For these models, you can add a
noise component by using the
by a transfer function expressed in pole-zero form.
The estimation function treats the noise variable e(t) as prediction error the residual portion of the
output that cannot be attributed to the measured inputs. All estimation algorithms work to minimize a
weighted norm of e(t) over the span of available measurements. The weighting function is defined by
the nature of the noise transfer function H and the focus of estimation, such as simulation or prediction
error minimization.
Black Box (Cold Start) Estimation on page 1-17
Structured Estimations on page 1-17
Estimation Options on page 1-18
Estimation Report on page 1-19
Black Box (Cold Start) Estimation
In a black-box estimation, you only have to specify the order to configure the structure of the model.
sys = estimator(data, orders)
where estimatoris the name of an estimation command to use for the desired model type.
For example, you use tfestto estimate transfer function models, arxfor ARX-structure polynomial
models, and procestfor process models.
The first argument, data, is time- or frequency domain data represented as an iddataor idfrdobject. The
second argument, orders, represents one or more numbers whose definitions depends upon the model
type:
For transfer functions, ordersrefers to the number of poles and zeros.
For state-space models, ordersis a scalar that refers to the number of states.
For process models, ordersis a string denoting the structural elements of a process model, such as, the
number of poles and presence of delay and integrator.
When working with the GUI, you specify the orders in the appropriate edit fields of corresponding
model estimation dialogs.
Structured Estimations
In some situations, you want to configure the structure of the desired model more closely than what is
achieved by simply specifying the orders. In such cases, you construct a template model and configure
its properties. You then pass that template model as an input argument to the estimation commands in
place of orders.
To illustrate, the following example assigns initial guess values to the numerator and the denominator
polynomials of a transfer function model, imposes minimum and maximum bounds on their estimated
values, and then passes the object to the estimator function.
% initial guess for numerator
num = [1 2] den = [1 2 1 1]
% initial guess for the denominator
sys = idtf(num, den);
% set min bound on den coefficients to 0.1 sys.Structure.den.Minimum = [1 0.1 0.1 0.1]; sysEstimated =
tfest(data, sys);
The estimation algorithm uses the provided initial guesses to kick-start the estimation and delivers a
model that respects the specified bounds.
You can use such a model template to also configure auxiliary model properties such as input/output
names and units. If the values of some of the models parameters are initially unknown, you can use
NaNsfor them in the template.
Estimation Options
There are many options associated with a models estimation algorithm that configure the estimation
objective function, initial conditions and numerical search algorithm, among other things. For every
estimation command, estimator, there is a corresponding option command named estimatorOptions. To
specify options for a particular estimator command, such as tfest, use the options command that
corresponds to the estimation command, in this case, tfestOptions. The options command returns an
options set that you then pass as an input argument to the corresponding estimation command.
For example, to estimate an Output-Error structure polynomial model, you use oe.Tospecify
simulationas the focus and lsqnonlinas the search method, you use oeOptions:
load iddata1 z1
Options = oeOptions('Focus','simulation','SearchMethod','lsqnonlin'); sys= oe(z1, [2 2 1], Options);
For information about how to view the list of options used to create an estimated model, see Estimation
Report on page 1-19.
Estimation Report
The model returned by the estimation command contains information about the estimation operation in
the Reportproperty. Information includes:
Information on initial conditions used for estimation
Termination conditions for iterative estimation algorithms under a category called Termination
Final prediction error (FPE), fit % and mean-square error (MSE) under a category called Fit
The nature of estimation data under a category called DataUsed
All estimated quantities - parameter values and their covariance, initial state values for state-space
models and values of input level for process models under a category called Parameters
The option set used for estimation under a category called OptionsUsed
To illustrate, this example displays the contents of the Report.OptionsUsed property of the model
estimated in Estimation Options on page 1-18.
sys.Report
Status: 'Estimated using POLYEST with Focus = "prediction"' Method: 'OE'
InitialCondition: 'zero'
Fit: [1x1 struct]
Parameters: [1x1 struct]
OptionsUsed: [1x1 idoptions.polyest]
Model Properties
Categories of Model Properties on page 1-27
Viewing Model Properties and Estimated Parameters on page 1-28
Categories of Model Properties
The way a model object stores information is defined by the properties of the corresponding model
class.
Each model object has properties for storing information that are relevant only to that specific model
type. The idtf, idgrey, idpoly, idproc,and idssmodel objects are based on the idltisuperclass and inherit
all idlti properties.
Similarly, the nonlinear models idnlarx, idnlhw,and idnlgreyare based on the idnlmodelsuperclass and
inherit all idnlmodelproperties.
In general, all model objects have properties that belong to the following categories:
Names of input and output channels, such as InputNameand OutputName
Sampling interval of the model, such as Ts
Units for time or frequency
Model order and mathematical structure (for example, ODE or nonlinearities)
Properties that store estimation results (Report)
User comments, such as Notesand Userdata
Estimation algorithm information (nonlinear models only)
- Algorithm
Structure includes fields that specify the estimation method. Algorithm includes another structure, called
Advanced, which provides additional flexibility for setting the search algorithm. Different fields apply to
different estimation techniques.
For linear parametric models, Algorithmspecifies the frequency weighing of the estimation using the
Focusproperty.
For information about getting help on object properties, see the model reference pages.
Viewing Model Properties and Estimated Parameters The following table summarizes the commands
for viewing and changing model property values. Property names are not case sensitive. You do not need
to type the entire property name if the first few letters uniquely identify the property.
Task
View all model
properties and their values
Access a specific model
property Use dot notation
Command get
Example
Load sample data, compute an ARX model, and list the model properties:
load iddata8
m_arx=arx(z8,[4 3 2 3 0 0 0]); get(m_arx)
View the A matrix containing the estimated parameters in the previous model:
Access model uncertainty information For properties, such as Report,that
are configured like structures, use dot notation of the form model.PropertyName.FieldName.
FieldNameis the name of any field of the property.
getpvecand
polydata
m_arx.a ViewthemethodusedinARXmodel estimation:
m_arx.Report.Method
View the A polynomial and 1 standard uncertainty of an ARX model:
[a,~,~,~,~,da] = polydata(m_arx)
Task Command
Change setor dot notation model
property
values
Example
Change the input delays for all three input channels to[111]for an ARX model:
set(m_arx,'InputDelay',[1 1 1])
or m_arx.InputDelay = [1 1 1]
See Also
Validate each model directly after estimation to help fine-tune your modeling strategy. When you do not
achieve a satisfactory model, you can try a different model structure and order, or try another
identification algorithm. For more information about validating and troubleshooting models, see
Validating Models After Estimation on page 8-3.
You can update the value of the numand denproperties after you create the object as follows:
new_den = [1 1 10]; sys.den = new_den;
To fix the denominator to the value you specified (treat its coefficients as fixed parameters), use the
Structureproperty of the object as follows:
sys.Structure.den.Value = new_den; sys.Structure.den.Free = false(1,3);
For a transfer function model, the num, den,and ioDelaymodel properties are simply pointers to the
Valueattribute of the corresponding parameter in the Structureproperty.
IDTF Model Properties Parameters
num double vector
den double vector
ioDelay scalar num:
Value:
Minimum: Maximum: Free:
Scale:
Info:
double vector double vector double vector logical vector double vector struct
Structure
InputDelay scalar
Ts scalar
. . den:
Value:
Minimum: Maximum: Free:
Scale:
Info:
..
. . ioDelay:
Value:
Minimum: Maximum:
Free:
Scale:
Info:
Similar relationships exist for other model structures. For example, the a property of a state-space model
contains the double value of the state matrix. It is an alias to the Aparameter value stored in
Structure.a.Value.
Note Model structure is not the only factor that determines model accuracy. If your model is poor, you
might need to preprocess your data by removing outliers or filtering noise. For more information, see
Ways to Prepare Data for System Identification on page 2-6.
Estimate impulse-response and frequency-response models first to gain insight into the system dynamics
and assess whether a linear model is sufficient. Then, estimate parametric models in the following order:
Transfer function, ARX polynomial and state-space models provide the simplest structures. Estimation
of ARX and state-space models let you determine the model orders.
1
See Also
Supported Continuous- and Discrete-Time Models on page 1-38
Time-series models
Nonlinear ARX models Hammerstein-Wiener models
Estimation Commands
tfest
procest
armax (ARMAX only)
arx(ARX only)
bj(BJ only)
iv4(ARX only)
oe(OE only)
polyest(for all models)
n4sid
ssest
ar
arx(for multiple outputs)
ivar
nlarx(for nonlinear time-series models)
nlarx
nlhw
If you know that some of the outputs have poor accuracy and should be less important during estimation,
you can control how much each output is weighed in the estimation. For more information, see
Improving Multiple-Output Estimation Results by Weighing Outputs During Estimation on page 1-43.
For linear models, use the OutputWeightestimation to indicate the desired output weighting. If you set
this option to 'noise', an automatic weighting, equal to the inverse of the estimated noise variance, is
used for model estimation. You can also specify a custom weighting matrix, which must be a positive
semi-definite matrix.
Note
The OutputWeightoption is not available for polynomial models, except ARX models, since their
estimation algorithm estimates the parameters oneoutputatatime.
Transfer function (idtf) and process models (idproc)ignore OutputWeight when they contain nonzero or
free transport delays. In the presence of delays, the estimation is carried out one output at a time.
For nonlinear models, you can specify output weights directly in the estimation command using the
Criterionand Weightingestimation options. You must set the Criterionfield to Trace, and set the
Weightingfield to the matrix that contains the output weights. The Tracecriterion minimizes the
weighted sum of the prediction errors using the weights specified by Weighting.
For more information about the OutputWeight estimation option, see arxOptions, ssestOptions,
tfestOptions, procestOptions,etc. Formore information about the Algorithmfields for nonlinear
estimation, see the idnlarxand idnlhwreference pages.
Note For multiple-output idnlarxmodels containing neuralnetor treepartitionnonlinearity estimators,
output weighting is ignored because each output is estimated independently.
Supported Data
System Identification Toolbox software supports estimation of linear models from both time- and
frequency-domain data. For nonlinear models, this toolbox supports only time-domain data. For more
information, see Supported Models for Time- and Frequency-Domain Data on page 1-35.
The data can have single or multiple inputs and outputs, and can be either real or complex.
Your time-domain data should be sampled at discrete and uniformly spaced time instants to obtain an
input sequence
u={u(T),u(2T),...,u(NT)}
and a corresponding output sequence
y={y(T),y(2T),...,y(NT)}
u(t) and y(t) are the values of the input and output signals at time t, respectively.
This toolbox supports modeling both single- or multiple-channel input-output data or time-series data.
Supported Data Time-domain I/O data
Time-series data
Description
One or more input variables u(t) and one or more output variables y(t), sampled as a function of time.
Time-domain data can be either real or complex
Contains one or more outputs y(t) and no measured input. Can be time-domain or frequency-domain
data.
Supported Data Description
Frequency-domain data Fourier transform of the input and output time-domain signals. The data is the
set of input and output signals in frequency domain; the frequency grid need not be uniform.
Frequency-response data Complex frequency-response values for a linear system characterized by its
transfer function G, measurable directly using a spectrum analyzer. Also called frequency function
data.Representedby frdor idfrd objects. The data sample time may be zero or nonzero. The frequency
vector need not be uniformly spaced.
Note If your data is complex valued, see Manipulating Complex-Valued Data on page 2-144 for
information about supported operations for complex data.
Review the data characteristics for any of the following features to determine if there is a need for
preprocessing:
Missing or faulty values (also known as outliers). For example, you might see gaps that indicate
missing data, values that do not fit with the rest of the data, or noninformative values.
See Handling Missing Data and Outliers on page 2-100.
Offsets and drifts in signal levels (low-frequency disturbances).
See Handling Offsets and Trends in Data on page 2-104 for information about subtracting means and
linear trends, and Filtering Data on page 2-120 for information about filtering.
High-frequency disturbances above the frequency interval of interest for the system dynamics.
See Resampling Data on page 2-111 for information about decimating and interpolating values, and
Filtering Data on page 2-120 for information about filtering.
Select a subset of your data
You can use data selection as a way to clean the data and exclude parts with noisy or missing
information. You can also use data selection to create independent data sets for estimation and
validation.
To learn more about selecting data, see Selecting Subsets of Data on page 2-96.
Combine data from multiple experiments
You can combine data from several experiments into a single data set. The model you estimate from a
data set containing several experiments describes the average system that represents these experiments.
To learn more about creating multiple-experiment data sets, see Creating Multiexperiment Data Sets in
the GUI on page 2-39 or Creating Multiexperiment Data at the Command Line on page 2-61.
For more information about importing data into the MATLAB workspace, see Data Import and
Export.
After you have the variables in the MATLAB workspace, import them into the System Identification
Tool GUI or create a data object for working at the command line. For more information, see Importing
Time-Domain Data into the GUI on page 2-18 and Representing Time- and Frequency-Domain Data
Using iddata Objects on page 2-55.
For information about estimating time-series model parameters, see Time-Series Model Identification.
f
f
iwtdt
In the context of numerical computations, continuous equations are replaced by their discretized
equivalents to handle discrete data values. For a discrete-time system with a sampling interval T, the
frequency-domain output Y(eiw) and input U(eiw) is the time-discrete Fourier transform (TDFT):
N Ye
k=1
iwT
= () ()T ykTeiwkT
In practice, the Fourier transform cannot be handled for all continuous frequencies and you must specify
a finite number of frequencies. The discrete Fourier transform (DFT) of time-domain data for N equally
spaced frequencies between 0 and the sampling frequency 2/N is:
N Ye
iw T=() ()nniw kT
ykTe
k=1
2
n
wn ==
TnN1
The DFT is useful because it can be calculated very efficiently using the fast Fourier transform (FFT)
method. Fourier transforms of the input and output data are complex numbers.
For more information on how to obtain identification data, see Ways to Obtain Identification Data on
page 2-5.
How to Represent Frequency-Domain Data in MATLAB.You must organize frequency-domain data
in the following format:
Input and output
- For single-input/single-output (SISO) data:
The input data must be a column vector containing the values
ue
ikT
Z()
The output data must be a column vector containing the values
ye
ikT
Z()
k=1, 2, ..., Nf,where Nfis the number of frequencies.
- For multi-input/multi-output data with Nuinputs, Nyoutputs and Nffrequency measurements:
The input data must be an Nf-byNumatrix
The output data must be an Nf-byNymatrix
Frequencies
- Must be a column vector.
For more information about importing data into the MATLAB workspace, see Data Import and
Export.
After you have the variables in the MATLAB workspace, import them into the System Identification
Tool GUI or create a data object for working at the command line. For more information, see Importing
Frequency-Domain Input/Output Signals into the GUI on page 2-23 and Representing Timeand
Frequency-Domain Data Using iddata Objects on page 2-55.
Frequency-Response Data Representation
What Is Frequency-Response Data? on page 2-13
How to Represent Frequency-Response Data in MATLAB on page 2-15
What Is Frequency-Response Data?. Frequency-response data,alsocalled frequency-function data,
consists of complex frequency-response values for a linear system characterized by its transfer function
G. Frequency-response data tells you how the system handles sinusoidal inputs. You can measure
frequency-response data values directly using a spectrum analyzer, for example, which provides a
compact representation of the input-output relationship (compared to storing input and output
independently). The transfer function G is an operator that takes the input u of a linear system to the
output y:
=yGu
For a continuous-time system, the transfer function relates the Laplace transforms of the input U(s) and
output Y(s):
Ys GsUs= () ()
In this case, the frequency function G(iw) is the transfer function evaluated on the imaginary axis s=iw.
For a discrete-time system sampled with a time interval T,thetransfer function relates the Z-transforms
of the input U(z) and output Y(z):
Yz GzU z= () ()
In this case, the frequency function G(eiwT) is the transfer function G(z) evaluated on the unit circle. The
argument of the frequency function G(eiwT) is scaled by the sampling interval T to make the frequency
function periodic
with the sampling frequency 2T.
When the input to the system is a sinusoid of a specific frequency, the output is also a sinusoid with the
same frequency. The amplitude of the output is G times the amplitude of the input. The phase of the
shifted from the input by = arg G. G is evaluated at the frequency of the input sinusoid.
Frequency-response data represents a (nonparametric) model of the relationship between the input and
the outputs as a function of frequency. You might use such a model, which consists of a table or plot of
values, to study the system frequency response. However, this model is not suitable for simulation and
prediction. You should create parametric model from the frequency-response data.
For more information on how to obtain identification data, see Ways to Obtain Identification Data on
page 2-5.
How to Represent Frequency-Response Data in MATLAB.You can represent frequency-response
data in two ways:
Complex-values G(ei) , for given frequencies
Amplitude G and phase shift = arg Gvalues
You can import both the formats directly in the System Identification Tool GUI. At the command line,
you must represent complex data using an frd or idfrdobject. If the data is in amplitude and phase
format, convert it to complex frequency-response vector using h() = A()ej().
You must organize frequency-response data in the following format:
Rrequency-ResponseFor Single-Input
Single-Output (SISO) Data Data
Representation Complex Values
For Multi-Input Multi-Output (MIMO) Data
Frequency function must be a column vector.
Frequency values must be a column vector.
Amplitude and phase shift values
Amplitude and phase must each be a column vector.
Frequency values must be a column vector.
Frequency function must be an Ny-byNu-byNfarray, where
N uis the number of inputs, Ny
For
an example of importing data into the System Identification Tool GUI, see the Getting Started
documentation.
In the System Identification Tool window, select Import data > Time domain data. This action opens
the Import Data dialog box.
2
Note For time series, only import the output signal and enter []for the input.
Input Enter the MATLAB variable name (column vector or matrix) or a MATLAB expression that
represents the input data. The expression must evaluate to a column vector or matrix.
Output Enter the MATLAB variable name (column vector or matrix) or a MATLAB expression
that represents the output data. The expression must evaluate to a column vector or matrix.
Data name Enter the name of the data set, which appears in the System Identification Tool window
after the import operation is completed.
Starting timeEnterthestartingvalueofthetimeaxisfortimeplots.
Sampling interval Enter the actual sampling interval in the experiment. For more information
about this setting, see Specifying the Data Sampling Interval on page 2-34.
Tip The System Identification Toolbox product uses the sampling interval during model estimation and
to set the horizontal axis on time plots. If you transform a time-domain signal to a frequency-domain
signal, the Fourier transforms are computed as discrete Fourier transforms (DFTs) using this sampling
interval.
4(Optional) In the Data Information area, click More to expand the dialog
box and enter the following settings:
Input Properties
InterSample This options specifies the behavior of the input signals between samples during data
acquisition. It is used when transforming models from discrete-time to continuous-time and when
resampling the data.
zoh(zero-order hold) indicates that the input was piecewise-constant during data acquisition.
foh(first-order hold) indicates that the output was piecewise-linear during data acquisition.
bl(bandwidth-limited behavior) specifies that the continuous-time input signal has zero power above
the Nyquist frequency (equal to the inverse of the sampling interval).
Note See the d2cand c2dreference pages for more information about transforming between discrete-time
and continuous-time models.
PeriodEnter Infto specify a nonperiodic input. If the underlying time-domain data was periodic over
an integer number of periods, enter the period of the input signal.
Note If your data is periodic, always include a whole number of periods for model estimation.
Channel Names
InputEnterastringtospecifythenameofoneormoreinput channels.
Tip Naming channels helps you to identify data in plots. For multivariable input-output signals, you can
specify the names of individual Input and Output channels, separated by commas.
OutputEnterastringtospecifythenameofoneormoreoutput channels.
Physical Units of Variables
Input Enter a string to specify the input units.
Tip When you have multiple inputs and outputs, enter a comma-separated list of Input and Output
units corresponding to each channel.
Output Enter a string to specify the output units.
Notes Enter comments about the experiment or the data. For example, you might enter the
experiment name, date, and a description of experimental conditions. Models you estimate from this
data inherit your data notes.
5Click
6Click
Import. This action adds a new data icon to the System Identification Tool window.
Close to close the Import Data dialog box.
In the System Identification Tool window, select Import data > Freq. domain data. This action
opens the Import Data dialog box.
3Specify the following options:
2
Input Enter the MATLAB variable name (column vector or matrix) or a MATLAB expression that
represents the input data. The expression must evaluate to a column vector or matrix.
Output Enter the MATLAB variable name (column vector or matrix) or a MATLAB expression
that represents the output data. The expression must evaluate to a column vector or matrix.
Frequency Enter the MATLAB variable name of a vector or a MATLAB expression that represents
the frequencies. The expression must evaluate to a column vector.
The frequency vector must have the same number of rows as the input and output signals.
Data name Enter the name of the data set, which appears in the System Identification Tool window
after the import operation is completed.
Frequency unitEnter Hzfor Hertz or keep the rad/sdefault value.
Sampling interval Enter the actual sampling interval in the experiment. For continuous-time data,
enter 0. For more information about this setting, see Specifying the Data Sampling Interval on page
2-34.
4(Optional)
In the Data Information area, click More to expand the dialog box and enter the following
optional settings:
Input Properties
InterSample This options specifies the behavior of the input signals between samples during data
acquisition. It is used when transforming models from discrete-time to continuous-time and when
resampling the data.
zoh(zero-order hold) indicates that the input was piecewise-constant during data acquisition.
foh(first-order hold) indicates that the output was piecewise-linear during data acquisition.
bl(bandwidth-limited behavior) specifies that the continuous-time input signal has zero power above
the Nyquist frequency (equal to the inverse of the sampling interval).
Note See the d2cand c2dreference page for more information about transforming between discrete-time
and continuous-time models.
PeriodEnter Infto specify a nonperiodic input. If the underlying time-domain data was periodic over
an integer number of periods, enter the period of the input signal.
Note If your data is periodic, always include a whole number of periods for model estimation.
Channel Names
InputEnterastringtospecifythenameofoneormoreinput channels.
Tip Naming channels helps you to identify data in plots. For multivariable input and output signals, you
can specify the names of individual Input and Output channels, separated by commas.
OutputEnterastringtospecifythenameofoneormoreoutput
Input Enter a string to specify the input units.
Tip When you have multiple inputs and outputs, enter a comma-separated list of Input and Output
units corresponding to each channel.
Output Enter a string to specify the output units.
Notes Enter comments about the experiment or the data. For example, you might enter the
experiment name, date, and a description of experimental conditions. Models you estimate from this
data inherit your data notes.
5Click
6Click
Import. This action adds a new data icon to the System Identification Tool window.
Close to close the Import Data dialog box.
Importing Frequency-Response Data into the GUI
Prerequisite on page 2-26
Importing Complex-Valued Frequency-Response Data on page 2-26
Importing Amplitude and Phase Frequency-Response Data on page 2-28
Prerequisite. Before you can import frequency-response data into the System Identification Tool GUI,
you must import the data into the MATLAB workspace, as described in Frequency-Response Data
Representation on page 2-13.
Importing Complex-Valued Frequency-Response Data. To import frequency-response data consisting
of complex-valued frequency values at specified frequencies:
1Type
the following command in the MATLAB Command Window to open the GUI:
ident
2In the System Identification Tool window, select Import data > Freq. domain data. This action opens
the Import Data dialog box.
3In the Data Format for Signals list, select Freq. Function (Complex).
4Specify the following options:
Freq. Func. EntertheMATLABvariablenameoraMATLAB expression that represents the complex
frequency-response data G(eiw).
Frequency Enter the MATLAB variable name of a vector or a MATLAB expression that represents
the frequencies. The expression must evaluate to a column vector.
Data name Enter the name of the data set, which appears in the System Identification Tool window
after the import operation is completed.
Frequency unitEnter Hzfor Hertz or keep the rad/sdefault value.
Sampling interval Enter the actual sampling interval in the experiment. For continuous-time data,
enter 0. For more information about this setting, see Specifying the Data Sampling Interval on page
2-34.
5(Optional)
In the Data Information area, click More to expand the dialog box and enter the following
optional settings:
Channel Names
InputEnterastringtospecifythenameofoneormoreinput channels.
Tip Naming channels helps you to identify data in plots. For multivariable input and output signals, you
can specify the names of individual Input and Output channels, separated by commas.
OutputEnterastringtospecifythenameofoneormoreoutput
Input Enter a string to specify the input units.
Tip When you have multiple inputs and outputs, enter a comma-separated list of Input and Output
units corresponding to each channel.
Output Enter a string to specify the output units.
Notes Enter comments about the experiment or the data. For example, you might enter the
experiment name, date, and a description of experimental conditions. Models you estimate from this
data inherit your data notes.
6Click
7Click
Import. This action adds a new data icon to the System Identification Tool window.
Close to close the Import Data dialog box.
In the Data Information area, click More to expand the dialog box and enter the following
optional settings:
Channel Names
InputEnterastringtospecifythenameofoneormoreinput channels.
Tip Naming channels helps you to identify data in plots. For multivariable input and output signals, you
can specify the names of individual Input and Output channels, separated by commas.
OutputEnterastringtospecifythenameofoneormoreoutput channels.
Physical Units of Variables
Input Enter a string to specify the input units.
Tip When you have multiple inputs and outputs, enter a comma-separated list of Input and Output
units corresponding to each channel.
Output Enter a string to specify the output units.
Notes Enter comments about the experiment or the data. For example, you might enter the
experiment name, date, and a description of experimental conditions. Models you estimate from this
data inherit your data notes.
6Click
7Click
Import. This action adds a new data icon to the System Identification Tool window.
Close to close the Import Data dialog box.
This action opens the Import Data dialog box. IDDATA or IDFRD/FRD is already
selected in the Data Format for Signals list.
3Specify the following options:
ObjectEnterthenameoftheMATLABvariablethatrepresentsthe data object in the MATLAB
workspace. Press Enter.
Data name Enter the name of the data set, which appears in the System Identification Tool window
after the import operation is completed.
(Only for time-domain iddataobject) Starting timeEnterthe starting value of the time axis for time
plots.
(Only for frequency domain iddataor idfrdobject) Frequency unit Enter the frequency unit for
response plots.
Sampling interval Enter the actual sampling interval in the experiment. For more information
about this setting, see Specifying the Data Sampling Interval on page 2-34.
Tip The System Identification Toolbox product uses the sampling interval during model estimation and
to set the horizontal axis on time plots. If you transform a time-domain signal to a frequency-domain
signal, the Fourier transforms are computed as discrete Fourier transforms (DFTs) using this sampling
interval.
4(Optional)
In the Data Information area, click More to expand the dialog box and enter the following
optional settings:
(Only for iddataobject) Input Properties
InterSample This options specifies the behavior of the input signals between samples during data
acquisition. It is used when transforming models from discrete-time to continuous-time and when
resampling the data.
zoh(zero-order hold) indicates that the input was piecewise-constant during data acquisition.
foh(first-order hold) indicates that the input was piecewise-linear during data acquisition.
bl(bandwidth-limited behavior) specifies that the continuous-time input signal has zero power above
the Nyquist frequency (equal to the inverse of the sampling interval).
Note See the d2cand c2dreference page for more information about transforming between discrete-time
and continuous-time models.
PeriodEnter Infto specify a nonperiodic input. If the underlying time-domain data was periodic over
an integer number of periods, enter the period of the input signal.
Note If your data is periodic, always include a whole number of periods for model estimation.
Channel Names
InputEnterastringtospecifythenameofoneormoreinput channels.
Tip Naming channels helps you to identify data in plots. For multivariable input and output signals, you
can specify the names of individual Input and Output channels, separated by commas.
OutputEnterastringtospecifythenameofoneormoreoutput channels.
Physical Units of Variables
Input Enter a string to specify the input units.
Tip When you have multiple inputs and outputs, enter a comma-separated list of Input and Output
units corresponding to each channel.
Output Enter a string to specify the output units.
Notes Enter comments about the experiment or the data. For example, you might enter the
experiment name, date, and a description of experimental conditions. Models you estimate from this
data inherit your data notes.
5Click
6Click
Import. This action adds a new data icon to the System Identification Tool window.
Close to close the Import Data dialog box.
The Inputs list displays the input channels and the Outputs list
displays the output channels in the selected data set.
In the Inputs list, select one or more channels in any of following ways:
Select one channel by clicking its name.
3
Select adjacent channels by pressing the Shift key while clicking the first and last channel names.
Select nonadjacent channels by pressing the Ctrl key while clicking each channel name.
Tip To exclude input channels and create time-series data, clear all selections by holding down the Ctrl
key and clicking each selection. To reset selections, click Revert.
4In the Outputs list, select one or more channels in any of following ways:
Select one channel by clicking its name.
Select adjacent channels by pressing the Shift key while clicking the first and last channel names.
Select nonadjacent channels by pressing the Ctrl key while clicking each channel name.
Tip To reset selections, click Revert.
5In the Data name field, type the name of the new data set. Use a name that is unique in the Data Board.
6Click Insert to add the new data set to the Data Board in the System Identification Tool GUI.
7Click Close.
Experiments can mean data that was collected during different sessions, or portions of the data collected
during a single session. In the latter situation, you can create multiexperiment data by splitting a single
data set into multiple segments that exclude corrupt data, and then merge the good data segments.
Limitations on Data Sets
You can only merge data sets that have all of the following characteristics:
Same number of input and output channels.
Different names. The name of each data set becomes the experiment name in the merged data set.
Same input and output channel names.
Same data domain (that is, time-domain data or frequency-domain data only).
Merging Data Sets
You can merge data sets using the System Identification Tool GUI. For example, suppose that you want
to combine the data sets tdata, tdata2, tdata3, tdata4showninthefollowingfigure.
In the System Identification Tool window, drag a data set icon to the Merge Experiments dialog box,to
the drop them here to be merged rectangle.
2
The name of the data set is added to the List of sets. Repeat for each data set you want to merge.
Data Board Now Contains tdatam with Merged Experiments 5Click Close to
close the Merge Experiments dialog box.
Tip To get information about a data set in the System Identification Tool GUI, right-click the data icon
to open the Data/model Info dialog box.
Extracting Specific Experiments from a Multiexperiment Data Set into a New Data Set
When adata set already consists of several experiments, you can extract one ormore of these experiments
into a new data set, using the System Identification Tool GUI.
For example, suppose that tdatamconsists of four experiments.
To create a new data set that includes only the first and third experiments in this data set:
1In the System Identification Tool window, drag and drop the tdatamdata icon to the Working Data
rectangle.
4In the Data name field, type the name of the new data set. This
name must be unique in the Data Board.
5Click Insert to add the new data set to the Data Board in the System Identification Tool GUI.
6Click Close to close the Select Experiment dialog box.
data
Type comments in the Notes field to describe the data sets. When you save a session, as described in
Saving, Merging, and Closing Sessions on page 12-6, all additional windows and notes are also saved.
iddata Constructor
Requirements for Constructing an iddata Object on page 2-55
Constructing an iddata Object for Time-Domain Data on page 2-56
Constructing an iddata Object for Frequency-Domain Data on page 2-57
Requirements for Constructing an iddata Object
To construct an iddataobject, you must have already imported data into the MATLAB workspace, as
described in Representing Data in MATLAB Workspace on page 2-9.
Constructing an iddata Object for Time-Domain Data Use the following syntax to create a timedomain iddataobject data:
data = iddata(y,u,Ts)
You can also specify additional properties, as follows:
data = iddata(y,u,Ts,'Property1',Value1,...,'PropertyN',ValueN)
For more information about accessing object properties, see Properties.
iddata Properties
To view the properties of the iddataobject, use the getcommand. For example, type the following
commands at the prompt:
load dryer2
data = iddata(y2,u2,0.08); get(data)
% Load input u2 and output y2 % Create iddata object
% Get property values of data Domain: 'Time'
Name: []
OutputData: [1000x1 double] y: 'Same as OutputData'
OutputName: {'y1'}
OutputUnit: {''}
InputData: [1000x1 double] u: 'Same as InputData' InputName: {'u1'}
InputUnit: {''}
Period: Inf
InterSample: 'zoh'
Ts: 0.0800
Tstart: []
SamplingInstants: [1000x0 double] TimeUnit: ''
ExperimentName: 'Exp1'
Notes: []
UserData: []
For a complete description of all properties, see the iddatareference page.
You can specify properties when you create an iddataobject using the constructor syntax:
data = iddata(y,u,Ts,'Property1',Value1,...,'PropertyN',ValueN)
To change property values for an existing iddataobject, use the setcommand or dot notation. For
example, to change the sampling interval to 0.05,type the following at the prompt:
set(data,'Ts',0.05)
or equivalently:
data.ts = 0.05
Property names are not case sensitive. You do not need to type the entire property name if the first few
letters uniquely identify the property. Tip You can use data.yas an alternative to data.OutputDatato
access the output values, or use data.uas an alternative to data.InputDatato access the input values.
An iddataobject containing frequency-domain data includes frequency-specific properties, such as
Frequencyfor the frequency vector and Unitsfor frequency units (instead of Tstartand
SamplingIntervals).
To view the property list, type the following command sequence at the prompt:
% Load input u2 and output y2
load dryer2;
% Create iddata object
data = iddata(y2,u2,0.08);
% Take the Fourier transform of the data
% transforming it to frequency domain data = fft(data)
% Get property values of data
get(data)
Domain: 'Frequency'
Name: []
OutputData: [501x1 double] y: 'Same as OutputData' OutputName: {'y1'}
OutputUnit: {''}
InputData: [501x1 double] u: 'Same as InputData' InputName: {'u1'}
InputUnit: {''}
Period: Inf
InterSample: 'zoh'
Ts: 0.0800
Units: 'rad/s'
Frequency: [501x1 double] TimeUnit: ''
ExperimentName: 'Exp1'
Notes: []
UserData: []
data(samples,outputchannels,inputchannels,experimentname)
In this syntax, samplesspecify one or more sample indexes, outputchannels and inputchannelsspecify
channel indexes or channel names, and experimentnamespecifies experiment indexes or names.
Forexample,toretrievesamples 5through 30in the iddataobject dataand store them in a new iddataobject
data_sub, use the following syntax:
data_sub = data(5:30)
You can also use logical expressions to subreference data. For example, to retrieve all data values from a
single-experiment data set that fall between sample instants 1.27and 9.3in the iddataobject dataand
assign them to data_sub, use the following syntax:
data_sub = data(data.sa>1.27&data.sa<9.3)
Note You do not need to type the entire property name. In this example, sa in data.sauniquely identifies
the SamplingInstantsproperty.
You can retrieve the input signal from an iddataobject using the following commands:
u = get(data,'InputData')
or
data.InputData
or
data.u % u is the abbreviation for InputData
Similarly, you can retrieve the output data using
data.OutputData
or
data.y % y is the abbreviation for OutputData
Subreferencing Data Channels
Use the following general syntax to subreference specific data channels in iddataobjects:
data(samples,outputchannels,inputchannels,experiment)
In this syntax, samplesspecify one or more sample indexes, outputchannels and inputchannelsspecify
channel indexes or channel names, and experimentnamespecifies experiment indexes or names.
To specify several channel names, you must use a cell array of name strings.
For example, suppose the iddataobject datacontains three output channels (named y1, y2,and y3), and
four input channels (named u1, u2, u3,and u4). To select all data samples in y3, u1,and u4, type the
following command at the prompt:
% Use a cell array to reference % input channels 'u1' and 'u4' data_sub = data(:,'y3',{'u1','u4'})
or equivalently
% Use channel indexes 1 and 4 % to reference the input channels data_sub = data(:,3,[1 4])
Tip Use a colon (:) to specify all samples or all channels, and the empty matrix ([]) to specify no
samples or no channels.
If you want to create a time-series object by extracting only the output data from an iddataobject, type
the following command:
data_ts = data(:,:,[])
You can assign new values to subreferenced variables. For example, the following command assigns the
first 10 values of output channel 1of datato values in samples 101through 110in the output channel 2of
data1.Italso assigns the values in samples 101through 110in the input channel 3of data1 to the first 10
values of input channel 1of data.
data(1:10,1,1) = data1(101:110,2,3)
Subreferencing Experiments
Use the following general syntax to subreference specific experiments in iddataobjects:
data(samples,outputchannels,inputchannels,experimentname)
In this syntax, samplesspecify one or more sample indexes, outputchannels and inputchannelsspecify
channel indexes or channel names, and experimentnamespecifies experiment indexes or names.
When specifying several experiment names, you must use a cell array of name strings. The iddataobject
stores experiments name in the ExperimentName property.
For example, suppose the iddataobject datacontains five experiments with default names, Exp1, Exp2,
Exp3, Exp4,and Exp5. Use the following syntax to subreference the first and fifth experiment in data:
data_sub = data(:,:,:,{'Exp1','Exp5'}) % Using experiment name
or
data_sub = data(:,:,:,[1 5]) % Using experiment index
Tip Use a colon (:) to denote all samples and all channels, and the empty matrix ([]) to specify no
samples and no channels.
Alternatively, you can use the getexpcommand. The following example shows how to subreference the
first and fifth experiment in data:
data_sub = getexp(data,{'Exp1','Exp5'}) % Using experiment name
or
data_sub = getexp(data,[1 5]) % Using experiment index
The following example shows how to retrieve the first 100 samples of output channels 2 and 3 and input
channels 4 to 8 of Experiment 3:
dat(1:100,[2,3],[4:8],3)
For multi-experiement data with Neexperiments, Unitsis a 1-byNecell array, and each cell contains the
frequency unit for each experiment.
data.freq =
logspace(-1,2,100)
Set the frequency unit to Hz:
data.FrequencyUnit = 'Hz'
Note that changing the frequency unit does not scale the frequency vector. For a proper translation of
units, use chgFreqUnit.
Naming, Adding, and Removing Data Channels
What Are Input and Output Channels? on page 2-73
Naming Channels on page 2-73
Adding Channels on page 2-74
Modifying Channel Data on page 2-74
What Are Input and Output Channels?. A multivariate system might contain several input variables
or several output variables, or both. When an input or output signal includes several measured variables,
these variables are called channels.
Naming Channels. The iddataproperties InputNameand OutputNamestore the channel names for the
input and output signals. When you plot the data, you use channel names to select the variable displayed
on the plot. If you have multivariate data, it is helpful to assign a name to each channel that describes the
measured variable. For more information about selecting channels on a plot, see Selecting Measured
and Noise Channels in Plots on page 12-16.
You can use the setcommand to specify the names of individual channels. For example, suppose
datacontains two input channels (voltage and current) and one output channel (temperature). To set these
channel names, use the following syntax:
set(data,'InputName',{'Voltage','Current'}, 'OutputName','Temperature')
Tip You can also specify channel names as follows:
data.una = {'Voltage','Current') data.yna = 'Temperature'
unais equivalent to the property InputName,and ynais equivalent to OutputName.
If you do not specify channel names when you create the iddataobject, the toolbox assigns default
names. By default, the output channels are named 'y1','y2',...,'yn', and the input channels are named
'u1','u2',...,'un'.
Adding Channels.You can add data channels to an iddataobject.
For example, consider an iddataobject named datathat contains an input signal with four channels. To
add a fifth input channel, stored as the vector Input5, use the following syntax:
data.u(:,5) = Input5;
Input5 must have the same number of rows as the other input channels. In this example,
data.u(:,5)references all samples as (indicated by :)ofthe input signal uand sets the values of the fifth
channel. This channel is created when assigning its value to Input5.
You can also combine input channels and output channels of several iddata objects into one iddataobject
using concatenation. For more information, see Increasing Number of Channels or Data Points of
iddata Objects on page 2-67.
Modifying Channel Data. After you create an iddataobject, you can modify or remove specific input
and output channels, if needed. You can accomplish this by subreferencing the input and output matrices
and assigning new values.
For example, suppose the iddataobject datacontains three output channels (named y1, y2,and y3), and
four input channels (named u1, u2, u3,and u4). To replace datasuch that it only contains samples in y3,
u1,and u4,type the following at the prompt:
data = data(:,3,[1 4])
The resulting data object contains one output channel and two input channels.
Subreferencing iddata Objects
See Select Data Channels, I/O Data and Experiments in iddata Objects on page 2-63.
Concatenating iddata Objects
See Increasing Number of Channels or Data Points of iddata Objects on page 2-67.
idfrd Constructor
The idfrdrepresents complex frequency-response data. Before you can create an idfrdobject, you must
import your data as described in Frequency-Response Data Representation on page 2-13.
Note The idfrdobject can only encapsulate one frequency-response data set. It does not support the
iddataequivalent of multiexperiment data.
Use the following syntax to create the data object fr_data:
fr_data = idfrd(response,f,Ts)
Suppose that nyis the number of output channels, nuis the number of input channels, and nfis a vector of
frequency values. responseis an ny-bynu-bynf3-D array. fis the frequency vector that contains the
frequencies of the response.Tsis the sampling time, which is used when measuring or computing the
frequency response. If you are working with a continuous-time system, set Tsto 0.
response(ky,ku,kf) ,where ky, ku,and kfreference the kth output, input, and frequency value,
respectively, is interpreted as the complex-valued frequency response from input kuto output kyat
frequency f(kf). Note When you work at the command line, you can only create idfrdobjects from
complex values of G(eiw).ForaSISOsystem, responsecan be a vector.
You can specify object properties when you create the idfrdobject using the constructor syntax:
fr_data = idfrd(response,f,Ts,
'Property1',Value1,...,'PropertyN',ValueN)
idfrd Properties
To view the properties of the idfrdobject, you can use the getcommand. The following example shows
how to create an idfrdobject that contains 100 frequency-response values with a sampling time interval
of 0.08 s and get its properties:
% Create the idfrd data object fr_data = idfrd(response,f,0.08)
% Get property values of data get(fr_data)
responseand fare variables in the MATLAB Workspace browser, representing the frequency-response
data and frequency values, respectively.
MATLAB returns the following object properties and values:
ans =
Name: ''
Frequency: [100x1 double] ResponseData: [1x1x100 double] SpectrumData: []
CovarianceData: []
NoiseCovariance: []
Units: 'rad/s'
Ts: 0.0800
InputDelay: 0
EstimationInfo: [1x1 struct]
InputName: {'u1'}
OutputName: {'y1'}
InputUnit: {''}
OutputUnit: {''}
Notes: []
UserData: []
For a complete description of all idfrdobject properties, see the idfrd reference page.
To change property values for an existing idfrdobject, use the setcommand or dot notation. For example,
to change the name of the idfrdobject, type the following command sequence at the prompt:
You can also use logical expressions to subreference data. For example, to retrieve all frequencyresponse values between frequencies 1.27and 9.3in the idfrdobject fr_data,usethefollowingsyntax:
fr_data_sub = fselect(fr_data,fr_data.f>1.27&fr_data.f<9.3)
Tip Use endto reference the last sample number in the data. For example, data(77:end).
Note You do not need to type the entire property name. In this example, fin fr_data.funiquely identifies
the Frequencyproperty of the idfrdobject.
Combined
u1
Horizonal Concatenation y1Same inputs u2 of Data 1 and Data 2y2 outputs u3 2-by-3-by-nf
Note Horizontal concatenation of idfrdobjects requires that they have the same outputs and frequency
vectors. If the output channel names are different and their dimensions are the same, the concatenation
operation resets the output names to their default values.
Vertical Concatenation of idfrd Objects
The following syntax creates a new idfrdobject datathat contains the vertical concatenation of
data1,data2,...,dataN:
data = [data1;data2;... ;dataN]
The resulting idfrdobject datacontains the frequency responses from the same inputs in
data1,data2,...,dataNto all the outputs. The following diagram is a graphical representation of vertical
concatenation of frequency-response data. The (j,i,:)vector of the resulting response data represents the
frequency response from the ith input to the jth output at all frequencies.
u1
Same
u1 Vertical Concatenationy1
of Data 1 and Data 2
y2
inputs
Note Vertical concatenation of idfrdobjects requires that they have the same inputs and frequency
vectors. If the input channel names are different and their dimensions are the same, the concatenation
operation resets the input names to their default values.
Concatenating Noise Spectrum Data of idfrd Objects When the SpectrumDataproperty of individual
idfrdobjectsisnotempty, horizontal and vertical concatenation handle SpectrumData,asfollows.
In case of horizontal concatenation, there is no meaningful way to combine the SpectrumDataof
individual idfrdobjects and the resulting SpectrumData property is empty. An empty property results
because each idfrdobject has its own set of noise channels, where the number of noise channels equals
the number of outputs. When the resulting idfrdobject contains the same output channels as each of the
individual idfrdobjects, it cannot accommodate the noise data from all the idfrdobjects.
In case of vertical concatenation, the toolbox concatenates individual noise models diagonally. The
following shows that data.SpectrumDatais a block diagonal matrix of the power spectra and cross
spectra of the output noise in the system:
?data1.s 0?
data s
=
??
??
?
0dataN s?
? ? sin data.sis the abbreviation for the SpectrumDataproperty name.
See Also
How to Analyze Data Using the advice Command on page 2-94 Ways to Prepare Data for System
Identification on page 2-6
HowtoPlotDatainthe GUI
How to Plot Data in the GUI on page 2-86
Manipulating a Time Plot on page 2-88
Manipulating Data Spectra Plot on page 2-89
Manipulating a Frequency Function Plot on page 2-91
How to Plot Data in the GUI
After importing data into the System Identification Tool GUI, as described in Importing Data into the
GUI on page 2-17, you can plot the data.
To create one or more plots, select the corresponding check box in the Data Views area of the System
Identification Tool GUI.
An active data icon has a thick line in the icon, while an inactive data set has a thin line. Only active data
sets appear on the selected plots. To toggle including and excluding data on a plot, click the
corresponding icon in the System Identification Tool GUI. Clicking the data icon updates any plots that
are currently open.
Thick lines indicate active data sets included in plots.
All three available data plots are
selected.
When you have several data sets, you can view different input-output channel pair by selecting that pair
from the Channel menu. For more information about selecting different input and output pairs, see
Selecting Measured and Noise Channels in Plots on page 12-16.
Action
Toggle display between periodogram and spectral estimate.
Change frequency units.
Toggle frequency scale between linear and logarithmic.
Toggle amplitude scale between linear and logarithmic.
Command
Select Options > Periodogram or Options > Spectral analysis. Select Style > Frequency (rad/s) or
Style > Frequency (Hz).
Select Style > Linear frequency scale or Style > Log frequency scale.
Select Style > Linear amplitude scale or Style > Log amplitude scale.
Manipulating a Frequency Function Plot
For time-domain data, the Frequency function plot shows the empirical transfer function estimate
(etfe). For frequency-domain data, the plot shows the ratio of output to input data.
Thefrequency-responseplotshowstheamplitudeandphaseplotsof the corresponding frequency response.
For more information about frequency-response data, see Frequency-Response Data Representation
on page 2-13.
Select Style > Linear frequency scale or Style > Log frequency scale.
Select Style > Linear amplitude scale or Style > Log amplitude scale.
time-domain data into the System Identification Tool GUI, as described in Importing Data into
the GUI on page 2-17.
2Drag the data set you want to subset to the Working Data area.
If your data contains multiple I/O channels, in the Channel menu, select
thechannelpairyouwanttoview. Theupperplotcorrespondstotheinput signal, and the lower plot
corresponds to the output signal.
3
Although you view only one I/O channel pair at a time, your data selection is applied to all channels in
this data set.
4Select the data of interest in either of the following ways:
Graphically Draw a rectangle on either the input-signal or the output-signal plot with the mouse to
select the desired time interval. Your selection appears on both plots regardless of the plot on which you
draw the rectangle. The Time span and Samples fields are updated to match the selected region.
By specifying the Time span Edit the beginning and the end times in seconds. The Samples field is
updated to match the selected region. For example:
28.5 56.8
By specifying the Samples range Edit the beginning and the end indices of the sample range. The
Time span field is updated to match the selected region. For example:
342 654
Note To clear your selection, click Revert.
5In the Data name field, enter the name of the data set containing the selected data.
6 Click Insert. This action saves the selection
7To select another range, repeat steps 4 to 6.
Handling Outliers
Malfunctions can produce errors in measured values, called outliers.Such outliers might be caused by
signal spikes or by measurement malfunctions. If you do not remove outliers from your data, this can
adversely affect the estimated models.
See Also
To learn more about the theory of handling missing data and outliers, see the chapter on preprocessing
data in System Identification: Theory for the User, Second Edition, by Lennart Ljung, Prentice Hall
PTR, 1999.
Tip When signals vary around a large signal level, you can improve computational accuracy of
nonlinear models by detrending the signal means.
Nonlinear ODE parameters (nonlinear grey-box models). For more information, see Estimating
Nonlinear Grey-Box Models on page 5-17.
To simulate or predict the linear model response at the system operating conditions, you can restore the
removed trend to the simulated or predicted model output using the retrendcommand.
For more information about handling drifts in the data, see the chapter on preprocessing data in System
Identification: Theory for the User,Second Edition, by Lennart Ljung, Prentice Hall PTR, 1999.
Examples
How to Detrend Data Using the GUI on page 2-108 How to Detrend Data at the Command Line on
page 2-109
the System Identification Tool, drag the data set you want to detrend to the Working Data rectangle.
To remove mean values from each input and output data signal, select Preprocess > Remove means.
More About Handling Offsets and Trends in Data on page 2-104
Note If you plan to estimate models from this data, your data must be regularly sampled.
Use the detrendcommandtoremovethesignalmeansorlineartrends:
[data_d,T]=detrend(data,Type)
where datais the data to be detrended. The second input argument Type=0removes signal means or
Type=1removes linear trends. data_dis the detrended data. Tis a TrendInfoobject that stores the values of
the subtracted offsets and slopes of the removed trends.
More About Handling Offsets and Trends in Data on page 2-104
a default object for storing input-output offsets that you want to remove from the data.
T = getTrend(data)
where Tis a TrendInfoobject.
2Assign offset values to T.
T.InputOffset=I_value; T.OutputOffset=O_value;
where I_valueis the input offset value, and O_valueis the input offset value.
3Remove the specified offsets from data.
data_d = detrend(data,T)
where the second input argument Tstores the offset values as its properties.
More About Handling Offsets and Trends in Data on page 2-104
See Also
detrend
TrendInfo
Resampling Data
In this section...
WhatIsResampling?onpage2-111
Resampling Data Without Aliasing Effects on page 2-112 See Also on page 2-116
What Is Resampling?
Resampling data signals in the System Identification Toolbox product applies an antialiasing (lowpass)
FIR filter to the data and changes the sampling rate of the signal by decimation or interpolation.
If your data is sampled faster than needed during the experiment, you can decimate it without
information loss. If your data is sampled more slowly than needed, there is a possibility that you miss
important information about the dynamics at higher frequencies. Although you can resample the data at
a higher rate, the resampled values occurring between measured samples do not represent new measured
information about your system. Instead of resampling, repeat the experiment using a higher sampling
rate.
Tip You should decimate your data when it contains high-frequency noise outside the frequency range
of the system dynamics.
Resampling takes into account how the data behaves between samples, which you specify when you
import the data into the System Identification Tool GUI (zero-order or first-order hold). For more
information about the data properties you specify before importing the data, see Importing Data into the
GUI on page 2-17.
You can resample data using the System Identification Tool GUI or the resamplecommand. You can only
resample time-domain data at uniform time intervals.
Examples
Resampling Data Using the GUI on page 2-117 Resampling Data at the Command Line on page
2-118
Folding
Effects with Manual Decimation
Use resampleto decimate the signal before estimating the spectrum and plot the frequency response, as
follows:
g3 = spa(resample(y,1,4));
figure
spectrumplot(g1,g3,g1.Frequency,opt)
The following figure shows that the estimated spectrum of the resampled signal has the same amplitude
as the original spectrum. Thus, there is no indication of folding effects when you use resampleto
eliminate aliasing.
No Folding
Effects When Using resample
Examples
Resampling Data Using the GUI on page 2-117
Resampling Data at the Command Line on page 2-118
See Also
For a detailed discussion about handling disturbances, see the chapter on preprocessing data in System
Identification: Theory for the User,Second Edition, by Lennart Ljung, Prentice Hall PTR, 1999.
The data.InterSampleproperty of the iddataobject is taken into account during resampling (for example,
first-order hold or zero-order hold). For more information, see iddata Properties on page 2-58.
More About Resampling Data on page 2-111
Filtering Data
In this section...
Supported Filters on page 2-120
Choosing to Prefilter Your Data on page 2-120 See Also on page 2-121
Supported Filters
You can filter the input and output signals through a linear filter before estimating a model in the System
Identification Tool GUI or at the command line. How you want to handle the noise in the system
determines whether it is appropriate to prefilter the data.
The filter available in the System Identification Tool GUI is a fifth-order (passband) Butterworth filter.
If you need to specify a custom filter, use the idfiltcommand.
Examples
How to Filter Data Using the GUI on page 2-122 How to Filter Data at the Command Line on page
2-126
See Also
To learn how to filter data during linear model estimation instead, you can set the Focusproperty of the
estimation algorithm to Filterand specify the filter characteristics.
For more information about prefiltering data, see the chapter on preprocessing data in System
Identification: Theory for the User, Second Edition, by Lennart Ljung, Prentice Hall PTR, 1999.
For practical examples of prefiltering data, see the section on posttreatment of data in Modeling of
Dynamic Systems, by Lennart Ljung and Torkel Glad, Prentice Hall PTR, 1994.
HowtoFilterDataUsingtheGUI
In this section...
Filtering Time-Domain Data in the GUI on page 2-122
Filtering Frequency-Domain or Frequency-Response Data in the GUI on page 2-123
5Select
Graphically Draw a rectangle with the mouse on either the input-signal or the output-signal plot to
select the desired frequency interval. Your selection is displayed on both plots regardless of the plot on
which you draw the rectangle. The Range field is updated to match the selected region. If you need to
clear your selection, right-click the plot.
Specify the Range Edit the beginning and the end frequency values. For example:
8.5 20.0(rad/s).
Tip To change the frequency units from rad/sto Hz,select Style > Frequency (Hz). To change the
frequency units from Hzto rad/s, select Style > Frequency (rad/s).
In the Range is list, select one of the following:
Pass band Allows data in the selected frequency range.
Stop band Excludes data in the selected frequency range.
6
7Click Filter to preview the filtered results. If you are satisfied, go to step 8. Otherwise,
8In the Data name field, enter the name of the data set containing the selected data.
9Click Insert to save the selection as a new data set and add it to the Data Board.
10To select another range, repeat steps 5 to 9.
return to step 5.
5Select
Graphically Draw a rectangle with the mouse on either the input-signal or the output-signal plot to
select the desired frequency interval. Your selection is displayed on both plots regardless of the plot on
which you draw the rectangle. The Range field is updated to match the selected region.
If you need to clear your selection, right-click the plot.
Specify the Range Edit the beginning and the end frequency values.
For example:
8.5 20.0(rad/s).
Tip If you need to change the frequency units from rad/sto Hz,select Style > Frequency (Hz). To
change the frequency units from Hzto rad/s, select Style > Frequency (rad/s).
7In the Data name field, enter the name of the data set containing the selected data.
8Click Insert. This action saves the selection as a new data set and adds it to the Data
9To select another range, repeat steps 5 to 8.
Board.
HowtoFilterDataattheCommandLine
In this section...
Simple Passband Filter on page 2-126 Defining a Custom Filter on page 2-127 Causal and
Noncausal Filters on page 2-128
You can define a general single-input/single-output (SISO) system for filtering time-domain or
frequency-domain data. For frequency-domain only, you can specify the (nonparametric) frequency
response of the filter.
You use this syntax to filter an iddataobject datausing a custom filter specified by filter:
fdata = idfilt(data,filter)
filtercanbealsoanyofthefollowing:
filter = idm
filter = {num,den} filter = {A,B,C,D}
idmis a SISO identified linear model or LTI object. For more information about LTI objects, see the
Control System Toolbox documentation.
{num,den}defines the filter as a transfer function as a cell array of numerator and denominator filter
coefficients.
{A,B,C,D}is a cell array of SISO state-space matrices.
Specifically for frequency-domain data, you specify the frequency response of the filter:
filter = Wf
Here, Wfis a vector of real or complex values that define the filter frequency response, where the inputs
and outputs of dataat frequency data.Frequency(kf)are multiplied by Wf(kf). Wfis a column vector with
the length equal to the number of frequencies in data.
When datacontains several experiments, Wfis a cell array with the length equal to the number of
experiments in data.
More About Filtering Data on page 2-120
empty.
u = iddata([],per_u,'Period',.300); 3View the data characteristics in time- and frequency-domain.
% Plot data in time-domain. plot(u);
% Plot the spectrum.
spectrum(spa(u));
4(Optional)
% Construct a polynomial model. m0 =idpoly([1 -1.5 0.7],[0 1 0.5]); % Simulate model output with
Gaussian noise. sim_opt = simOptions('AddNoise',true); sim(m0,u,sim_opt);
A = [1 -1.2 0.7];
B = {[0 1 0.5 0.1],[0 1.5 -0.5],[0 -0.1 0.5 -0.1]}; C=[1 000 0];
Ts = 1;
m = idpoly(A,B,C,'Ts',1);
The leading zeros in the Bmatrix indicate the input delay (nk), which is 1 for each input channel.
2Construct a pseudorandom binary input data.
u = idinput([200,3],'prbs');
3Simulate model output with noise using the input data.
sim(m0,u,simOptions('AddNoise',true))
4Represent the simulation data as an iddataobject.
iodata = iddata(y,u,m.Ts);
5(Optional) Estimate a model of the same order as musing iodata.
na =2;nb= [3 23];nc= 4;nk= [1 11]; me = armax(iodata,[na,nb,nc,nk]);
Use bode(m,me)and compare(iodata,me)to check how closely meand m match.
Data Board.
7Click Transform to add the new data set to the Data Board in the System Identification Tool GUI.
Transforming Frequency-Domain Data
In the System Identification Tool GUI, frequency-domain data has an icon with a green background.
You can transform frequency-domain data to time-domain or frequency-response (frequency-function)
data.
Transforming from time-domain or frequency-domain data to frequency-response data is equivalent to
estimating a nonparametric model of the data using the spafdrmethod.
1In
the System Identification Tool GUI, drag the icon of the data you want to transform to the Working
Data rectangle.
2Select <--Preprocess > Transform data.
3In the Transform to list, select one of the following:
Frequency FunctionCreateanew idfrdobject using the spafdr method. Gotostep4.
Time Domain DataCreateanew iddataobject using the ifft (inverse fast Fourier transform) method.
Go to step 6.
4In the Frequency Spacing list, select the spacing of the frequencies at which the frequency function is
estimated:
linear Uniform spacing of frequency values between the endpoints.
logarithmic Base-10 logarithmic spacing of frequency values between the endpoints.
5In the Number of Frequencies field, enter the number of frequency values.
6In the Name of new data field, type the name of the new data set. This name must be unique in the
Data Board.
7Click Transform to add the new data set to the Data Board in the System Identification Tool GUI.
Transforming Frequency-Response Data
In the System Identification Tool GUI, frequency-response data has an icon with a yellow background.
You can transform frequency-response data to frequency-domain data (iddataobject) or to frequencyresponse data with a different frequency resolution.
When you select to transform single-input/single-output (SISO) frequency-response data to frequencydomain data, the toolbox creates outputs that equal the frequency responses, and inputs equal to 1.
Therefore, the ratio between the Fourier transform of the output and the Fourier transform of the input is
equal to the system frequency response.
For the multiple-input case, the toolbox transforms the frequency-response data to frequency-domain
data as if each input contributes independently to the entire output of the system and then combines
information. For example, if a system has three inputs, u1, u2,and u3and two frequency samples, the
input matrix is set to:
? 10 0? ?10 0?
?
??
In general, for nuinputs and nssamples (the number of frequencies), the input matrix has nucolumns and
(ns? nu)rows.
Note To create a separate experiment for the response from each input, see Transforming Between
Frequency-Domain and Frequency-Response Data on page 2-141.
When you transform frequency-response data by changing its frequency resolution, you can modify the
number of frequency values by changing between linear or logarithmic spacing. You might specify
variable frequency spacing to increase the number of data points near the system resonance frequencies,
and also make the frequency vector coarser in the region outside the system dynamics. Typically, highfrequency noise dominates away from frequencies where interesting system dynamics occur. The
System Identification Tool GUI lets you specify logarithmic frequency spacing, which results in a
variable frequency resolution.
Note The spafdrcommand lets you lets you specify any variable frequency resolution.
1In the System Identification Tool GUI, drag the icon of the data you want to transform to the Working
Data rectangle.
2Select <--Preprocess > Transform data.
In the Transform to list, select one of the following:
Frequency Domain DataCreateanew iddataobject. Gotostep6.
3
the Frequency Spacing list, select the spacing of the frequencies at which the frequency function is
estimated:
linear Uniform spacing of frequency values between the endpoints.
logarithmic Base-10 logarithmic spacing of frequency values between the endpoints.
5In the Number of Frequencies field, enter the number of frequency values.
6In the Name of new data field, type the name of the new data set. This name must be unique in the
Data Board.
7Click Transform to add the new data set to the Data Board in the System Identification Tool GUI.
See Also
For a description of time-domain, frequency-domain, and frequency-response data, see Representing
Data in MATLAB Workspace on page 2-9.
To learn how to transform data at the command line instead of the GUI, see Transforming Data Domain
at the Command Line on page 2-139.
system has three inputs, u1, u2,and u3and two frequency samples, the input matrix is set to: ?10 0? ?10
0?
?
??
In general, for nuinputs and nssamples, the input matrix has nucolumns and (ns? nu)rows.
If you have nyoutputs, the transformation operation produces an output matrix has nycolumns and (ns?
nu) rows using the values in the complex frequency response G(iw) matrix (ny-bynu-byns). In this
example, y1is determined by unfolding G(1,1,:), G(1,2,:),and G(1,3,:)into three column vectors and
vertically concatenating these vectors into a single column. Similarly, y2is determined by unfolding
G(2,1,:), G(2,2,:),and G(2,3,:) into three column vectors and vertically concatenating these vectors.
If you are working with multiple inputs, you also have the option of storing the contribution by each
input as an independent experiment in a multiexperiment data set. To transform an idfrdobject with the
name idfrdobjto a multiexperiment data set datf, where each experiment corresponds to each of the
inputs in idfrdobj
datf = iddata(idfrdobj,'me')
In this example, the additional argument 'me'specifies that multiple experiments are created.
By default, transformation from frequency-response to frequency-domain data strips away frequencies
where the response is infor NaN. To preserve the entire frequency vector, use datf =
iddata(idfrdobj,'inf').Formore information, type help idfrd/iddata.
See Also
Transforming from time-domain or frequency-domain data to frequency-response data is equivalent to
creating a frequency-response model from the data. For more information, see Identifying FrequencyResponse Models on page 3-8.
The display commands compareand plotalso work with complex-valued data and models. To plot the
real and imaginary parts of the data separately, use plot(real(data))and plot(imag(data)),respectively.
Refine ARMAX Model with Initial Parameter Guesses at Command Line on page 3-133
Refine Initial ARMAX Model at Command Line on page 3-134
Extracting Numerical Model Data on page 3-136
Transforming Between Discrete-Time and Continuous-Time Representations on page 3-139
Continuous-Discrete Conversion Methods on page 3-143
Effect of Input Intersample Behavior on Continuous-Time Models on page 3-153
Transforming Between Linear Model Representations on page 3-156
Subreferencing Models on page 3-159
Concatenating Models on page 3-164
Merging Models on page 3-168
Building and Estimating Process Models Using System Identification Toolbox on page 3-169
Determining Model Order and Delay on page 3-195
Model Structure Selection: Determining Model Order and Input Delay on page 3-196
Frequency Domain Identification: Estimating Models Using Frequency Domain Data on page 3-211
Building Structured and User-Defined Models Using System Identification Toolbox on page 3-235
Black-Box Modeling
In this section...
Selecting Black-Box Model Structure and Order on page 3-3 When to Use Nonlinear Model
Structures? on page 3-5 Black-Box Estimation Example on page 3-5
State-space model, which you can estimate by specifying the number of model states
Estimation of some of these structures also uses noniterative estimation algorithms, which further
reduces complexity.
You can configure a model structure using the model order. The definition of model order varies
depending on the type of model you select. For example, if you choose a transfer function
representation, the model order is related to the number of poles and zeros. For state-space
representation, the model order corresponds to the number of states. In some cases, such as for linear
ARX and state-space model structures, you can estimate the model order from the data.
If the simple model structures do not produce good models, you can select more complex model
structures by:
Specifying a higher model order for the same linear model structure. Higher model order increases the
model flexibility for capturing complex phenomena. However, unnecessarily high orders can make the
model less reliable.
Explicitly modeling the noise:
y(t)=Gu(t)+He(t)
where H models the additive disturbance by treating the disturbance as the output of a linear system
driven by a white noise source e(t).
Using a model structure that explicitly models the additive disturbance can help to improve the accuracy
of the measured component G.Furthermore, such a model structure is useful when your main interest is
using the model for predicting future response values.
Using a different linear model structure.
See Linear Model Structureson page 1-21 in the Users Guide.
Using a nonlinear model structure.
Nonlinear models have more flexibility in capturing complex phenomena than linear models of similar
orders. See Available Nonlinear Models on page 1-32 in Users Guide.
Ultimately, you choose the simplest model structure that provides the best fit to your measured data. For
more information, see Estimating Linear Models Using Quick Start.
Regardless of the structure you choose for estimation, you can simplify the model for your application
needs. For example, you can separate out the measured dynamics (G) from the noise dynamics (H) to
obtain a simpler model that represents just the relationship between y and u. You can also linearize a
nonlinear model about an operating point.
You can assessthe need to use a nonlinear model structure by plotting the response of the system to an
input. If you notice that the responses differ depending onthe input level or input sign, try using a
nonlinear model. For example, if the output response to an input step up is faster than the response to a
step down, you might need a nonlinear model.
Before building a nonlinear model of a system that you know is nonlinear, try transforming the input and
output variables such that the relationship between the transformed variables is linear. For example,
consider a system that has current and voltage as inputs to an immersion heater, and the temperature of
the heated liquid as an output. The output depends on the inputs via the power of the heater, which is
equal to the product of current and voltage. Instead of building a nonlinear model for this two-input and
one-output system, you can create a new input variable by taking the product of current and voltage and
then build a linear model that describes the relationship between power and temperature.
If you cannot determine variable transformations that yield a linear relationship between input and
output variables, you can use nonlinear structures such as Nonlinear ARX or Hammerstein-Wiener
models. For a list of supported nonlinear model structures and when to use them, see Available
Nonlinear Models on page 1-32 in Users Guide.
Gs bbsbs2 ()= ++ +
1fs f s2++ + ()
For the mass-spring damper system, this transfer function is: Gs()1
ms 2 cs
which is a system with no zeros and 2 poles.
In discrete-time, the transfer function of the mass-spring-damper system can be:
bz
1
Gz() = 1 fz 1
++()
where the model orders correspond to the number of coefficients of the numerator and the denominator
(nb=1and nf= 2) and the input-output delay equals the lowest order exponent of z1in the numerator
(nk=1).
In continuous-time, you can build a linear transfer function model using the tfestcommand:
m = tfest(data, 2, 0)
where datais your measured input-output data, represented as an iddata object and the model order is the
set of number of poles (2) and the number of zeros (0).
Similarly, you can build a discrete-time model Output Error structure using the following command:
m = oe(data, [1 2 1])
The model order is [ nb nf nk]=[12 1]. Usually, you do not know the model orders in advance. You
should try several model order values until you find the orders that produce an acceptable model.
Alternatively, you can choose a state-space structure to represent the mass-spring-damper system and
estimate the model parameters using the ssestor the n4sidcommand:
m = ssest(data, 2)
where order= 2represents the number of states in the model.
In black-box modeling, you do not need the systems equation of motiononly a guess of the model
orders.
For more information about building models, see Steps for Using the System Identification Tool GUI
on page 12-2 and Model Estimation Commands on page 1-40 in the Users Guide.
The frequency-response function describes the steady-state response of a system to sinusoidal inputs.
For a linear system, a sinusoidal input of a specific frequency results in an output that is also a sinusoid
with the same frequency, but with a different amplitude and phase. The frequency-response function
describes the amplitude change and phase shift as a function of frequency.
For a discrete-time system sampled with a time interval T,the frequency-response model G(z) relates the
Z-transforms of the input U(z) and output Y(z):
Yz GzU z= () ()
In other words, the frequency-response function, G(eiwT),istheLaplace
transformoftheimpulseresponsethatisevaluatedontheimaginaryaxis. The frequency-response function is
the transfer function G(z) evaluated on the unit circle.
The estimation result is an idfrdmodel, which stores the estimated frequency response and its
covariance.
3Specify
the frequencies at which to compute the spectral model in one of the following ways:
In the Frequencies field, enter either a vector of values, a MATLAB expression that evaluates to a
vector, or a variable name of a vector in the MATLAB workspace. For example, logspace(-1,2,500).
Use the combination of Frequency Spacing and Frequencies to construct the frequency vector of
values:
In the Frequency Spacing list, select Linearor Logarithmic frequency spacing.
5In
the Model Name field, enter the name of the correlation analysis model. The model name should be
unique in the Model Board.
6Click Estimate to add this model to the Model Board in the System Identification Tool GUI.
7In the Spectral Model dialog box, click Close.
To view the frequency-response plot, select the Frequency resp check box in the System
Identification Tool GUI. For more information about working with this plot, see Frequency Response
Plots on page 8-42.
8
To view the estimated disturbance spectrum, select the Noise spectrum check box in the System
Identification Tool GUI. For more information about working with this plot, see Noise Spectrum Plots
on page 8-51.
9
10Validate
the model after estimating it. For more information, see Model Validation.
To export the model to the MATLAB workspace, drag it to the To Workspace rectangle in the System
Identification Tool GUI. You can retrieve the responses from the resulting idfrdmodel object using the
bodeor nyquist command.
2k k
Spectrum Normalization
The spectrum of a signal is the square of the Fourier transform of the signal. The spectral estimate using
the commands spa, spafdr,and etfeis normalized by the sampling interval T:
M
iwT
where WM(k) is the lag window, and M is the width of the lag window. The output covariance Ry(kT) is
given by the following discrete representation:
RkT
y
()
1
=ylT kT ylT( )( ) N
l=1
Because there is no scaling in a discrete Fourier transform of a vector, the purpose of T is to relate the
discrete transform of a vector to the physically meaningful transform of the measured signal. This
normalization sets the
units of y() as power per radians per unit time, and makes the frequency
()
=
1
/
T
()
d
2 /T
SEyt2()
1 /T
2Sdy()/T
Tocomparetheleftsideoftheequation(S1)totherightside(S2), enter the following commands in the
MATLAB Command Window:
load iddata1
% Create time-series iddata object
y = z1(:,1,[]);
% Define sample interval from the data T = y.Ts;
% Estimate frequency response
sp = spa(y);
% Remove spurious dimensions
phiy = squeeze(sp.spec);
% Compute average energy from the estimated % energy spectrum, where S1 is scaled by T S1 =
sum(phiy)/length(phiy)/T
% Compute average energy of the signal S2 = sum(y.y.^2)/size(y,1)
In this code, phiycontains y() between = 0 and = T with the
yt() =()?h t z u z dz
0
Tip You can also enter a 2-D vector in the format [min_value max_value].
3In the Order of whitening filter field, specify the filter order.
The prewhitening filter is determined by modeling the input as an autoregressive process of order N. The
algorithm applies a filter of the form A(q)u(t)=u_F(t). That is, the input u(t) is subjected to an FIR filter
A to produce the filtered signal u_F(t). Prewhitening the input by applying a whitening filter before
estimation might improve the quality of the estimated impulse response g.
The order of the prewhitening filter, N, is the order of the A filter. N equals the number of lags. The
default value of N is 10, which you can also specify as [].
4In
the Model Name field, enter the name of the correlation analysis model. The name of the model
should be unique in the Model Board.
5Click Estimate to add this model to the Model Board in the System Identification Tool GUI.
6In the Correlation Model dialog box, click Close.
Next Steps
Export the model to the MATLAB workspace for further analysis by dragging it to the To Workspace
rectangle in the System Identification Tool GUI.
View the transient response plot by selecting the Transient resp check box in the System
Identification Tool GUI. For more information about working with this plot and selecting to view
impulse- versus step-response, see Impulse and Step Response Plots on page 8-33.
yt() t gu tWWWd
f
In discrete-time:
f
yt g k u t k
k1
Prewhitening The input can be pre-whitened by applying an input-whitening filter of order PWto
the data. This minimizes the effect of the neglected tail (k> n) of the impulse response.
1Afilteroforder
yt ka yt k
k
11
This gives both better results for small nandallowsunbiasedestimates when data are generated in closed
loop. impulseestuses NA = 5 for t>0 and NA = 0 (no autoregressive component) for t<0.
Noncausal effects Response for negative lags. It may happen that the data has been generated
partly by output feedback:
f
ut() h k y t k r t
k0
where h(k) is the impulse response of the regulator and r is a setpoint or disturbance term. The existence
and character of such feedback h can be estimated in the same way as g, simply by trading places
between y and u in the estimation call. Using impulseestwith an indication of negative
delays,mi impulseest(,,), nk 0, returns a model miwith
an impulse response
Gs
()
1 sTp1 K pesTd
1In
the System Identification Tool GUI, select Estimate > Process models to open the Process Models
dialog box.
If your model contains multiple inputs, select the input channel in the Input list. This list only appears
when you have multiple inputs. For more information, see Estimating Multiple-Input, Multi-Output
Process Models on page 3-41.
2
3In
the Model Transfer Function area, specify the model structure using the following options:
Under Poles, select the number of poles, and then select All realor Underdamped.
Note You need at least two poles to allow underdamped modes (complex-conjugate pair).
Select the Zero check box to include a zero, which is a numerator term other than a constant, or clear
the check box to exclude the zero.
Select the Delay check box to include a delay, or clear the check box to exclude the delay.
Select the Integrator check box to include an integrator (self-regulating
process),orclearthecheckboxtoexcludetheintegrator.
The Parameterareashowsasmanyactiveparametersasyouincludedin the model structure.
Note By default, the model Name is set to the acronym that reflects the model structure, as described in
Process Model Structure Specification on page 3-40.
In the Initial Guess area, select Auto-selectedto calculate the initial parameter values for the
estimation. The Initial Guess column in the Parameter table displays Auto. If you do not have a good
guess for the parameter values, Autoworks better than entering an ad hoc value.
4
(Optional) If you approximately know a parameter value, enter this value in the Initial Guess column
of the Parameter table. The estimation algorithm uses this value as a starting point. If you know a
parameter value exactly, enter this value in the Initial Guess column, and also select the corresponding
Known check box in the table to fix its value.
5
If youknow the range of possible values for a parameter, enter these values into the corresponding
Bounds field to help the estimation algorithm.
For example, the following figure shows that the delay value Tdis fixed at 2sandisnotestimated.
In the Disturbance Model list, select one of the available options. For more information about each
option, see Disturbance Model Structure for Process Models on page 3-42.
6
In the Focus list, select how to weigh the relative importance of the fit at different frequencies. For
more information about each option, see Assigning Estimation Weightings on page 3-43.
7
In the Initial state list, specify how you want the algorithm to treat initial states. For more information
about the available options, see Specifying Initial Conditions for Iterative Estimation Algorithms on
page 3-43.
8
Tip If you get a bad fit, you might try setting a specific method for handling initial states, rather than
choosing it automatically.
In the Covariance list, select Estimateif you want the algorithm to compute parameter uncertainties.
Effects of such uncertainties are displayed on plots as model confidence regions.
To omit estimating uncertainty, select None. Skipping uncertainty computation might reduce
computation time for complex models and large data sets.
9
10In
the Model Name field, edit the name of the model or keep the default. The name of the model
should be unique in the Model Board.
To view the estimation progress, select the Display Progress check box. This opens a progress viewer
window in which the estimation progress is reported.
11
12Click
Estimate to add this model to the Model Board in the System Identification Tool GUI.
To stop the search and save the results after the current iteration has been completed, click Stop
Iterations. To continue iterations from the current model, click the Continue button to assign current
parameter values as initial guesses for the next search.
13
Next Steps
Validate the model by selecting the appropriate check box in the Model Views area of the System
Identification Tool GUI. For more information about validating models, see Validating Models After
Estimation on page 8-3.
Refine the model by clicking the Value > Initial Guess button to assign current parameter values as
initial guesses for the next search, edit the Name field, and click Estimate.
Export the model to the MATLAB workspace for further analysis by dragging it to the To Workspace
rectangle in the System Identification Tool GUI.
pesTd
This process has two inputs and the response from each input is estimated by a first-order process
model. All parameters are free to vary.
Usethefollowingcommandstoestimateamodel mfrom sample data:
% Load sample data
load co2data
% Sampling interval is 0.5 min (known) Ts = 0.5;
Use the following commands to prepare the data and construct a process model with one pole and a
delay:
% Load sample data
load co2data
% Sampling interval is 0.5 min (known) Ts = 0.5;
% Split data set into estimation data ze % and validation data zv
ze = iddata(Output_exp1,Input_exp1,Ts,...
'TimeUnit','min'); zv = iddata(Output_exp2,Input_exp2,Ts,...
'TimeUnit','min'); mod = idproc({'p1d','p1d'},'TimeUnit','min')
The model parameters Kp, Tp1,and Tdare assigned NaNvalues, which means that the parameters have
not yet been estimated from the data.
Use the Structuremodel property to specify the initial guesses for unknown parameters, minimum/
maximum parameter bounds and fix known parameters.
Set the value of Kpfor the second transfer function to 10and specify it as a fixed parameter. Initialize the
delay values for the two transfer functions to 2 and 5 minutes, respectively. Specify them as free
estimation parameters.
mod.Structure(2).Kp.Value = 10; mod.Structure(2).Kp.Free = false;
mod.Structure(1).Td.Value = 2; mod.Structure(2).Td.Value = 5;
To estimate Tp1and Tdonly, use the following command:
mod_proc = procest(ze, mod, opt) MATLAB computes the following result:
mod_proc =
Process model with 2 inputs: y = G11(s)u1 + G12(s)u2 From input "u1" to output "y1":
Kp
G11(s) = ---------- * exp(-Td*s)
1+Tp1*s
Kp = 2.7448
Tp1 = 0.40544 Td = 1.9745
From input "u2" to output "y1": Kp
G12(s) = ---------- * exp(-Td*s) 1+Tp1*s
Kp = 10
Tp1 = 2.0734
Td = 4.92
An additive ARMA disturbance model exists for output "y1": y = G u + (C/D)e
C(s) = s + 2.702 D(s) = s + 0.6309
Parameterization: 'P1D' 'P1D'
pesTd
Gs KsT1+() = pz
12
++
22
sT s T
ww
Gs
()
=
K
pesTd s
procest(data,'P3Z')to estimate the following structure:
=
Gs KsT
1+
pz()
You can estimate only the dynamic model G, or estimate both the dynamic model and the disturbance
model H. For process models, H is a rational transfer function C/D,wherethe C and D polynomials for a
first- or second-order ARMA model.
In the GUI. To specify whether to include or exclude a noise model in the Process Models dialog box,
select one of the following options from the Disturbance Model list:
None The algorithm does not estimate a noise model (C=D=1). This option also sets Focus to
Simulation.
Order 1 Estimates a noise model as a continuous-time, first-order ARMA model.
Order 2 Estimates a noise model as a continuous-time, second-order ARMA model.
At the command line. Specify the disturbance model using the procestOptionsoption set. For example,
use this command to estimate a first-order transfer function and a first-order noise model:
opt = procestOptions;
opt.DisturbanceModel = 'arma1'; model = procest(data, 'P1D', opt);
For a complete list of values for the DisturbanceModelmodel property, see the procestOptionsreference
page.
iBq()
Cq()
The variables A, B, C, D,and F are polynomials expressed in the time-shift operator q^-1. uiis the ith
input, nu is the total number of inputs, and nkiis the ith input delay that characterizes the transport delay.
The variance of the white noise e(t) is assumed to be . For more information about the time-shift
operator, see Understanding the Time-Shift Operator q on page 3-47.
In practice, not all the polynomials are simultaneously active. Often, simpler forms, such as ARX,
ARMAX, Output-Error, and Box-Jenkins are employed. You also have the option of introducing an
integrator in the noise source so that the general model takes the form:
Aq yt() ()
nu Bq () Cq() 1
i
i1
et()Fqut nk Dq()1 q1
iii
For more information, see Different Configurations of Polynomial Models on page 3-47.
You can estimate polynomial models using time or frequency domain data.
For estimation, you must specify the model order as a set of integers that represent the number of
coefficients for each polynomial you include in your selected structurena for A, nb for B, nc for C, nd
for D,and nf for F.Youmust also specify the number of samples nk corresponding to the input
delaydead timegiven by the number of samples before the output responds to the input.
The number of coefficients in denominator polynomials is equal to the number of poles, and the number
of coefficients in the numerator polynomials is equal to the number of zeros plus 1. When the dynamics
from u(t) to y(t) contain a delay of nk samples, then the first nk coefficients of B are zero. For more
information about the family of transfer-function models, see the corresponding section in System
Identification: Theory for the User,Second Edition, by Lennart Ljung, Prentice Hall PTR, 1999.
but T b ut() ( )
+
12
where y(t) is the output, u(t) is the input, and T is the sampling interval. q-1 is a time-shift operator that
compactly represents such difference equations using1qut ut T):
=
1yt a q yt a q yt2
()++ =
b ()1 1qut bq ut
+
or
Aq yt =))() ( ) ()
In this case, Aq()1 a q1 +2and Bq b q1 2.=+a q
1 =+b q
Note This q description is completely equivalent to the Z-transform form: q corresponds to z.
Different Configurations of Polynomial Models These model structures are subsets of the following
general polynomial equation:
nuiBq()
Cq()
The model structures differ by how many of these polynomials are included in the structure. Thus,
different model structures provide varying levels of flexibility for modeling the dynamics and noise
characteristics.
The following table summarizes common linear polynomial model structures supported by the System
Identification Toolbox product. If you have a specific structure in mind for your application, you can
decide whether the dynamics and the noise have common or different poles. A(q) corresponds to poles
that are common for the dynamic model and the noise model. Using common poles for dynamics and
noise is useful when the disturbances enter the system at the input. Fidetermines the poles unique to the
system dynamics, and D determines the poles unique to the disturbances.
Model Equation Description Structure
ARX
nu
noise source, e(t). This is useful in cases where the disturbance is not stationary.
Box-Jenkins Provides completely independent (BJ)nu Bq() Cq() parameterization for the
Output-Error Use when you want to (OE)nu Bq() parameterize dynamics, but yt()=Fqut nk et()
donotwanttoestimateanoise
model.i=1iii
Note In this case, the noise models is H = 1in the general equation and the white noise source e(t) affects
only the output.
The polynomial models can contain one or more outputs and zero or more inputs.
The System Identification Tool GUI supports direct estimation of ARX, ARMAX, OE and BJ models.
You can add a noise integrator to the ARX, ARMAX and BJ forms. However, you can use polyestto
estimate all five polynomial or any subset of polynomials in the general equation. For more information
about working with pem, see Using polyest to Estimate Polynomial Models on page 3-66.
Continuous-Time Representation of Polynomial Models In continuous time, the general frequencydomain equation is written in terms of the Laplace transform variable s, which corresponds to a
differentiation operation:
AsY s
() ()
=+
FsUs Cs
()
() ()
In the continuous-time case, the underlying time-domain model is a differential equation and the model
order integers represent the number of estimated numerator and denominator coefficients. For example,
na=3 and nb=2 correspond to the following model:
4
13
22
As s asasa
=+ + +
Bs b s b12
=+
You can only estimate continuous-time polynomial models directly using continuous-time frequencydomain data. In this case, you must set the Tsdata property to 0 to indicate that you have continuoustime frequency-domain data, and use the oecommand to estimate an Output-Error polynomial model.
Continuous-time models of other structures such as ARMAX or BJ cannot be estimated. You can obtain
those forms only by direct construction (using idpoly), conversion from other model types, or by
converting a discrete-time model into continuous-time (d2c). Note that the OE form represents a transfer
function expressed as a ratio of numerator (B) and denominator (F) polynomials. For such forms
consider using the transfer function models, represented by idtfmodels. You can estimate transfer
function models using both time and frequency domain data. In addition to the numerator and
denominator polynomials, you can also estimate transport delays. See idtfand tfestfor more information.
Multi-Output Polynomial Models
You can create multi-output polynomial models by using the idpolycommand or estimate them using ar,
arx, bj, oe, armax,and polyest.IntheGUI,you can estimate such models by choosing a multi-output data
set and setting the orders appropriately in the Polynomial Models dialog box. For more details on the
orders of multi-output models, see Polynomial Sizes and Orders of Multi-Output Polynomial Models
on page 3-68.
insight into the physics of your system, you can specify the number of poles and zeros.
In most cases, you do not know the model orders in advance. To get initial model orders and delays for
your system, you can estimate several ARX models with a range of orders and delays and compare the
performance of these models. You choose the model orders that correspond to the best model
performance and use these orders as an initial guess for further modeling.
Because this estimation procedure uses the ARX model structure, which includes the A and B
polynomials, you only get estimates for the na, nb,and nk parameters. However, you can use these
results as initial guesses for the corresponding polynomial orders and input delays in other model
structures, such as ARMAX, OE, and BJ.
If the estimated nk is too small, the leading nb coefficients are much smaller than their standard
deviations. Conversely, if the estimated nk is too large, there is a significant correlation between the
residuals and the input for lags that correspond to the missing B terms. For information about residual
analysis plots, see Residual Analysis on page 8-24.
Estimating Orders and Delays in the GUI
The following procedure assumes that you have already imported your data into the GUI and performed
any necessary preprocessing operations. For more information, see Represent Data.
To estimate model orders and input delays in the System Identification Tool GUI:
In the System Identification Tool GUI, select Estimate > Polynomial and State Space Models to
open the Polynomials and State Space Models dialog box.
1
Tip As a shortcut for entering 1:10for each required model order, click Order Selection.
Click Estimate to open the ARX Model Structure Selection window, which displays the model
performance for each combination of model parameters. The following figure shows an example plot.
3
Select a rectangle that represents the optimum parameter combination and click Insert to estimates a
model with these parameters. For information about using this plot, see Selecting Model Orders from
the Best ARX Structure on page 3-59.
4
This action adds a new model to the Model Board in the System Identification Tool GUI. The default
name of the parametric model contains the model type and the number of poles, zeros, and delays. For
example, arx692is an ARX model with na=6, nb=9, and a delay of two samples.
5Click
Note You cannot estimate model orders when using multi-output data. for estimating other model
structures, as described in How to Estimate Polynomial Models in the GUI on page 3-61.
Estimating Model Orders at the Command Line
You can estimate model orders using the struc, arxstruc,and selstruc commands in combination.
If you are working with a multiple-output system, you must use the struc, arxstruc,and
selstruccommands one output at a time. You must subreference the correct output channel in your
estimation and validation data sets.
For each estimation, you use two independent data setsan estimation data set and a validation data set.
These independent data set can be from different experiments, or data subsets from a single experiment.
For more information about subreferencing data, see Select Data Channels, I/O Data and Experiments
in iddata Objects on page 2-63 and Select I/O Channels and Data in idfrd Objects on page 2-79.
For an example of estimating model orders for a multiple-input system, see Estimating Delays in the
Multiple-Input System in System Identification Toolbox Getting Started Guide.
struc. The struccommand creates a matrix of possible model-order combinations for a specified range of
na, nb,and nkvalues.
For example, the following command defines the range of model orders and delays na=2:5, nb=1:5,and
nk=1:5:
NN = struc(2:5,1:5,1:5))
arxstruc. The arxstruccommand takes the output from struc,estimates an ARX model for each model
order, and compares the model output to the measured output. arxstrucreturns the loss for each model,
which is the normalized sum of squared prediction errors.
For example, the following command uses the range of specified orders NN to compute the loss function
for single-input/single-output estimation data data_eand validation data data_v:
V = arxstruc(data_e,data_v,NN)
Each row in NNcorresponds to one set of orders:
[na nb nk]
selstruc. The selstruccommand takes the output from arxstrucand opens the ARX Model Structure
Selection window to guide your choice of the model order with the best performance.
For example, to open the ARX Model Structure Selection window and interactively choose the optimum
parameter combination, use the following command:
selstruc(V)
For more information about working with the ARX Model Structure Selection window, see Selecting
Model Orders from the Best ARX Structure on page 3-59.
To find the structure that minimizes Akaikes Information Criterion, use the following command:
nn = selstruc(V,'AIC')
where nncontains the corresponding na, nb,and nkorders.
Similarly, to find the structure that minimizes the Rissanens Minimum Description Length (MDL), use
the following command:
nn = selstruc(V,'MDL')
To select the structure with the smallest loss function, use the following command:
nn = selstruc(V,0)
for estimating other model structures, as described in Using polyest to Estimate Polynomial Models
on page 3-66.
Estimating Delays at the Command Line
The delayestcommand estimates the time delay in a dynamic system by estimating a low-order, discretetime ARX model and treating the delay as an unknown parameter.
By default, delayestassumes that na=nb=2and that there is a good signal-to-noise ratio, and uses this
information to estimate nk.
To estimate the delay for a data set data, type the following at the prompt:
delayest(data)
If your data has a single input, MATLAB computes a scalar value for the input delayequal to the
number of data samples. If your data has multiple inputs, MATLAB returns a vector, where each value is
the delay for the corresponding input signal.
To compute the actual delay time, you must multiply the input delay by the sampling interval of the data.
You can also use the ARX Model Structure Selection window to estimate input delays and model order
together, as described in Estimating Model Orders at the Command Line on page 3-57.
SelectingModel Ordersfrom theBestARX Structure You generate the ARX Model Structure Selection
window for your data to select the best-fit model.
For a procedure on generating this plot in the System Identification Tool GUI, see Estimating Orders
and Delays in the GUI on page 3-54. To open this plot at the command line, see Estimating Model
Orders at the Command Line on page 3-57.
The following figure shows a sample plot in the ARX Model Structure Selection window.
You use this plot to select the best-fit model.
Three rectangles are highlighted on the plot in green, blue, and red. Each color indicates a type of bestfit criterion, as follows:
RedBestfitminimizesthesumofthesquaresofthedifferencebetween the validation data output and the
model output. This rectangle indicates the overall best fit.
Green Best fit minimizes Rissanen MDL criterion.
Blue Best fit minimizes Akaike AIC criterion.
In the ARX Model Structure Selection window, click any bar to view the orders that give the best fit.
The area on the right is dynamically updated to show the orders and delays that give the best fit.
For more information about the AIC criterion, see Akaikes Criteria for Model Validation on page
8-86.
ARX:[na nb nk]
ARMAX:[na nb nc nk]
OE:[nb nf nk]
BJ:[nb nc nd nf nk]
This action updates the options in the Polynomial and State Space Models dialog box to correspond with
this model structure. For information about each model structure, see What Are Polynomial Models?
on page 3-45.
Note For time-series data, only AR and ARMA models are available. For more information about
estimating time-series models, see Time-Series Model Identification.
3In
the Orders field, specify the model orders and delays, as follows:
For single-output polynomial models. Enter the model orders and delays according to the sequence
displayed in the Structure field. For multiple-input models, specify nband nkas row vectors with as
many elements as there are inputs. If you are estimating BJ and OE models, you must also specify nfas a
vector.
For example, for a three-input system, nbcan be [1 2 4], where each element corresponds to an input.
For multiple-output models. Enter the model orders, as described in Polynomial Sizes and Orders of
Multi-Output Polynomial Models on page 3-68.
Tip To enter model orders and delays using the Order Editor dialog box, click Order Editor.
(ARX models only) Select the estimation Method as ARX or IV (instrumental variable method). For
information about the algorithms, see Polynomial Model Estimation Algorithms on page 3-73.
4
5(ARX,
ARMAX, and BJ models only) Check the Add noise integration check box to add an integrator
to the noise source, e.
Specify the delay using the Input delay edit box. The value must be a vector of length equal to the
number of input channels in the data. For discrete-time estimations (any estimation using data with
nonzero sample-time), the delay must be expressed in the number of lags. These delays are separate
from the in-model delays specified by the nkorder in the Orders edit box.
6
7In
the Name field, edit the name of the model or keep the default.
In the Focus list, select how to weigh the relative importance of the fit at different frequencies. For
more information about each option, see Assigning Estimation Weightings on page 3-72.
8
In the Initial state list, specify how you want the algorithm to treat initial conditions. For more
information about the available options, see Specifying Initial Conditions for Iterative Estimation
Algorithms on page 3-43.
9
Tip If you get an inaccurate fit, try setting a specific method for handling initial states rather than
choosing it automatically.
In the Covariance list, select Estimateif you want the algorithm to compute parameter uncertainties.
Effects of such uncertainties are displayed on plots as model confidence regions.
10
To omit estimating uncertainty, select None. Skipping uncertainty computation for large, multiple-output
models might reduce computation time.
(ARMAX, OE, and BJ models only) To view the estimation progress in the MATLAB Command
Window, select the Display progress check box. This launches a progress viewer window in which
estimation progress is reported.
11
12 Click Estimate to add this model to the Model Board in the System Identification Tool GUI.
13(Prediction-error method only) To stop the search and save the results after the current iteration
has
been completed, click Stop Iterations.To continue iterations from the current model, click the Continue
iter button to assign current parameter values as initial guesses for the next search.
Next Steps
Validate the model by selecting the appropriate check box in the Model Views area of the System
Identification Tool GUI. For more information about validating models, see Validating Models After
Estimation on page 8-3.
Export the model to the MATLAB workspace for further analysis by dragging it to the To Workspace
rectangle in the System Identification Tool GUI.
Tip For ARX and OE models, you can use the exported model for initializing a nonlinear estimation at
the command line. This initialization may improve the fit of the model. See Using Linear Model for
Nonlinear ARX Estimation on page 4-28, and Using Linear Model for Hammerstein-Wiener
Estimation on page 4-63.
which includes only the A, B, and C polynomials, you must set ndand nfto zero matrices of the
appropriate size. For some simpler configurations, there are dedicated estimation commands such as arx,
armax, bj,and oe, which deliver the required model by using just the required orders. For example,
oe(data, [nb nf nk],opt) estimates an output-error structure polynomial model.
Note To get faster estimation of ARX models, use arxor iv4instead of polyest.
In addition to the polynomial models listed in What Are Polynomial Models? on page 3-45, you can
use polyestto model the ARARX structurecalled the generalized least-squares modelby setting
nc=nf=0. You can also model the ARARMAX structurecalled the extended matrix modelby setting
nf=0.
The third input argument, opt, contains the options for configuring the estimation of the polynomial
model, such as handling of initial conditions, input offsets and search algorithm. You can create and
configure the option set optusing the polyestOptionscommand. The three input arguments can also be
followed by name and value pairs to specify optional model structure attributes such as InputDelay,
ioDelay,and IntegrateNoise.
For ARMAX, Box-Jenkins, and Output-Error modelswhich can only be estimated using the iterative
prediction-error methoduse the armax, bj, and oeestimation commands, respectively. These
commands are versions of polyestwith simplified syntax for these specific model structures, as follows:
m = armax(Data,[na nb nc nk]) m = oe(Data,[nb nf nk])
m = bj(Data,[nb nc nd nf nk])
Similar to polyest, you can specify as input arguments the option set configured using commands
armaxOptions, oeOptions,and bjOptionsfor the estimators armax, oe,and bjrespectively. You can also
use name and value pairs to configure additional model structure attributes.
Tip If your data is sampled fast, it might help to apply a lowpass filter to the data before estimating the
model, or specify a frequency range for the Focus property during estimation. For example, to model
only data in the frequency range 0-10 rad/s, use the Focusproperty, as follows:
opt = oeOptions('Focus',[0 10]) m = oe(Data, [nb nf nk], opt)
For more information about validating your model, see Validating Models After Estimation on page
8-3.
You can use pemor polyestto refine parameter estimates of an existing polynomial model (of any
configuration), as described in Refining Linear Parametric Models on page 3-130.
For more information, see polyest, pemand idpoly.
A Ny-byNyarray of row vectors A{i,j}contains coefficients of relation between output yiand output yj
B Ny-byNuarray of row vectors B{i,j}contain coefficients of relations between output yiand input uj
na :
Ny-byNy
matrix
such
that each
entry
contains
the
degree
of the
corresponding A
polynomial.
nk:
Ny-byNumatrix
such
that each
entry
contains
the
number
of
leading
fixed
zeros
of the
corresponding B
polynomial
(input
delay).
nb:
Ny-byNumatrix
such
nb(i,j)
C,D Ny-by-1 array of row vectors C{i}and D{i}contain coefficients of relations between output yiand
noise ei
F Ny-byNuarray of row vectors F{i,j}contains coefficients of relations between output yiand input uj
=
length(B{i,j})nk(i,j).
nc and
ndare
Ny-by-1
matrices
such
that each
entry
contains
the
degree
of the
corresponding
C and D
polynomial,
respectively.
nf:
Ny-byNumatrix
such
that each
entry
contains
the
degree
of the
corresponding
F
polynomial.
For more information, see idpoly.
For example, consider the ARMAX set of equations for a 2 output, 1 input model:
y (t) + 0.5 y (t-1) + 0.9 y (t-1) + 0.1 y (t-2) = u(t) + 5 u(t-1) + 2 u(t-2) + e (t) + 0.01 e 11 2 2 11
y (t) + 0.05 y (t-1) + 0.3 y (t-2)
2222 2 2= 10 u(t-2) + e (t) + 0.1 e (t-1) + 0.02 e (t-2)2
y1andy2represent the two outputs and u represents the input variable. e1 and e2represent the white noise
disturbances on the outputs, y1and y2, respectively. To represent these equations as an ARMAX form
polynomial using idpoly,configurethe A, B,and Cpolynomialsasfollows:
A = cell(2,2);
A{1,1} = [1 0.5]; A{1,2} = [0 0.9 0.1]; A{2,1} = [0]; A{2,2} = [1 0.05 0.3];
B = cell(2,1);
B{1,1} = [1 5 2]; B{2,1} = [0 0 10];
C = cell(2,1);
C{1} = [1 0.01]; C{2} = [1 0.1 0.02];
model = idpoly(A,B,C)
modelis a discrete-time ARMAX model with unspecified sample-time.
When estimating such models, you need to specify the orders of these polynomials as input arguments.
In the System Identification Tool GUI. You can enter the matrices directly in the Orders field.
At the command line. Define variables that store the model order matrices and specify these variables
in the model-estimation command.
Tip To simplify entering large matrices orders in the System Identification Tool GUI, define the variable
NN=[NA NB NK]at the command line. You can specify this variable in the Orders field.
This information supports the estimation procedures How to Estimate Polynomial Models in the GUI
on page 3-61 and Using polyest to Estimate Polynomial Models on page 3-66.
In the System Identification Tool GUI. For ARMAX, OE, and BJ models, set Initial state to one of
the following options:
Auto Automatically chooses Zero, Estimate,or Backcastbased on the estimation data. If initial states
have negligible effect on the prediction errors, the initial states are set to zero to optimize algorithm
performance.
Zero Sets all initial states to zero.
Estimate Treats the initial states as an unknown vector of parameters and estimates these states from
the data.
Backcast Estimates initial states using a smoothing filter.
At the command line. Specify the initial conditions as an estimation option. Use polyestOptionsto
configure options for the polyestcommand, armaxOptionsfor the armaxcommand etc. Set the
InitialConditionoption to the desired value in the option set. For example, use this command to estimate
an ARMAX model and set the initial states to zero:
opt = armaxOptions('InitialCondition','zero') m = armax(data,[2 2 2 3],opt)
For a complete list of values for the InitialConditionestimation option, see the armaxOptionsreference
page.
1Load
a sample data set z8with three inputs and one output, measured at 1-second intervals and
containing 500 data samples:
load iddata8
2Use armaxto both construct the idpolymodel object, and estimate the parameters:
nu
Typically you try different model orders and compare results, ultimately choosing the simplest model
that best describes the system dynamics. The following command specifies the estimation data set,
z8,andtheordersof the A, B,and C polynomials as na, nb,and nc, respectively. nkof [0 0 0] specifies that
there is no input delay for all three input channels.
opt = armaxOptions;
opt.Focus = 'simulation';
opt.SearchOption.MaxIter = 50;
opt.SearchOption.Tolerance = 1e-5; na = 4;
nb =[32 3];
nc = 4;
nk =[00 0];
m_armax = armax(z8, [na nb nc nk], opt)
Focus , Tolerance,and MaxIterare estimation options that configure the estimation objective function and
the attributes of the search algorithm. The Focusoption specifies whether the model is optimized for
simulation or prediction applications. The Toleranceand MaxItersearch options specify when to stop
estimation. For more information about these properties, see the armaxOptionsreference page.
armax is a version of polyestwith simplified syntax for the ARMAX model structure. The armaxmethod
both constructs the idpolymodel object and estimates its parameters.
3To view information about the resulting model object, type the following at
the prompt:
m_armax
MATLAB returns the following information about this model object:
m_armax =
Discrete-time ARMAX model: A(z)y(t) = B(z)u(t) + C(z)e(t) A(z) = 1 - 1.284 z^-1 + 0.3048 z^-2 + 0.2648 z^-3 - 0.05708
z^-4
B1(z) = -0.07547 + 1.087 z^-1 + 0.7166 z^-2
B2(z) = 1.019 + 0.1142 z^-1
B3(z) = -0.06739 + 0.06828 z^-1 + 0.5509 z^-2
C(z) = 1 - 0.06096 z^-1 - 0.1296 z^-2 + 0.02489 z^-3 - 0.04699 z^-4
Sample time: 1 seconds
Parameterization:
Polynomial orders: na=4 nb=[3 2 3] nc=4 nk=[0 0 0]
m_armaxis an idpolymodel object. The coefficients represent estimated parameters of this polynomial
model.
Tip You can use present(m_armax)to show additional information about the model, including parameter
uncertainties.
4To view all property values for this model, type the following command:
get(m_armax)
MATLAB returns the following information:
a: [1 -1.2836 0.3048 0.2648 -0.0571] b: {1x3 cell}
c: [1 -0.0610 -0.1296 0.0249 -0.0470] d: 1
f: {[1] [1] [1]}
Variable: 'z^-1'
ioDelay: [0 0 0]
IntegrateNoise: 0
Structure: [1x1 pmodel.polynomial]
NoiseVariance: 0.9899
Report: [1x1 idresults.polyest]
InputDelay: [3x1 double]
OutputDelay: 0
Ts: 1
TimeUnit: 'seconds'
InputName: {3x1 cell}
InputUnit: {3x1 cell}
InputGroup: [1x1 struct]
OutputName: {'y1'}
OutputUnit: {''}
OutputGroup: [1x1 struct]
Name: ''
Notes: {}
UserData: []
The Reportmodel property contains detailed information on the estimation results. To view the
properties and values inside Report,usedotnotation. For example:
5
m_armax.Report
This action displays the contents of estimation report such as model quality measures (Fit), search
termination criterion (Termination), and a record of estimation data
(DataUsed)andoptions(OptionsUsed).
Status: 'Estimated using POLYEST with Focus = "simulation"' Method: 'ARMAX' InitialCondition: 'zero' Fit: [1x1 struct]
Parameters: [1x1 struct] OptionsUsed: [1x1 idoptions.polyest]
RandState: [1x1 struct] DataUsed: [1x1 struct] Termination: [1x1 struct]
It is often easier to define a parameterized state-space model in continuous time because physical laws
are most often described in terms of differential equations. In this case, the matrices F, G, H,and D
contain elements with physical significancefor example, material constants. x0 specifies the initial
states. You can estimate continuous-time state-space model using both timeand frequency-domain data.
Note K = 0 gives the state-space representation of an Output-Error model. For more information about
Output-Error models, see What Are Polynomial Models? on page 3-45.
Discrete-Time Representation
Discrete-time state-space models provide the same type of linear difference relationship between the
inputs and the outputs as the linear ARX model, but are rearranged such that there is only one delay in
the expressions. The discrete-time state-space model structure is often written in the innovations form
that describes noise:
x kT( ) () () ()
+= + +
ykT() () () ()
=+ +
x() = x0
where T is the sampling interval, u(kT) is the input at time instant kT,and y(kT) is the output at time
instant kT.
Note K=0 gives the state-space representation of an Output-Error model. For more information about
Output-Error models, see What Are Polynomial Models? on page 3-45.
Relationship Between Continuous-Time and Discrete-Time State Matrices
The relationships between the discrete state-space matrices A, B, C, D,and K and the continuous-time
state-space matrices F, G, H, D,and K are given for piece-wise-constant input, as follows:
AeFT
=
T
=BeGdF
0
CH
=
These relationships assume that the input is piece-wise-constant over time intervals kT t< +k () .
The exact relationship between K and K is complicated. However, for short sampling intervals T, the
following approximation works well: T
= KeKdF
0
State-Space Representation of Transfer Functions For linear models, the general symbolic model
= +
1 A K I
ny
where Inxis the nx-bynx identity matrix, Inyis the nx-bynx identity matrix, and ny is the dimension of y
and e. The state-space representation in the continuous-time case is similar.
Structured parameterization lets you specify the fixed values of specific parameters and exclude
these parameters from estimation. You choose which entries of the system matrices to estimate and
which to treat as fixed.
Completely arbitrary mapping of user-chosen parameters to state-space matrices. For more
information, see Estimating Linear Grey-Box Models on page 5-6.
4Verify
Click Estimate to open the Model Order Selection window, which displays the relative measure of
how much each state contributes to the input-output behavior of the model (log of singular values of the
covariance matrix). The following figure shows an example plot.
5
Select the rectangle that represents the cutoff for the states on the left that provide a significant
contribution to the input-output behavior, and click Insert to estimate a model with this order. Red
indicates the recommended choice. In the previous figure, states 1 and 2 provide the most significant
contribution. The contributions to the right of state 2 drop significantly. For information about using the
Model Order Selection window, see Using the Model Order Selection Window on page 3-88.
6
This action adds a new model to the Model Board in the System Identification Tool GUI. The default
name of the parametric model combines the string n4sand the selected model order.
7Click
You can use this model as an initial guess for estimating other state-space models, as described in How
to Estimate State-Space Models in the GUI on page 3-89.
Note You can specify additional attributes of the model structure when searching for best orders, such as
input delays, the presence of feedthrough, the canonical form and the model sample time.
Estimate Model With Selected Order at the Command Line You can estimate the state-space model
with a selected order using the n4sid and ssestcommands.
Use following syntax to specify the range of model orders to try for a specific input delay.
m = n4sid(data,n1:n2); where datais the estimation data set, n1and n2specify the range of orders, and
nkspecifies the input delay.
This command opens the Model Order Selection window. For information about using this plot, see
Using the Model Order Selection Window on page 3-88.
Alternatively, you can use the ssestcommand to open the Model Order Selection window, as follows:
m = ssest(data, nn)
where nn = [n1,n2,...,nN]specifies the vector or range of orders you want to try. n4sidestimates a model
whose sample time matches that of data, hence a discrete-time model for time domain data.
ssestestimates a continuous-time model by default. You can change the default setting by including the
Tsname and value pair input arguments in the estimation command. For example, to estimate a discretetime model of optimal order using ssest,assuming Data.Ts>0,type:
model = ssest(data,nn,'Ts',data.Ts); To omit opening the Model Order Selection window and
automatically select the best order, use the following syntax:
m = n4sid(data,'best')
Using the Model Order Selection Window
You can generate the Model Order Selection window for your data to select the number of states that
provide the highest relative contribution to the input-output behavior of the model (log of singular
values of the covariance matrix).
For a procedure on generating this plot in the System Identification Tool GUI, see Estimate Model
With Selected Order in the GUI on page 3-84. To open this plot at the command line, see Estimate
Model With Selected Order at the Command Line on page 3-87.
The following figure shows a sample Model Order Selection window.
The horizontal axis corresponds to the model order n. The vertical axis, called Log of Singular values,
shows the singular values of a covariance matrix constructed from the observed data.
You use this plot to decide which states provide a significant relative contribution to the input-output
behavior, and which states provide the smallest contribution. Based on this plot, select the rectangle that
represents the cutoff for the states on the left that provide a significant contribution to the input-output
behavior. The recommended choice is shown in red.
For example, in the previous figure, states 1 and 2 provide the most significant contribution. However,
the contributions of the states to the right of state 2 drop significantly. This sharp decrease in the log of
the singular values after n=2 indicates that using two states is sufficient to get an accurate model.
This action updates the options in the Polynomial and State Space Models dialog box to correspond with
this model structure. For information about each model structure, see What Are State-Space Models?
on page 3-79.
3In
Tip To enter model order using the Order Editor dialog box, click Order Editor. Using this editor, you
can also configure options that influence the estimation such as N4Weightand N4Horizon.
Select the estimation Method as N4SID or PEM. For more information about these methods, StateSpace Model Estimation Algorithms on page 3-112.
4
Specify whether the model has feedthrough or not. In the Feedthrough edit box, enter a logical vector
of length equal to number of inputs. For example, for a model with 2 inputs, you may enter [true
6
false],which means that the first input has direct feedthrough to the models outputs while the second
input does not.
7Select
Specify any input delays using the Input delay edit box. Specify the value as a vector of length equal
to number of inputs. For continuous-time models, the delay must be specified in seconds. For discretetime models, specify the value in terms on number of lags (multiples of sample data time).
8
9In
the Name field, edit the name of the model or keep the default. The name of the model should be
unique in the Model Board.
In the Focus list, select how to weigh the relative importance of the fit at different frequencies. For
more information about each option, see Assigning Estimation Weightings on page 3-110.
10
In the Initial state list, specify how you want the algorithm to treat initial states. For more
information about the available options, see Specifying Initial States for Iterative Estimation
Algorithms on page 3-111.
11
Tip If you get an inaccurate fit, try setting a specific method for handling initial states rather than
choosing it automatically.
In the Covariance list, select Estimateif you want the algorithm to compute parameter uncertainties.
Effects of such uncertainties are displayed on plots as model confidence regions.
12
To omit estimating uncertainty, select None. Skipping uncertainty computation reduces computation
time for complex models and large data sets.
(PEM only) To view the estimation progress, select the Display progress check box. This launches a
progress viewer window in which estimation progress is reported.
13
14Click
(PEM only) To stop the search and save the results after the current iteration has been completed,
click Stop Iterations. To continue iterations from the current model, click the Continue iter button to
assign current parametervaluesasinitialguessesforthenextsearch.
15
Next Steps
Validate the model by selecting the appropriate check box in the Model Views area of the System
Identification Tool GUI. For more information about validating models, see Validating Models After
Estimation on page 8-3.
Export the model to the MATLAB workspace for further analysis by dragging it to the To Workspace
rectangle in the System Identification Tool GUI.
The structured estimation approach is also referred to as grey-box modeling. However, in this toolbox,
the grey box modeling terminology is used only when referring to idgreyand idnlgreymodels.
Using the structured estimation approach, you cannot specify relationships among state-space
coefficients. Each coefficient is essentially considered to be independent of others. For imposing
dependencies, or to use more complex forms of parameterization, use the idgreymodel and the
associated greyestestimator.
Estimating State-Space Models Using ssest and n4sid You can estimate continuous-time and discretetime state-space model using the iterative estimation command ssestthat minimizes the prediction errors
to obtain maximum-likelihood values. You can also use the noniterative subspace estimator n4sid.
Use the following general syntax to both configure and estimate state-space models:
m = ssest(data,n,opt,Name,Value)
where datais the estimation data, nis the model order. optcontains the options for configuring the
estimation of the state-space models. These options include the handling of the initial conditions, input
offset, estimation focus and search algorithm options. opt can be followed by name and value pair input
arguments that specify optional model structure attributes such as the presence of feedthrough, the
canonical form of the model, and input delay. For more information, see ssest.
As an alternative to ssest,youcanuse n4sid:
m = n4sid(data,n,opt,Name,Value)
Unless the sample time is specified as a name and value pair input argument, ssestestimates a
continuous-time model, while n4sidestimates a model whosesampletimematchesthatofdata.
Note ssestuses n4sidto initialize the state-space matrices, and takes longer than n4sidto estimate a model
but typically provides better fit to data.
For more information about estimating model order, see Estimate Model With Selected Order at the
Command Line on page 3-87.
For information about validating your model, see Validating Models After Estimation on page 8-3
Choosing the Structure of A, B, C Matrices
By default, all entries of the A, B,and C state-space matrices are treated as free parameters. Using the
Formname and value pair input argument of ssest, you can choose various canonical forms that employ
fewer parameters, such as the companion and modal forms.
For more information about estimating a specific state-space parameterization, see the following topics:
How to Estimate Free-Parameterization State-Space Models on page 3-98
How to Estimate State-Space Models with Canonical Parameterization on page 3-99
How to Estimate State-Space Models with Structured Parameterization on page 3-100
Choosing Between Continuous-Time and Discrete-Time Representations
For estimation of state-space models, you have the option of switching the model sample time between
zero and that of the estimation data. You can do this using the Tsname and value pair input argument.
By default, ssestestimates a continuous-time model. If you are using data set with nonzero sample
time, data, which includes all time domain data, you can also estimate a discrete-time model by using:
model = ssest(data,nx,'Ts',data.Ts);
If you are using continuous-time frequency-domain data, you cannot estimate a discrete-time model.
By default, n4sidestimates a model whose sample time matches that of the data. Thus, for time-domain
data, n4siddelivers a discrete-time model. You can estimate a continuous-time model by using:
model = n4sid(data,nx,'Ts',0);
Choosing to Estimate D, K, and X0 Matrices
For state-space models with any parameterization, you can specify whether to estimate the D, K and X0
matrices, which represent the input-to-output feedthrough, noise model and the initial states,
respectively.
For state-space models with structured parameterization, you can also specify to estimate the D matrix.
However, for free and canonical forms, the structure of the D matrix is set based on your choice of
'Feedthrough'name and value pair input argument.
DMatrix.By default, the Dmatrixisnotestimatedanditsvalueisfixedto zero, except for static models.
Black box estimation: Use the Feedthroughname and value pair input argument to denote the
presence or absence of feedthrough from individual inputs. For example, in case of a two input model
such that there is feedthrough from only the second output, use model =
n4sid(data,n,'Feedthrough',[false true]);.
Structured estimation: Configure the values of the
init_sys.Structure.d,where init_sysis an idssmodel that represents the desired model structure. To force
no feedthrough for the i-th input, set:
init_sys.Structure.d.Value(:,i) = 0; init_sys.Structure.d.Free = true; init_sys.Structure.d.Free(:,i) = false;
The first line specifies the value of the i-th column of D as zero. The next line specifies all the elements
of D as free, estimable parameters. The last line specifies that the i-th column of the D matrix is fixed for
estimation.
Alternatively, use ssformwith 'Feedthrough'name-value pair..
KMatrix.K represents the noise matrix of the model, such that the noise component of the model is:.
xAx Ke nyCxe
For frequency-domain data, no noise model is estimated and K is set to 0. For time-domain data, K is
estimated by default in the black box estimation setup.
Black box estimation: Use the DisturbanceModelname and value pair input argument to indicate if
the disturbance component is fixed to zero (specify Value = `none') or estimated as a free parameter
(specify Value = `estimate'). For example, use model = n4sid(data,n,'DisturbanceModel','none').
Structured estimation: Configure the value of the
init_sys.Structure.kparameter, where init_sysis an idss
model that represents the desired model structure. You can fix some K matrix coefficients to known
values and prescribe minimum/maximum bounds for free coefficients. For example, to estimate only the
first column of the K matrix for a two output model:
kpar = init_sys.Structure.k;
kpar.Free(:,1) = true;
kpar.Free(:,2) = false;
kpar.Value(:,2) = 0; % second column value is fixed to zero init_sys.Structure.k = kpar;
Alternatively, use ssform.
When not sure how to easily fix or free all coefficients of K, initially you can omit estimating the noise
parameters in K to focus on achieving a reasonable model for the system dynamics. After estimating the
dynamic model, you can use ssestto refine the model while configuring the K parameters to be free. For
example:
init_sys = ssest(data, n,'DisturbanceModel','none'); init_sys.Structure.k.Free = true;
sys = ssest(data, init_sys);
where init_sysis the dynamic model without noise.
To set K to zero in an existing model, you can set its Valueto 0and Free flag to false:
m.Structure.k.Value = 0; m.Structure.k.Free = false;
X0 Matrices. The initial state vector X0 is obtained as the by-product of model estimation. The
n4sidand ssestcommands return the value of X0 as their second output arguments. You can choose how
to handle initial conditions during model estimation by using the InitialStateestimation option. Use
n4sidOptions(for n4sid)and ssestOptions(for ssest) to create the estimation option set. For example, in
order to hold the initial states to zero during estimation using n4sid:
opt = n4sidOptions;
opt.InitialState = 'zero'; [m,X0] = n4sid(data,n,opt);
The returned X0variable is a zero vector of length n.
When you estimate models using multiexperiment data, the X0matrix contains as many columns as data
experiments.
For a complete list of values for the InitialStatesoption, see Specifying Initial States for Iterative
Estimation Algorithms on page 3-111.
Suppose that you have no knowledge about the internal structure of the discrete-time state-space model.
To quickly get started, use the following syntax:
m = ssest(data)
where datais your estimation data. This command estimates a continuous-time state-space model for an
automatically selected order between 1 and 10.
To find a model of a specific order n, use the following syntax:
m = ssest(data,n)
The iterative algorithm ssestis initialized by the subspace method n4sid. You can use n4siddirectly, as an
alternative to ssest:
m = n4sid(data,n)
for the five state-space matrices, A, B, C, D,and K. For each parameter, you can set the following
attributes:
Value Parameter values.
Minimum Minimum value that the parameter can assume during estimation.
Maximum Maximum value that the parameter can assume during estimation.
Free Boolean specifying whether the parameter is a free estimation variable. If you want to fix the
value of a parameter during estimation, set the corresponding Free = false. For example, if A is a 3-by-3
matrix of the model sys, sys.Structure.a.Free = eye(3)fixes all of the off-diagonal entries in A, to the
values specified in sys.Structure.a.Value.Inthis case, only the diagonal entries in A are estimable.
Scale Scale of the parameters value. Scaleis not used in estimation.
Info Structure array for storing parameter units and labels. The structure has Labeland Unitfields.
Use these fields for your convenience, to store strings that describe parameter units and labels.
For example, suppose that you constructed a nominal state-space model m with the following Amatrix:
A = [2 0; 0 3]
Suppose you want to fix A(1,2)=A(2,1)=0. Todothis,use:
m.Structure.a.Value(1,2) = 0; m.Structure.a.Value(2,1) = 0; m.Structure.a.Free(1,2) = false;
m.Structure.a.Free(2,1) = false;
Alternatively, to quickly configure the parameterization and whether to estimate feedthrough and
disturbance dynamics, use ssform.
The estimation algorithm only estimates the parameters in Afor which m.Structure.a.Freeis true.
Finally, use ssestto estimate the model, as described in How to Estimate State-Space Models at the
Command Line on page 3-92.
Use physical insight, whenever possible, to initialize the parameters for the iterative search algorithm.
Because it is possible that the numerical minimization gets stuck in a local minimum, try several
different initialization values for the parameters. For random initialization, use the initcommand. When
the model structure contains parameters with different orders of magnitude, try to scale the variables so
that the parameters are all roughly thesamemagnitude.
The iterative search computes gradients of the prediction errors with respect to the parameters using
numerical differentiation. The step size is specified by the nuderstcommand. The default step size is
equal to 104times the absolute value of a parameter or equal to 107, whichever is larger. To specify a
different step size, edit the nuderstMATLAB file.
Are Grey-Box Models Similar to State-Space Models with Structured Parameterization?
Structured parameterization state-space models are similar to grey-box modeling. However, the statespace models are simpler to estimate than grey-box models. The structured estimation approach is also
referred to as grey-box modeling. However, in this toolbox, the grey box modeling terminology is
used only when referring to idgreyand idnlgreymodels. Using the structured estimation approach, you
cannot specify relationships among state-space coefficients. Each coefficient is essentially considered to
be independent of others. For imposing dependencies, or to use more complex forms of
parameterization, use the idgreymodel and the associated greyest estimator.
4Estimate
The parameter
The motor is at rest at t=0, but its angular position 3is unknown. Suppose that the approximate nominal
values of the unknown parameters are 1 =1
and 2 = 025 . The variance of the errors in the position measurement is 0.01, and the variance in the
angular velocity measurements is 0.1.For more information about this example, see the section on statespace models in System Identification: Theory for the User, Second Edition, by Lennart Ljung, Prentice
Hall PTR, 1999.
The continuous-time state-space model structure is defined by the following equation:
xt() Fxt Gut Kwt()
=+ +
yt() Hx t Dut wt()
=+ +
xx=00
simulate this system using the sampling interval T = 0.1for input u and the noise realization e, use
the following commands:
e = randn(300,2);
u = idinput(300);
simdat = iddata([],u,'Ts',0.1);
simopt = simOptions('AddNoise', true, 'NoiseData', e) y = sim(m,simdat,simopt)
The continuous system is sampled using Ts=0.1for simulation purposes. The noise sequence is scaled
according to the matrix m.NoiseVariance..
If you discover that the motor was not initially at rest, you can estimate x2(0) by setting the second
bq
12
}
den
(()
2
112
qaqaq }1 2
The roots of num(q^-1)and den(q^-1) are expressed in terms of the lag variable q^-1.
Delays
In continuous-time, input and transport delays are of the form:
num s() s W () ()Ys()
den seUs Es
Where represents the delay.
In discrete-time:
num
yt()
denutW ) () where num and den are polynomials in the lag operator q^(-1).
Perform any required data preprocessing operations. If input and/or output signals contain nonzero
offsets, consider detrending your data. See Ways to Prepare Data for System Identification on page
2-6.
2
3In
the System Identification Tool, select Estimate > Transfer Function Models
4Specify
the number of
The Model Orders dialog box opens where you specify the number of poles and zeros for each input/
output pair. Use the Output list to select an output.
5Select
Continuous-time or Discretetime to specify whether the model is a continuous- or discrete-time transfer function.
For discrete-time models, the number of poles and zeros refers to the roots of the numerator and
denominator polynomials expressed in terms of the lag variable q^-1.
6(For
Hz bbz bz bz
11 2
12
az
When the model has direct feedthrough, b0is a free parameter whose value is estimated along with the
rest of the model parameters b1, b2, b3, a1, a2. When the model has no feedthrough, b0is fixed to zero.
For SISO models, select the Feedthrough check box.
For models that are multi input, multi output or both, click Feedthrough.
The Model Orders dialog box opens, where you specify to estimate the feedthrough for each input/
output pair separately. Use the Output list to select an output.
Expand the I/O Delay section to specify nominal values and constraints for transport delays for
different input/output pairs.
7
Use the Output list to select an output. Select the Fixed check box to specify a transport delay as a fixed
value. Specify its nominal value in the Delay field.
8Expand
In the Minimum and Maximum fields, specify the frequency range over which the transfer function
model must fit the data.
Select Display progress to view the progress of the optimization.
Select Estimate covariance to estimate the covariance of the transfer function parameters.
Specify how to treat the initial conditions in the Initial condition list. For more information, see
Specifying Initial Conditions for Iterative Estimation Algorithms on page 3-127.
Specify the algorithm used to initialize the values of the numerator and denominator coefficients in the
Initialization method list.
'iv' Instrument Variable approach.
'svf' State Variable Filters approach.
'gpmf' Generalized Poisson Moment Functions approach.
'n4sid' Subspace state-space estimation approach.
`all' Combination of all of the above approaches. The software tries all the above methods and
selects the method that yields the smallest value of prediction error norm.
9Click
Iterations Options to specify the options for controlling the iterations. The Options for Iterative
Minimization dialog box opens.
12Export
the model to the MATLAB workspace for further analysis. Drag the model to the To
Workspace rectangle in the System Identification Tool.
Input/Output data. See Representing Time- and Frequency-Domain Data Using iddata Objects on
page 2-55. For supported data formats, see Data Supported by Transfer Function Models on page
3-115.
Performed any required data preprocessing operations. You can detrend your data before estimation.
For more information, see Ways to Prepare Data for System Identification on page 2-6.
Alternatively, you can specify the input/output offset for the data using an estimation option set. Use
tfestOptionsto create the estimation option set. Use the InputOffsetand OutputOffsetname and value
pairs to specify the input/output offset.
Estimate continuous-time and discrete-time transfer function models using tfest. The output of tfestis an
idtfobject, which represents the identified transfer function.
The general workflow in estimating a transfer function model is:
1Createadataobject(iddataor idfrd) that captures the experimental data.
2(Optional) Specify estimation options using tfestOptions.
3(Optional) Create a transfer function model that specifies the expected model structure and any
constraints on the estimation parameters.
4Use tfestto identify the transfer function model, based on the data. 5Validate the model. See Model
Validation.
How to Estimate Transfer Function Models with Transport Delay to Fit Given
Frequency Response Data
This example shows how to identify a transfer function to fit a given frequency response data (FRD)
containing additional phase roll off induced by input delay.
Obtain frequency response data. For this example, use bodeto obtain the magnitude and phase response
data for the following system:
Hs e
5s s02
3221
sss
Use 100 frequency points, ranging from 0.1 rad/s to 10 rad/s, to obtain the frequency response data. Use
frdto create a frequency response data object.
freq = logspace(-1,1,100);
[mag, phase] = bode(tf([1 .2],[1 2 1 1],'InputDelay',.5),freq); data = frd(mag.*exp(1j*phase*pi/
180),freq);
datais an iddataobject that contains frequency response data for the described system.
Estimate a transfer function using data. Specify an unknown transport delay for the identified transfer
function.
np = 3;
nz = 1;
iodelay = NaN;
sys = tfest(data,np,nz,iodelay)
npand nzspecify the number of poles and zeros in the identified transfer function, respectively.
iodelayspecifies an unknown transport delay for the identified transfer function.
sysis an idtfmodel containing the identified transfer function.
In the first situation, you have already estimated a parametric model and wish to update the values of its
free parameters to improve the fit to the estimation data. This is useful if your previous estimation
terminated because of search algorithm constraints such as maximum number of iterations or function
evaluations allowed reached. However, if your model captures the essential dynamics, it is usually not
necessary to continue improving the fitespecially when the improvement is a fraction of a percent.
In the second situation, you might have constructed a model using one of the model constructors
described in Commands for Constructing Model Structures on page 1-25. In this case, you built initial
parameter guesses into the model structure and wish to refine these parameter values.
3In the Linear Parametric Models dialog box, select By Initial Modelfrom
4Enter the model name into the Initial model field, and press Enter.
The model name must be in the Model Board of the System Identification Tool GUI or a variable in the
MATLAB workspace. This model need not be a state-space or polynomial model; it could also be a
process model (idproc) or a transfer function model (idtf).
Tip As a shortcut for specifying a model in the Model Board, you can drag the model icon from the
System Identification Tool GUI into the Initial model field.
When you enter the model name, algorithm settings in the Polynomial and State Space Models dialog
box override the initial model settings. 5Modify the iteration options, displayed in the Polynomial and
State Space Models and Transfer Functions dialog box, if necessary.
6Click Estimate to refine the model.
7Validate the new model.
Tip To continue refining the model using additional iterations, click Continue iter. This action
continues parameter estimation using the most recent model.
For more information about estimating polynomial models, see Identifying Input-Output Polynomial
Models on page 3-45.
refine_sysprovides a closer fit to the data than sys. You can similarly use polyestor armaxto refine the
estimated model.
A parametric noise model is a time-series model with the following mathematical description:
yt() = H q et( ) () Ee2 =
The noise spectrum is computed by the following discrete-time equation:
v() () 2
where is the variance of the white noise e(t),and Trepresents the spectral density of e(t). Resampling
the noise model preserves the spectral density T . The spectral density T is invariant up to the Nyquist
frequency. For more information about spectrum normalization, see Spectrum Normalization on page
3-14.
d2d resampling of the noise model affects simulations with noise using sim. If you resample a model to
a faster sampling rate, simulating this model results in higher noise level. This higher noise level results
from the underlying continuous-time model being subject to continuous-time white noise disturbances,
which have infinite, instantaneous variance. In this case, the underlying continuous-time
modelistheuniquerepresentationfor discrete-timemodels.
Tomaintainthesamelevelofnoiseafterinterpolating
the noise signal, scale the noise spectrum byTNewT ,where T
Old
new
is the new
sampling interval and Toldis the original sampling interval. before applying sim.
You want an exact discretization in the time domain for piecewise linear inputs.
You want an exact discretization in thetimedomainforimpulsetrain inputs.
Discretization Method
Tustin Approximation on page 3-148
Zero-Pole Matching Equivalents on page 3-151
Use when:
You want good matching in the frequency domain between the continuous- and discrete-time models.
Your model has important dynamics at some particular frequency.
You have a SISO model, and you want good matching in the frequency domain between the continuousand discrete-time models.
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 following block diagram illustrates the zero-order-hold discretization Hd(z) of a continuous-time
linear model H(s)
ut uk [],1()T
() = ss
The signal u(t) is the input to the continuous system H(s). The output y[k] results from sampling
y(t)every Tsseconds.
Conversely, given a discrete system Hd(z), d2cproduces a continuous system H(s). The ZOH
discretization of H(s) coincides with Hd(z).
The ZOH discrete-to-continuous conversion has the following limitations:
d2ccannot convert LTI models with poles at z=0.
For discrete-time LTI models having negative real poles, ZOH d2c conversion produces a continuous
system with higher order. The model order increases because a negative real pole in the z domain maps
to apureimaginaryvalueinthe s domain. Such mapping results in a continuous-time model with complex
data. To avoid this, the software instead introduces a conjugate pair of complex poles in the s domain.
H(s)
e-ts
For such systems, c2dperforms the following actions to compute an approximate ZOH discretization:
kT
1 Decomposes the delay as with 0< Ts.s
2Absorbs the fractional delay into H(s).
Discretizes H(s)to H(z).
k
4 Represents the integer portion of the delay kTsas an internal discrete-time delay z . The final
discretized model appears in the following figure:
3
H(z)
e-srH(s)
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.
FOH differs from ZOH by the underlying hold mechanism. To turn the input samplesu[k] into a
continuous input u(t), FOH uses linear interpolation between samples:
()
=
[]
+
ut uk tkTs()11()T
T
s ss
This method is generally 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.
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)
Tustin Approximation
The Tustin or bilinear approximation yields the best frequency-domain match between the continuoustime and discretized systems. This method relates the s-domain and z-domain transfer functions using
the approximation:
zesTs|12s / .12s /
In c2dconversions, the discretization Hd(z) of a continuous transfer function H(s)is:
d
()
=
Hz Hs
()
,
s
=
21 Ts z+1
Similarly, the d2cconversion relies on the inverse correspondence
>@
T Bu kT T
AT xkT s ss s . 22 2
Tsis the sampling time of the discrete-time model. A and B are state-space matrices of the continuoustime model.
Tustin Approximation with Frequency Prewarping 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 continuousand discrete-time responses
at the prewarp frequency.
The Tustin approximation with frequency prewarping uses the following transformation of variables:
d
()
=
Hz Hs
()
,
s
=
Z z1
() z+1
This change of variable ensures the matching of the continuous- and discrete-time frequency responses
at the prewarp frequency ,becauseof the following correspondence:
Hj H e
()
()
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 sampling time.
Therefore, for any time delay tau,theintegerportion of the delay, k*Ts,mapstoadelayof ksampling 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 FractDelayApproxOrderoption of c2dOptions.
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,outputdelay o, and internal delay .
G(s)
e
tis etos H(s)
ets
The following figure shows the general result of discretizing G(s)usingthe Tustin method.
Gd(z)
z-mi Fi(z)Hd(z) Fo(z) z-mo
z-m F(z)
By default, c2dconverts the time delays to pure integer time delays. The c2dcommand 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.
If you set FractDelayApproxOrderto a non-zero value, c2dapproximates the fractional portion of the
time delays by Thiran filters Fi(z), Fo(z), and F(z).
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:
order(Fi(z)) = max(ceil( i/Ts), FractDelayApproxOrder).
If ceil( i/Ts)< FractDelayApproxOrder,theThiranfilter Fi(z)approximates the entire input delay i.Ifceil(
i/Ts)> FractDelayApproxOrder,theThiran 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 zm,i where
mi=ceil( i/Ts) FractDelayApproxOrder.
c2duses Thiran filters and FractDelayApproxOrderin a similar way to approximate the output delay oand
the internal delay .
When you discretize tfand zpkmodels using the Tustin method, c2dfirst aggregates all input, output, and
transfer delays into a single transfer delay TOTfor each channel. c2dthen approximates TOTas a Thiran
filter and a
chain of unit delays in the same way as described for each of the time delays in ssmodels.
For more information about Thiran filters, see the thiranreference page and [4].
ze
sT is
=
where:
ziis the ith pole or zero of the discrete-time system.
siis the ith pole or zero of the continuous-time system.
Tsis the sampling time.
References
[1] strm, K.J. and B. Wittenmark, Computer-Controlled Systems: Theory and Design,PrenticeHall,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 | d2c | c2dOptions | d2cOptions | d2d | thiran
Discrete-time frequency domain data (IDDATAwith domain = frequency or IDFRDwith sample time
Ts?0) is treated as continuous-time data by setting the sample time Ts to zero.
The resulting continuous-time frequency domain data is used for model estimation. For more
information, see Pintelon, R. and J. Schoukens, System Identification. A Frequency Domain
Approach,section10.2, pp-352-356,Wiley-IEEE Press, New York, 2001.
Similarly, the intersample behavior of the input data affects the results of simulation and prediction of
continuous-time models. simand predict commands use the InterSampleproperty to choose the right
algorithm for computing model response. Say more or give some pointers about which algorithms are
used?
The following example simulates a system using first-order hold (foh) intersample behavior for input
signal.
sys=idtf([-1 -2],[1 2 1 0.5]);
rng('default')
u = idinput([100 1 5],'sine',[],[],[5 10 1]); Ts = 2;
y = lsim(sys, u, (0:Ts:999)', 'foh');
Create an iddataobject for the simulated input-output data:
data = iddata(y,u,Ts);
The default intersample behavior is zero-order hold (zoh):
data.InterSample
ans =
zoh
Estimate a transfer function using this data:
np = 3; % number of poles
nz = 1; % number of zeros
opt = tfestOptions('InitMethod','all','Display','on'); opt.SearchOption.MaxIter = 100;
modelZOH = tfest(data,np,nz,opt);
The model gives about 80% fit to data. The sample time of the data is large enough that intersample
inaccuracy (using zohrather than foh)leadsto significant modeling errors.
Re-estimate the model using fohintersample behavior:
data.InterSample = 'foh';
modelFOH = tfest(data, np, nz,opt); modelFOHis able to retrieve the original system correctly: Compare
the model outputs with data.
compare(data, modelZOH, modelFOH)
modelZOHis compared to data whose intersample behavior is foh.There,its fit decreases to around 70%.
m_f = idfrd(m,f)
To get frequency response for a submodel from input 2to output 3,usethe following command:
m_f = idfrd(m(2,3))
To get an ARMAX model from state-space model m_ss,usethefollowingcommand:
m_p = idpoly(m_ss)
Commands for Transforming Model Representations (Continued)
Command Model Type to Convert Usage Example
this command converts any numeric LTI model, except frd.
idss Converts any linear identified model, except idfrd,to state-space representation. If you have the
Control System Toolbox product, this command converts any numeric LTI model, except frd.
idtf Converts any linear identified model, except idfrd, to transfer function representation. The noise
component of the original model is lost since an idtf objecthasnoelementsto model noise dynamics. If
you have the Control System Toolbox product, this command converts any numeric LTI model, except
frd.
To get a state-space model from an ARX model m_arx,usethefollowingcommand:
m_ss = idss(m_arx)
To get a transfer function from a state-space model m_ss,usethefollowing command:
m_tf = idtf(m_ss)
Note Most transformations among identified models (among idss, idtf, idpoly) causes the parameter
covariance information to be lost, with few exceptions:
Conversion of an idtfmodel to an idpolymodel.
Conversion of an idgreymodel to an idssmodel.
If you want to translate the estimated parameter covariance during conversion, use translatecov.
Subreferencing Models
In this section...
What Is Subreferencing? on page 3-159
Limitation on Supported Models on page 3-159
Subreferencing Specific Measured Channels on page 3-160 Separation of Measured and Noise
Components of Models on page 3-161 Treating Noise Channels as Measured Inputs on page 3-162
What Is Subreferencing?
You can use subreferencing to create models with subsets of inputs and outputs from existing
multivariable models. Subreferencing is also useful when you want to generate model plots for only
certain channels, such as when you are exploring multiple-output models for input channels that have
minimal effect on the output.
The toolbox supports subreferencing operations for idtf, idpoly, idproc, idss,and idfrdmodel objects.
Subreferencing is not supported for idgreymodels. If you want to analyze the sub-model, convert it into
an idssmodel first, and then subreference the I/Os of the idssmodel. If you want a grey-box
representation of a subset of I/Os, create a new idgreymodel that uses an ODE function returning the
desired I/O dynamics.
In addition to subreferencing the model for specific combinations of measured inputs and output, you
can subreference dynamic and noise models individually.
H is an operator that describes the properties of the additive output disturbance and takes the
hypothetical (unmeasured) noise source inputs to the outputs. H represents the noise model. When you
specify to estimate a noise model, the resulting model include one noise channel e at the input for each
output in your system.
Thus, linear, parametric models represent input-output relationships for two kinds of input channels:
measured inputs and (unmeasured) noise inputs. For example, consider the ARX model given by one of
the following equations:
Aq yt Bqu t nk et() + ()
=
or Bq() 1
yt() =
Aqut() + Aq et() ()
In this case, the dynamic model is the relationship between the measured
input u and output y, G Bq Aq () (). The noise model is the contribution of the input noise e to the output
y,givenby H = 1 ().
Suppose that the model mcontains both a dynamic model G and a noise model H. To create a new model
that only has G and no noise contribution, simply set its NoiseVarianceproperty value to zero value.
To create a new model by subreferencing H due to unmeasured inputs, use the following syntax:
m_H = m(:,[])
This operation creates a time-series model from mby ignoring the measured input.
The covariance matrix of e is given by the model property NoiseVariance, which is the matrix :
= LLT
The covariance matrix of e is related to v,asfollows:
= eLv
where v is white noise with an identity covariance matrix representing independent noise sources with
unit variances.
the noise contributions. To include this variance information, normalize e such that v becomes white
noise with an identity covariance matrix, where
=eLv
To normalize e, use the following command:
m_GH = noisecnv(m,'Norm')
This command creates a model where u and v are treated as measured signals, as follows:
yt() Gut HLv G HL[]?u?=+ = ?v?
??
For example, the scaling by L causes the step responses from v to y to reflect
thesizeofthedisturbanceinfluence.
The converted noise sources are named in a way that relates the noise channel to the corresponding
output. Unnormalized noise sources e are assigned names such as 'e@y1', 'e@y2',..., 'e@yn',where
'e@yn'refers to the noise input associated with the output yn. Similarly, normalized noise sources v, are
named 'v@y1', 'v@y2', ..., 'v@yn'.
If you want to create a model that has only the noise channels of an identified model as its measured
inputs, use the noise2meascommand. It results in a model with y(t)= He or y(t)= HLv,where e or v is
treated as a measured input.
Note When you plot models in the GUI that include noise sources, you can select to view the response
of the noise model corresponding to specific outputs. For more information, see Selecting Measured
and Noise Channels in Plots on page 12-16.
Concatenating Models
In this section...
About Concatenating Models on page 3-164
Limitation on Supported Models on page 3-165
Horizontal Concatenation of Model Objects on page 3-165 Vertical Concatenation of Model Objects
on page 3-165 Concatenating Noise Spectrum Data of idfrd Objects on page 3-166 See Also on
page 3-167
You can also concatenate nonparametric models, which contain the estimated impulse-response
(idtfobject) and frequency-response (idfrdobject)ofa system.
In case of idfrdmodels, concatenation combines information in the ResponseDataproperties of the
individual model objects. ResponseDatais an ny-bynu-bynfarray that stores the response of the system,
where ny is the number of output channels, nuis the number of input channels, and nfis the number of
frequency values. The (j,i,:)vector of the resulting response data represents the frequency response from
the ith input to the jth output at all frequencies.
Combinedu1 Horizonal Concatenationy1 Same Inputsu2 of Model 1 and Model 2y2 Outputsu3
y3
Same
u1
Vertical Concatenationy1 of Model 1 and Model 2 y2
Inputsu2 y3 Combined Outputs
??
0mN s?
? ? sin m.sis the abbreviation for the SpectrumDataproperty name.
See Also
If you have the Control System Toolbox product, see Combining Model Objects on page 10-5 about
additional functionality for combining models.
Merging Models
You can merge models of the same structure to obtain a single model with parameters that are
statistically weighed means of the parameters of the individual models. When computing the merged
model, the covariance matrices of the individual models determine the weights of the parameters.
You can perform the merge operation for the idtf, idgrey, idpoly, idproc, and idssmodel objects.
Note Each merge operation merges the same type of model object.
Merging models is an alternative to merging data sets into a single multiexperiment data set, and then
estimating a model for the merged data. Whereas merging data sets assumes that the signal-to-noise
ratios are about the same in the two experiments, merging models allows greater variations in model
uncertainty, which might result from greater disturbances in an experiment.
When the experimental conditions are about the same, merge the data instead of models. This approach
is more efficient and typically involves better-conditioned calculations. For more information about
merging data sets into a multiexperiment data set, see Creating Multiexperiment Data at the Command
Line on page 2-61.
For more information about merging models, see the mergereference page.
This example illustrates how to build simple process models often used in process industry. Simple, loworder continuous-time transfer functions are usually employed to describe process behavior. Such
models are described by IDPROC objects which represent the transfer function in a pole-zero-gain form.
Process models are of the basic type Static Gain + Time Constant + Time Delay. They may be
represented as:
or as an integrating process:
where the user can determine the number of real poles (0, 1, 2 or 3), as well as the presence of a zero in
the numerator, the presence of an integrator term (1/s) and the presence of a time delay (Td). In addition,
an underdamped (complex) pair of poles may replace the real poles.
Representation of Process Models using IDPROC Objects
IDPROC objects define process models by using the letters P(for process model), D(for time delay),
Z(for a zero) and I(for integrator). An integer will denote the number of poles. The models are generated
by calling idprocwith astring identifier using these letters.
This should be clear from the following examples.
idproc('P1') % transfer function with only one pole (no zeros or delay) idproc('P2DIZ') % model with 2
poles, delay integrator and delay idproc('P0ID') % model with no poles, but an integrator and a delay
ans =
Process model with transfer function: Kp
G(s) = ---------
1+Tp1*s
Kp = NaN Tp1 = NaN
Parameterization:
'P1'
Number of free coefficients: 2
Use "getpvec", "getcov" for parameters and their uncertainties.
Status:
Created by direct construction or transformation. Not estimated.
ans =
Process model with transfer function: 1+Tz*s
G(s) = Kp * ------------------- * exp(-Td*s) s(1+Tp1*s)(1+Tp2*s)
Kp = NaN Tp1 = NaN Tp2 = NaN
Td = NaN Tz = NaN
Parameterization:
'P2DIZ'
Number of free coefficients: 5
Use "getpvec", "getcov" for parameters and their uncertainties. Status:
Created by direct construction or transformation. Not estimated.
ans =
Process model with transfer function: Kp
G(s) = --- * exp(-Td*s)
s
Kp = NaN Td = NaN
Parameterization:
'P0DI'
Number of free coefficients: 2
Use "getpvec", "getcov" for parameters and their uncertainties.
Status:
Created by direct construction or transformation. Not estimated.
Creating an IDPROC Object (using a Simulink Model as Example)
set_param('iddempr1/Random Number','seed','0')
The red part is the system, the blue part is the controller and the reference
signalisasweptsinusoid(achirpsignal). Thedatasamplingtimeissetto0.5 seconds. As observed, the system
is a continuous-time transfer function, and can hence be described using model objects in System
Identification Toolbox, such as idss, idpolyor idproc.
Let us describe the system using idpolyand idprocobjects. Using idpoly object, the system may be
described as:
m0 = idpoly(1,0.1,1,1,[1 0.5],'Ts',0,'InputDelay',1.57,'NoiseVariance',0.01
The IDPOLY form used above is useful for describing transfer functions of arbitrary orders. Since the
system we are considering here is quite simple (one pole and no zeros), and is continuous-time, we may
use the simpler IDPROC object to capture its dynamics:
m0p = idproc('p1d','Kp',0.2,'Tp1',2,'Td',1.57) % one pole+delay, with initi % for gain, pole and delay s
m0p =
Process model with transfer function: Kp
G(s) = ---------- * exp(-Td*s) 1+Tp1*s
Kp = 0.2 Tp1 = 2
Td = 1.57
Parameterization:
'P1D'
Number of free coefficients: 3
Use "getpvec", "getcov" for parameters and their uncertainties.
Status:
Created by direct construction or transformation. Not estimated.
Estimating Parameters of IDPROC Models
Once a system is described by a model object, such as IDPROC, it may be used for estimation of its
parameters using measurement data. As an example, we consider the problem of estimation of
parameters of the Simulink models system (red portion) using simulation data. We begin by acquiring
data for estimation:
sim('iddempr1')
dat1e = iddata(y,u,0.5); % The IDDATA object for storing measurement data
Letuslookatthedata:
plot(dat1e)
We can identify a process model using procestcommand, by providing the same structure information
specified to create IDPROC models. For example, the 1-pole+delay model may be estimated by calling
procestas follows:
m1 = procest(dat1e,'p1d'); % estimation of idproc model using data 'dat1e'.
% Check the result of estimation: m1
m1 =
Process model with transfer function: Kp
G(s) = ---------- * exp(-Td*s) 1+Tp1*s
Kp = 0.20045 Tp1 = 2.0431
Td = 1.499
Parameterization:
'P1D'
Number of free coefficients: 3
Use "getpvec", "getcov" for parameters and their uncertainties.
Status:
Estimated using PROCEST on time domain data "dat1e". Fit to estimation data: 87.34% (prediction
focus) FPE: 0.01068, MSE: 0.01063
To get information about uncertainties, use
present(m1)
m1 =
Process model with transfer function: Kp
G(s) = ---------- * exp(-Td*s) 1+Tp1*s
Kp = 0.20045 +/- 0.00077275 Tp1 = 2.0431 +/- 0.061216
Td = 1.499 +/- 0.040854 Parameterization:
'P1D'
Number of free coefficients: 3
Use "getpvec", "getcov" for parameters and their uncertainties.
Status:
Termination condition: Near (local) minimum, (norm(g) < tol). Number of iterations: 4, Number of
function evaluations: 9
Estimated using PROCEST on time domain data "dat1e". Fit to estimation data: 87.34% (prediction
focus) FPE: 0.01068, MSE: 0.01063
More information in model's "Report" property.
The model parameters, K, Tp1and Tdare now shown with one standard deviation uncertainty range.
Computing Time and Frequency Response of IDPROC Models
The model m1estimated above is an IDPROC model object to which all of the toolboxs model
commands can be applied:
step(m1,m0) %step response of models m1 (estimated) and m0 (actual) legend('m1 (estimated
parameters)','m0 (known parameters)','location','nort
Bode response with confidence region corresponding to 5 s.d. may be computed by doing:
h = bodeplot(m1,m0); showConfidence(h,3)
Similarly, the measurement data may be compared to the models outputs using compareas follows:
compare(dat1e,m0,m1)
Other operations such as sim, impulse, c2darealsoavailable,justasthey are for other model objects.
bdclose('iddempr1')
Accommodating the Effect of Intersample Behavior in Estimation
It may be important (at least for slow sampling) to consider the intersample behavior of the input data.
To illustrate this, let us study the same system as before, but without the sample-and-hold circuit:
open_system('iddempr5')
Simulate this system with the same sampling interval:
sim('iddempr5')
dat1f = iddata(y,u,0.5); % The IDDATA object for the simulated data
We estimate an IDPROC model using data1fwhilealsoimposinganupper bound on the allowable value
delay. We will use lm as search method and also choose to view the estimation progress.
m2_init = idproc('P1D');
m2_init.Structure.Td.Maximum = 2;
opt = procestOptions('SearchMethod','lm','Display','on'); m2 = procest(dat1f,m2_init,opt);
m2
m2 =
Process model with transfer function: Kp
G(s) = ---------- * exp(-Td*s) 1+Tp1*s
However, by
telling the estimation process that the intersample behavior is first-order-hold (an approximation to the
true continuous) input, we do better:
dat1f.InterSample = 'foh';
m3 = procest(dat1f,m2_init,opt);
Compare the four models m0 (true) m1 (obtained from zoh input) m2 (obtained for continuous input,
with zoh assumption) and m3 (obtained for the same input, but with foh assumption)
[m0p.Td, m1.Td, m2.Td, m3.Td]
compare(dat1e,m0,m1,m2,m3)
step(m0,m1,m2,m3)
legend('m0','m1','m2','m3')
bdclose('iddempr5')
ans =
1.5700 1.4990 1.3100 1.5570
Modeling a System
Operating in Closed Loop
Let us now consider a more complex process, with integration, that is operated in closed loop:
open_system('iddempr2')
Thetruesystemcanberepresentedby:
m0 = idproc('P2ZDI','Kp',1,'Tp1',1,'Tp2',5,'Tz',3,'Td',2.2);
The process is controlled by a PD regulator with limited input amplitude and a zero order hold device.
The sampling interval is 1 second.
set_param('iddempr2/Random Number','seed','0')
sim('iddempr2')
dat2 = iddata(y,u,1); % IDDATA object for estimation
Two different simulations are made, the first for estimation and the second one for validation purposes.
set_param('iddempr2/Random Number','seed','13')
sim('iddempr2')
dat2v = iddata(y,u,1); % IDDATA object for validation purpose
Letuslookatthedata(estimationandvalidation).
plot(dat2,dat2v)
legend('dat2 (estimation)','dat2v (validation)')
Let us now
perform estimation using dat2.
m2_init = idproc('P2ZDI');
m2_init.Structure.Td.Maximum = 5;
m2_init.Structure.Tp1.Maximum = 2;
opt = procestOptions('SearchMethod','lm','Display','full'); opt.SearchOption.MaxIter = 50;
m2 = procest(dat2, m2_init, opt)
m2 =
Process model with transfer function:
1+Tz*s
bode(m2,m0)
legend({'m2 (est)','m0 (actual)'},'location','west')
impulse(m2,m0)
legend({'m2 (est)','m0 (actual)'})
Compare also
with the parameters of the true system:
present(m2)
[getpvec(m0), getpvec(m2)]
m2 =
Process model with transfer function:
1+Tz*s
G(s) = Kp * ------------------- * exp(-Td*s)
s(1+Tp1*s)(1+Tp2*s)
Kp = -0.89555 +/- 22.268
Tp1 = 2 +/- 0.25413
Tp2 = 1388.4 +/- 16546
Td = 3.08 +/- 0.20786
Tz = -1519.1 +/- 19687
Parameterization:
'P2DIZ'
Number of free coefficients: 5
Use "getpvec", "getcov" for parameters and their uncertainties.
Status:
Termination condition: Maximum number of iterations reached. Number of iterations: 50, Number of
function evaluations: 344
Estimated using PROCEST on time domain data "dat2". Fit to estimation data: 90.21% (prediction
focus) FPE: 0.1651, MSE: 0.1457
More information in model's "Report" property.
ans =
1.0e+03 *
0.0010 -0.0009
0.0010 0.0020
0.0050 1.3884
0.0022 0.0031
0.0030 -1.5191
A word of caution. Identification of several real time constants may sometimes be an ill-conditioned
problem, especially if the data are collected in closed loop.
To illustrate this, let us estimate a model based on the validation data:
m2v = procest(dat2v, m2_init, opt) [getpvec(m0), getpvec(m2), getpvec(m2v)]
m2v =
Process model with transfer function: 1+Tz*s
G(s) = Kp * ------------------- * exp(-Td*s) s(1+Tp1*s)(1+Tp2*s)
Kp = -2.8056 Tp1=2
Tp2 = 4586.1
Td = 2.252 Tz = -1630
Parameterization:
'P2DIZ'
Number of free coefficients: 5
Use "getpvec", "getcov" for parameters and their uncertainties.
Status:
Estimated using PROCEST on time domain data "dat2v". Fit to estimation data: 89.61% (prediction
focus) FPE: 0.1897, MSE: 0.1675
ans =
1.0e+03 *
0.0010 -0.0009 -0.0028
0.0010 0.0020 0.0020
0.0050 1.3884 4.5861
0.0022 0.0031 0.0023
0.0030 -1.5191 -1.6300
This model has much worse parameter values. On the other hand, it performs nearly identically to the
true system m0 when tested on the other data set dat2:
compare(dat2,m0,m2,m2v)
Status:
Estimated using PROCEST on time domain data "dat2v". Fit to estimation data: 91.23% (prediction
focus) FPE: 0.1209, MSE: 0.1193
Thus, the simpler model is able to estimate system output pretty well. However, m1xdoes not contain
any integration, so the open loop long time range behavior will be quite different:
step(m0,m2,m2v,m1x)
legend('m0','m2','m2v','m1x')
bdclose('iddempr2')
Additional
Information
For more information on identification of dynamic systems with System Identification Toolbox visit the
System Identification Toolbox product information page.
are inside the statistically zero region (marked by the confidence bound) before the response goes
outside that region.
- Select the model order in n4sidby specifying the model order as a vector.
- Choose the model order of an ARX model using arxstrucor ivstrucand selstruc. These command select
the number of poles, zeros and delay. See Model Structure Selection: Determining Model Order and
Input Delay on page 3-196 for an example of using these tools.
Choosing a model structure is usually the first step towards its estimation. There are various possibilities
for structure - state-space, transfer functions and polynomial forms such as ARX, ARMAX, OE, BJ etc.
If you do not have detailed prior knowledge of your system, such as its noise characteristics and
indication of feedback, the choice of a reasonable structure may not be obvious. Also for a given choice
of structure, the order of the model needs to be specified before the corresponding parameters are
estimated. System Identification Toolbox offers some tools to assist in the task of model order
selection.
The choice of a model order is also influenced by the amount of delay. A good idea of the input delay
simplifies the task of figuring out the orders of other model coefficients. Discussed below are some
options for input delay determination and model structure and order selection.
Choosing and Preparing Example Data for Analysis
This example uses the hair dryer data, also used by iddemo1 ("Estimating Simple Models from Real
Laboratory Process Data"). The process consists of air being fanned through a tube. The air is heated at
the inlet of the tube, and the input is the voltage applied to the heater. The output is the temperature at
the outlet of the tube.
Let us begin by loading the measurement data and doing some basic preprocessing:
loaddry2
Form a data set for estimation of the first half, and a reference set for validation purposes of the second
half:
ze = dry2(1:500); zr = dry2(501:1000);
Detrend each of the sets:
ze = detrend(ze); zr = detrend(zr);
Letuslookataportionoftheestimationdata:
plot(ze(200:350))
Estimating Input
Delay
There are various options available for determining the time delay from input to output. These are:
Using the DELAYESTutility.
Using a non-parametric estimate of the impulse response, using IMPULSEEST.
Using the state-space model estimator N4SIDwith a number of different orders and finding the delay of
the best one.
Using delayest:
Let us discuss the above options in detail. Function delayestreturns an estimate of the delay for a given
choice of orders of numerator and denominator polynomials. This function evaluates an ARX structure:
y(t) + a1*y(t-1) + ... + ana*y(t-na) = b1*u(t-nk) + ...+bnb*u(t-nb-nk+1)
with various delays and chooses the delay value that seems to return the best fit. In this process, chosen
values of naand nbare used.
delay = delayest(ze) % na = nb = 2 is used, by default
delay =
3
A value of 3 is returned by default. But this value may change a bit if the assumed orders of numerator
and denominator polynomials (2 here) is changed. For example:
delay = delayest(ze,5,4)
delay =
2
returns a value of 2. To gain insight into how delayestworks, let us evaluate the loss function for various
choices of delays explicitly. We select a second order model (na=nb=2), which is the default for
delayest, and try out every time delay between 1 and 10. The loss function for the different models are
computed using the validation data set:
V = arxstruc(ze,zr,struc(2,2,1:10));
We now select that delay that gives the best fit for the validation data:
[nn,Vm] = selstruc(V,0); % nn is given as [na nb nk]
The chosen structure was:
nn
nn =
223
which show the best model has a delay of nn(3) = 3.
We can also check how the fit depends on the delay. This information is returned in the second output
Vm. The logarithms of a quadratic loss function are given as the first row, while the indexes na, nband
nkare given as a column below the corresponding loss function.
Vm
Vm =
Columns 1 through 7
-0.1283 -1.3142 -1.8787 -0.2339 0.0084 0.0900 0.1957 2.0000 2.0000 2.0000 2.0000 2.0000 2.0000
2.0000 2.0000 2.0000 2.0000 2.0000 2.0000 2.0000 2.0000 1.0000 2.0000 3.0000 4.0000 5.0000 6.0000
7.0000
Columns 8 through 10
0.2082 0.1728 0.1631
2.0000 2.0000 2.0000
2.0000 2.0000 2.0000
8.0000 9.0000 10.0000
The choice of 3 delays is thus rather clear, since the corresponding loss is minimum.
Using impulse
To gain a better insight into the dynamics, let us compute the impulse response of the system. We will
use the function impulseestto compute a non-parametric impulse response model. We plot this response
with a confidence interval represented by 3 standard deviations.
FIRModel = impulseest(ze); clf
h = impulseplot(FIRModel); showConfidence(h,3)
The filled light-blue region shows the confidence interval for the insignificant response in this
estimation. There is a clear indication that the impulse response "takes off" (leaves the uncertainty
region) after 3 samples. This points to a delay of three intervals.
Using n4sid based state-space evaluation
We may also estimate a family of parametric models to find the delay corresponding to the "best" model.
In case of state-space models, a range of orders may be evaluated simultaneously and user gets
prompted to choose the best order. Execute the following command to invoke n4sidin an interactive
mode:
m = n4sid(ze,1:15); % All orders between 1 and 15. The plot indicates an order of 4 as the best value.
For this choice, let us computetheimpulseresponseofthemodel m:
m = n4sid(ze,4);
showConfidence(impulseplot(m),3)
As with non-parametric impulse response, there is a clear indication that the delay from input to output
is of three samples.
Choosing a Reasonable Model Structure
In lack of any prior knowledge, it is advisable to try out various available choices and use the one that
seems to work the best. State-space models may be a good starting point since only the number of states
needs to be specified in order to estimate a model. Also, a range of orders may be evaluated quickly,
using n4sid, for determining the best order, as described in the next section. For polynomial models, a
similar advantage is realized using the arx estimator. Output-error (OE) models may also be good choice
for a starting polynomial model because of their simplicity.
Determining Model Order
Once you have decided upon a model structure to use, the next task is to determine the order(s). In
general, the aim should be to not use a model order higher than necessary. This can be determined by
analyzing the improvement in %fit as a function of model order. When doing this, it is advisable to use a
separate, independent dataset for validation. Choosing an independent validation data set (zrin our
example) would improve the detection of over-fitting.
In addition to a progressive analysis of multiple model orders, explicit determination of optimum orders
can be performed for some model structures. Functions arxstrucand selstrucmay be used for choosing
the best order for ARX models. For our example, let us check the fit for all 100 combinations of up to 10
b-parameters and up to 10 a-parameters, all with a delay value of 3:
V = arxstruc(ze,zr,struc(1:10,1:10,3));
The best fit for the validation data set is obtained for:
nn = selstruc(V,0)
nn =
1043
Let us check how much the fit is improved for the higher order models. For this, we use the function
selstrucwith only one input. In this case, a plot showing the fit as a function of the number of parameters
used is generated. Theuserisalsopromptedtoenterthenumberofparameters. The routine then selects a
structure with these many parameters that gives the best fit. Note that several different model structures
use the same number of parameters. Execute the following command to choose a model order
interactively:
nns = selstruc(V) %invoke selstruc in an interactive mode The best fit is thus obtained for nn = [4 4 3],
while we see that the improved fit compared to nn = [2 2 3] is rather marginal.
We may also approach this problem from the direction of reducing a higher order model. If the order is
higher than necessary, then the extra parameters are basically used to "model" the measurement noise.
These "extra" poles are estimated with a lower level of accuracy (large confidence interval). If their are
cancelled by a zero located nearby, then it is an indication that this pole-zero pair may not be required to
capture the essential dynamics of the system.
For our example, let us compute a 4th order model: Let us check the pole-zero configuration for this
model. We can also include confidence regions for the poles and zeros corresponding to 3 standard
deviations, in order to determine how accurately they are estimated and also how close the poles and
zeros are to each other.
h = iopzplot(th4); showConfidence(h,3)
The confidence intervals for the two complex-conjugate poles and zeros overlap, indicating they are
likely to cancel each other. Hence, a second order model might be adequate. Based on this evidence, let
us compute a 2nd order ARX model:
We can test how well this model (th2) is capable of reproducing the validation data set. To compare the
simulated output from the two models with the actual output (plotting the mid 200 data points) we use
the compareutility:
compare(zr(150:350),th2,th4)
The plot indicates that there was no significant loss of accuracy in reducing the order from 4 to 2. We
can also check the residuals ("leftovers") of this model, i.e., what is left unexplained by the model.
e = resid(ze,th2);
plot(e(:,1,[])), title('The residuals')
We see that the residuals are quite small compared to the signal level of the output, that they are
reasonably well (although not perfectly) uncorrelated with the input and among themselves. We can thus
be (provisionally) satisfied with the model th2.
Let us now check if we can determine the model order for a state-space structure. As before, we know
the delay is 3 samples. We can try all orders from 1 to 15 with a fixed delay of 3 in n4sid. Execute the
following command to try various orders and choose one interactively.
ms = n4sid(ze,[1:15],'InputDelay',2); %n4sid estimation with variable orders
The default order, indicated in the figure above, is 3, that is in good agreement with our earlier findings.
Finally, we compare how the state-space model ms and the ARX model th2compare in reproducing the
measured output of the validation data:
ms = n4sid(ze,3,'InputDelay',2);
compare(zr,ms,th2)
The comparison plot indicates that the two models are practically identical.
Conclusions
This example described some options for choosing a reasonable model order. Determining delay in
advance can simplify the task of choosing orders. With ARX and state-space structures, we have some
special tools (arxand n4sid estimators) for automatically evaluating a whole set of model orders, and
choosing the best one among them. The information revealed by this exercise (using utilities such as
arxstruc, selstruc, n4sidand delayest)couldbe used as a starting point when estimating models of other
structures, such as BJ and ARMAX.
Additional Information
Formore information on identification of dynamic systems with System Identification Toolbox visit the
System Identification Toolbox product information page.
both domains, compare and combine these models. A model estimated using time domain data may be
validated using spectral data or vice-versa.
Frequency domain data can not be used for estimation or validation of nonlinear models.
Introduction
This
experimental data will now be stored as an IDFRD object. First transform amplitude and phase to a
complex valued response:
zfr = AMP.*exp(1i*PHA*pi/180);
Ts = 0.1;
gfr = idfrd(zfr,W,Ts);
Ts is the sampling interval of the underlying data. If the data corresponds to continuous time, for
example since the input has been band-limited, use Ts =0.
Note: If you have the Control System Toolbox, you could use an FRD object instead of the IDFRD
object. IDFRD has options for more information, like disturbance spectra and uncertainty measures
which are not available in FRD objects.
The IDFRD object gfrnow contains the data, and it can be plotted and analyzed in different ways. To
view the data, we may use plotor bode:
clf
bode(gfr), legend('gfr')
Estimating Models
Using Frequency Response (FRF) Data
To estimate models, you can now use gfras a data set with all the commands of the toolbox in a
transparent fashion. The only restriction is that noise models cannot be built. This means that for
polynomial models only OE (output-error models) apply, and for state-space models, you have to fixK=
0.
m1 = oe(gfr,[2 2 1]) % Discrete-time Output error (transfer function) model ms = ssest(gfr) %
Continuous-time state-space model with default choice of mproc = procest(gfr,'P2UDZ') % 2nd-order,
continuous-time model with underd compare(gfr,m1,ms,mproc)
m1 =
Discrete-time OE model: y(t) = [B(z)/F(z)]u(t) + e(t) B(z) = 0.9982 z^-1 + 0.4974 z^-2
F(z) = 1 - 1.499 z^-1 + 0.6998 z^-2
Sample time: 0.1 seconds
Parameterization:
Polynomial orders: nb=2 nf=2 nk=1
Number of free coefficients: 4
Use "polydata", "getpvec", "getcov" for parameters and their uncertainti
Status:
Estimated using OE on frequency response data "gfr". Fit to estimation data: 88.04% (prediction focus)
FPE: 0.2501, MSE: 0.2494
ms =
Continuous-time identified state-space model: dx/dt = A x(t) + B u(t) + K e(t) y(t) = C x(t) + D u(t) +
e(t)
A= x1 x2
x1 -0.9005 6.636
x2 -3.308 -2.669
B= u1
x1 -32.9
x2 -28.33
C= x1 x2
y1 -0.5073 0.499
D= u1
y1 0
K= y1
x1 0
x2 0
Parameterization:
FREE form (all coefficients in A, B, C free).
Feedthrough: none
Disturbance component: none
Number of free coefficients: 8
Use "idssdata", "getpvec", "getcov" for parameters and their uncertainti
Status:
Estimated using SSEST on frequency response data "gfr". Fit to estimation data: 73.16% (prediction
focus) FPE: 0.2511, MSE: 1.255
mproc =
Process model with transfer function:
1+Tz*s
G(s) = Kp * ---------------------- * exp(-Td*s) 1+2*Zeta*Tw*s+(Tw*s)^2
Kp = 7.4612 Tw = 0.20246
Zeta = 0.36238 Td = 0
Tz = 0.013617
Parameterization:
'P2DUZ'
Number of free coefficients: 5
Use "getpvec", "getcov" for parameters and their uncertainties. Status:
Estimated using PROCEST on frequency response data "gfr". Fit to estimation data: 73.2% (prediction
focus) FPE: 0.2504, MSE: 1.251
As shown above a variety of linear model types may be estimated in both continuous and discrete time
domains, using spectral data. These models may be validated using, time-domain data. The time-domain
I/O data set ztime, for example, is collected from the same system, and can be used for validation of m1,
msand mproc:
We may also look at the residuals to affirm the quality of the model using the validation data ztime. As
observed, the residuals are almost white:
resid(mproc,ztime) % Residuals plot
Condensing Data
Using SPAFDR
An important reason to work with frequency response data is that it is easy to condense the information
with little loss. The command SPAFDR allows you to compute smoothed response data over limited
frequencies, for example with logarithmic spacing. Here is an example where the gfrdata is condensed to
100 logarithmically spaced frequency values. With a similar technique, also
theoriginaltimedomaindatacanbecondensed:
sgfr = spafdr(gfr) % spectral estimation with frequency-dependent resolutio sz = spafdr(ztime); %
spectral estimation using time-domain data clf
bode(gfr,sgfr,sz)
axis([pi/100 10*pi, -272 105])
legend('gfr (raw data)','sgfr','sz','location','southwest')
sgfr =
IDFRD model.
Contains Frequency Response Data for 1 output(s) and 1 input(s), and the sp Response data and
disturbance spectra are available at 200 frequency points
Sample time: 0.1 seconds
Output channels: 'y1'
Input channels: 'u1'
Status:
Estimated using SPAFDR on frequency response data "gfr".
The Bode plots show that the information in the smoothed data has been taken well care of. Now, these
data records with 100 points can very well be used for model estimation. For example:
msm = oe(sgfr,[2 2 1]);
compare(ztime,msm,m1) % msm has the same accuracy as M1 (based on 1000 poin
It may be that the measurements are available as Fourier transforms of inputs and output. Such
frequency domain data from the system are given as the signals Y and U. In loglog plots they look like
Wfd = (0:500)'*10*pi/500;
subplot(211),loglog(Wfd,abs(Y)),title('The amplitude of the output')
subplot(212),loglog(Wfd,abs(U)),title('The amplitude of the input')
The frequency
response data is essentially the ratio between Yand U.To collect the frequency domain data as an
IDDATA object, do as follows:
ZFD = iddata(Y,U,'ts',0.1,'Domain','Frequency','Freq',Wfd)
ZFD =
Frequency domain data set with responses at 501 frequencies, ranging from 0 to 31.416 rad/seconds
Sample time: 0.1 seconds
Outputs Unit (if specified)
y1
Inputs Unit (if specified)
u1
Now, again the frequency domain data set ZFDcan be used as data in all estimation routines, just as time
domain data and frequency response data:
mf = ssest(ZFD)
compare(ztime,mf,m1)
mf =
Continuous-time identified state-space model: dx/dt = A x(t) + B u(t) + K e(t) y(t) = C x(t) + D u(t) +
e(t)
A= x1 x2
x1 -1.501 6.791
x2 -3.115 -2.059
B= u1
x1 -28.11
x2 -33.39
C= x1 x2
y1 -0.5844 0.4129
D= u1
y1 0
K= y1
x1 0
x2 0
Parameterization:
FREE form (all coefficients in A, B, C free). Feedthrough: none
Disturbance component: none
Number of free coefficients: 8
Use "idssdata", "getpvec", "getcov" for parameters and their uncertainti
Status:
Estimated using SSEST on frequency domain data "ZFD". Fit to estimation data: 97.21% (prediction
focus) FPE: 0.04263, MSE: 0.04184
Time and frequency domain input-output data sets can be transformed to either domain by using FFT
and IFFT. These commands are adapted to IDDATA objects:
dataf = fft(ztime)
datat = ifft(dataf)
dataf =
Frequency domain data set with responses at 501 frequencies, ranging from 0 to 31.416 rad/seconds
Sample time: 0.1 seconds
Outputs Unit (if specified) y1
Inputs Unit (if specified) u1
datat =
Time domain data set with 1000 samples. Sample time: 0.1 seconds
Outputs Unit (if specified) y1
Inputs Unit (if specified) u1
Time and frequency domain input-output data can be transformed to frequency response data by
SPAFDR, SPA and ETFE:
g1 = spafdr(ztime) g2 = spafdr(ZFD); bode(g1,g2)
g1 =
IDFRD model.
Contains Frequency Response Data for 1 output(s) and 1 input(s), and the sp Response data and
disturbance spectra are available at 100 frequency points
Sample time: 0.1 seconds Output channels: 'y1'
Input channels: 'u1'
Status:
Estimated using SPAFDR on time domain data "ztime".
Frequency
response data can also be transformed to more smoothed data (less resolution and less data) by SPAFDR
and SPA;
g3 = spafdr(gfr);
Frequency response data can be transformed to frequency domain input-output signals by the command
IDDATA:
gfd = iddata(g3)
gfd =
Frequency domain data set with responses at 200 frequencies, ranging from -31.416 to 31.416 rad/
seconds
Sample time: 0.1 seconds
Outputs Unit (if specified) y1
Inputs Unit (if specified) u1
Using Continuous-time Frequency-domain Data to Estimate Continuous-time Models
Time domain data can naturally only be stored and dealt with as discrete-time, sampled data. Frequency
domain data have the advantage that continuous time data can be represented correctly. Suppose that the
underlying continuous time signals have no frequency information above the Nyquist frequency, e.g.
because they are sampled fast, or the input has no frequency component above the Nyquist frequency.
Then the Discrete Fourier transforms (DFT) of the data also are the Fourier transforms of the continuous
time signals, at the chosen frequencies. They can therefore be used to directly fit continuous time
models. In fact, this is the correct way of using band-limited data for model fit.
This will be illustrated by the following example.
Consider the continuous time system:
m0 = idpoly(1,1,1,1,[1 1 1],'ts',0)
m0 =
Continuous-time OE model: y(t) = [B(s)/F(s)]u(t) + e(t) B(s) = 1
F(s) =s^2 +s +1
Parameterization:
Polynomial orders: nb=1 nf=2 nk=0
Number of free coefficients: 3
Use "polydata", "getpvec", "getcov" for parameters and their uncertainti
Status:
Created by direct construction or transformation. Not estimated.
Choose an input with low frequency contents that is fast sampled:
rng(235,'twister');
u = idinput(500,'sine',[0 0.2]); u = iddata([],u,0.1,'intersamp','bl');
0.1 is the sampling interval, and 'bl'indicates that the input is band-limited, i.e. in continuous time it
consists of sinusoids with frequencies below half the sampling frequency. Correct simulation of such a
system should be done in the frequency domain:
uf = fft(u);
uf.ts = 0; % Denoting that the data is continuous time
yf = sim(m0,uf);
%
% Add some noise to the data:
yf.y = yf.y + 0.05*(randn(size(yf.y))+1i*randn(size(yf.y))); dataf = [yf uf] % This is now a continuous
time frequency domain data set.
dataf =
Frequency domain data set with responses at 251 frequencies, ranging from 0 to 31.416 rad/seconds
Sample time: 0 seconds
Outputs Unit (if specified) y1
Inputs Unit (if specified) u1
Look at the data:
plot(dataf)
axis([0 10 0 2.5])
Using dataffor
estimation will by default give continuous time models: State-space:
m4 = ssest(dataf,2); %Second order continuous-time model
For a polynomial model with nb = 2numerator coefficient and nf = 2 estimated denominator coefficients
use:
nb = 2;
nf = 2;
m5 = oe(dataf,[nb nf])
m5 =
Continuous-time OE model: y(t) = [B(s)/F(s)]u(t) + e(t) B(s) = -0.01761 s + 1
F(s) = s^2 + 0.9873 s + 0.9902
Parameterization:
Polynomial orders: nb=2 nf=2 nk=0
Number of free coefficients: 4
Use "polydata", "getpvec", "getcov" for parameters and their uncertainti
Status:
Estimated using OE on frequency domain data "dataf". Fit to estimation data: 70.15% (prediction focus)
FPE: 0.00482, MSE: 0.004723
Compare step responses with uncertainty of the true system m0and the models m4and m5:
clf
h = stepplot(m0,m4,m5);
showConfidence(h,1)
% *Blue: m0, Green: m4, Red: m5.*
% The confidence intervals are shown with patches.
Although it was not necessary in this case, it is generally advised to focus the fit to a limited frequency
band (low pass filter the data) when estimating using continuous time data. The system has a bandwidth
of about 3 rad/s, and was excited by sinusoids up to 6.2 rad/s. A reasonable frequency range
tofocusthefittoisthen[07]rad/s:
m6 = ssest(dataf,2,ssestOptions('Focus',[0 7])) % state space model
m6 =
Continuous-time identified state-space model:
dx/dt = A x(t) + B u(t) + K e(t)
y(t) = C x(t) + D u(t) + e(t)
A=
x1 x2
x1 -0.2714 -1.809
x2 0.4407 -0.7282
B= u1
x1 0.5873
x2 -0.3025
C= x1 x2
y1 0.7565 1.526
D= u1
y1 0
K= y1
x1 0
x2 0
Parameterization:
FREE form (all coefficients in A, B, C free).
Feedthrough: none
Disturbance component: none
Number of free coefficients: 8
Use "idssdata", "getpvec", "getcov" for parameters and their uncertainti
Status:
Estimated using SSEST on frequency domain data "dataf". Fit to estimation data: 87.08% (filter focus)
FPE: 0.004213, MSE: 0.003716
m7 = oe(dataf,[1 2],oeOptions('Focus',[0 7])) % polynomial model of Output
m7 =
Continuous-time OE model: y(t) = [B(s)/F(s)]u(t) + e(t) B(s) = 0.9866
F(s) = s^2 + 0.9791 s + 0.9761
Parameterization:
Polynomial orders: nb=1 nf=2 nk=0
Number of free coefficients: 3
Use "polydata", "getpvec", "getcov" for parameters and their uncertainti
Status:
Estimated using OE on frequency domain data "dataf". Fit to estimation data: 87.04% (filter focus) FPE:
0.004008, MSE: 0.003742
opt = procestOptions('SearchMethod','lsqnonlin','Focus',[0 7]); % Requires m8 =
procest(dataf,'P2UZ',opt) % process model with underdamped poles
m8 =
Process model with transfer function: 1+Tz*s
G(s) = Kp * ---------------------1+2*Zeta*Tw*s+(Tw*s)^2
Kp = 1.0124
Tw = 1.0019
Zeta = 0.5021
Tz = -0.017474
Parameterization:
'P2UZ'
Number of free coefficients: 4
Use "getpvec", "getcov" for parameters and their uncertainties.
Status:
Estimated using PROCEST on frequency domain data "dataf". Fit to estimation data: 87.08% (filter
focus)
FPE: 0.003947, MSE: 0.003716
opt = tfestOptions('SearchMethod','lsqnonlin','Focus',[0 7]); % Requires Op m9 = tfest(dataf,2,opt) %
transfer function with 2 poles
m9 =
From input "u1" to output "y1":
-0.01647 s + 1.003
---------------------s^2 + 0.9948 s + 0.9922
Continuous-time identified transfer function.
Parameterization:
Number of poles: 2 Number of zeros: 1
Number of free coefficients: 4
Use "tfdata", "getpvec", "getcov" for parameters and their uncertainties
Status:
Estimated using TFEST on frequency domain data "dataf". Fit to estimation data: 87.08% (filter focus)
FPE: 0.004067, MSE: 0.003717
h = stepplot(m0,m6,m7,m8,m9); showConfidence(h,1)
legend('show')
Conclusions
We saw how time, frequency and spectral data can seamlessly be used to estimate a variety of linear
models in both continuous and discrete time domains. The models may be validated and compared in
domains different from the ones they were estimated in. The data formats (time, frequency and
spectrum) are interconvertible, using methods such as fft, ifft, spafdr and spa. Furthermore, direct,
continuous-time estimation is achievable by using tfest, ssestand procestestimation routines. The
seamless use of data in any domain for estimation and analysis is an important feature of System
Identification Toolbox.
Additional Information
For more information on identification of dynamic systems with System Identification Toolbox visit the
System Identification Toolbox product information page.
We shall investigate data produced by a (simulated) dc-motor. We first load the data:
load dcmdata
who
Figure:
Measurement Data: Voltage to Angle
Figure:
Measurement Data: Voltage to Angle
Model Structure Selection
d/dt x= Ax +B u+ K e
y = Cx +D u +e
We shall build a model of the dc-motor. The dynamics of the motor is well known. If we choose x1 as
the angular position and x2 as the angular velocity it is easy to set up a state-space model of the
following character neglecting disturbances: (see Example 4.1 in Ljung(1999):
|0 1 | | 0 |
d/dt x = | | x + | | u
| 0 -th1 | | th2 |
|1 0 |
y= | |x |0 1|
The parameter th1is here the inverse time-constant of the motor and th2 is such that th2/th1is the static
gain from input to the angular velocity. (See Ljung(1987) for how th1and th2relate to the physical
parameters of the motor). We shall estimate these two parameters from the observed data. The model
structure (parameterized state space) described above can be represented in MATLAB using IDSS and
IDGREY models. These models let you perform estimation of parameters using experimental data.
Specification of a Nominal (Initial) Model
If we guess that th1=1 and th2 = 0.28 we obtain the nominal or initial model
A = [0 1; 0 -1]; %initial guess for A(2,2) is -1 B = [0; 0.28]; %initial guess for B(2) is 0.28 C = eye(2);
D = zeros(2,1);
and we package this into an IDSS model object:
ms = idss(A,B,C,D);
The model is characterized by its matrices, their values, which elements are free (to be estimated) and
upper and lower limits of those:
ms.Structure.a
ans =
Name: 'a'
Value: [2x2 double] Minimum: [2x2 double] Maximum: [2x2 double]
Free: [2x2 logical] Scale: [2x2 double]
Info: [2x2 struct] 1x1 param.Continuous
ms.Structure.a.Value ms.Structure.a.Free
ans =
01 0-1
ans =
11 11
Specification of Free (Independent) Parameters Using IDSS Models
So we should now mark that it is only A(2,2) and B(2,1) that are free parameters to be estimated.
ms.Structure.a.Free = [0 0; 0 1];
ms.Structure.b.Free = [0; 1];
ms.Structure.c.Free = 0; % scalar expansion used ms.Structure.d.Free = 0;
set(ms,'Ts',0); % This defines the model to be continuous
The Initial Model
ms % Initial model
ms =
Continuous-time identified state-space model: dx/dt = A x(t) + B u(t) + K e(t) y(t) = C x(t) + D u(t) +
e(t)
A= x1 x2
x101
x2 0 -1
B= u1
x1 0
x2 0.28
C= x1 x2
y110
y201
D= u1
y1 0
y2 0
K= y1 y2
x100
x200
Parameterization:
STRUCTURED form (some fixed coefficients in A, B, C).
Feedthrough: none
Disturbance component: none
Number of free coefficients: 2
Use "idssdata", "getpvec", "getcov" for parameters and their uncertainti
Status:
Created by direct construction or transformation. Not estimated.
Estimation of Free Parameters of the IDSS Model
The prediction error (maximum likelihood) estimate of the parameters is now computed by:
dcmodel = ssest(z,ms,ssestOptions('Display','on')); dcmodel
dcmodel =
Continuous-time identified state-space model: dx/dt = A x(t) + B u(t) + K e(t) y(t) = C x(t) + D u(t) +
e(t)
A= x1 x2
x101
x2 0 -4.013
B= Voltage x1 0 x2 1.002
C= x1 x2
Angle 1 0
AngVel 0 1
D= Voltage Angle 0 AngVel 0
K= Angle AngVel x100 x200
Parameterization:
STRUCTURED form (some fixed coefficients in A, B, C).
Feedthrough: none
Disturbance component: none
Number of free coefficients: 2
Use "idssdata", "getpvec", "getcov" for parameters and their uncertainti Status:
Estimated using SSEST on time domain data "z". Fit to estimation data: [98.35;84.42]% (prediction
focus) FPE: 0.001071, MSE: 0.05967
The estimated values of the parameters are quite close to those used when
thedataweresimulated(-4and1). Toevaluatethemodelsqualitywecan simulate the model with the actual
input by and compare it with the actual output.
compare(z,dcmodel);
We can now, for example plot zeros and poles and their uncertainty regions. We will draw the regions
corresponding to 3 standard deviations, since the model is quite accurate. Note that the pole at the origin
is absolutely certain, since it is part of the model structure; the integrator from angular velocity to
position.
clf
showConfidence(iopzplot(dcmodel),3)
Now, we may make various modifications. The 1,2-element of the A-matrix (fixed to 1) tells us that x2is
the derivative of x1. Suppose that the sensors are not calibrated, so that there may be an unknown
proportionality constant. To include the estimation of such a constant we just "let loose" A(1,2)and reestimate:
dcmodel2 = dcmodel;
dcmodel2.Structure.a.Free(1,2) = 1;
dcmodel2 = pem(z,dcmodel2,ssestOptions('Display','on'));
The resulting model is
dcmodel2
dcmodel2 =
Continuous-time identified state-space model: dx/dt = A x(t) + B u(t) + K e(t) y(t) = C x(t) + D u(t) +
e(t)
A= x1 x2
x1 0 0.9975
x2 0 -4.011
B= Voltage x1 0 x2 1.004
C= x1 x2
Angle 1 0
AngVel 0 1
D= Voltage Angle 0 AngVel 0
K= Angle AngVel x100 x200
Parameterization:
STRUCTURED form (some fixed coefficients in A, B, C).
Feedthrough: none
Disturbance component: none
Number of free coefficients: 3
Use "idssdata", "getpvec", "getcov" for parameters and their uncertainti
Status:
Estimated using SSEST on time domain data "z". Fit to estimation data: [98.35;84.42]% (prediction
focus) FPE: 0.001076, MSE: 0.05966
We find that the estimated A(1,2)iscloseto1. Tocomparethetwomodelwe use the comparecommand:
compare(z,dcmodel,dcmodel2)
Suppose that we accurately know the static gain of the dc-motor (from input voltage to angular velocity,
e.g. from a previous step-response experiment. If the static gain is G, and the time constant of the motor
is t, then the state-space model becomes
|0 1| | 0 |
d/dt x= | |x+ | |u
|0 -1/t| | G/t |
|1 0|
y=| |x |0 1|
With Gknown, there is a dependence between the entries in the different matrices. In order to describe
that, the earlier used way with "Free" parameters will not be sufficient. We thus have to write a
MATLAB file which produces the A, B, C, and D, and optionally also the K and X0 matrices as outputs,
for each given parameter vector as input. It also takes auxiliary arguments as inputs, so that the user can
change certain things in the model structure, without having to edit the file. In this case we let the known
static gain Gbe entered as such an argument. The file that has been written has thenamemotor.m.
type motor
function [A,B,C,D,K,X0] = motor(par,ts,aux)
%MOTOR ODE file representing the dynamics of a motor.
%
% [A,B,C,D,K,X0] = MOTOR(Tau,Ts,G)
% returns the State Space matrices of the DC-motor with
% time-constant Tau (Tau = par) and known static gain G. The sample % time is Ts.
%
% This file returns continuous-time representation if input argument Ts % is zero. If Ts>0, a discretetime representation is returned. To make % the IDGREY model that uses this file aware of this
flexibility, set the % value of Structure.FcnType property to 'cd'. This flexibility is useful % for
conversion between continuous and discrete domains required for % estimation and simulation.
%
% See also IDGREY, IDDEMO7.
% L. Ljung
% Copyright 1986-2011 The MathWorks, Inc.
% $Revision: 1.1.10.2 $ $Date: 2011/12/22 18:22:34 $
t = par(1);
G = aux(1); A = [0 1;0 -1/t];
B = [0;G/t];
C = eye(2);
D = [0;0];
K = zeros(2);
X0 = [0;0];
if ts>0 % Sample the model with sample time Ts
With this model we can now proceed to test various aspects as before. The syntax of all the commands is
identical to the previous case. For example, we can compare the idgrey model with the other state-space
model:
compare(z,dcmm,dcmodel)
The state-space part of the toolbox also handles multivariate (several outputs) ARX models. By a
multivariate ARX-model we mean the following:
A(q) y(t) = B(q) u(t) + e(t)
Here A(q) is a ny | ny matrix whose entries are polynomials in the delay operator 1/q. The k-l element is
denoted by:
where:
It is thus a polynomial in 1/qof degree nakl.
Similarly B(q) is a ny | nu matrix, whose kj-element is:
Parameterization:
Polynomial orders: na=[1 1;0 1] nb=[0;1] nk=[1;1]
Number of free coefficients: 4
Use "polydata", "getpvec", "getcov" for parameters and their uncertainti
Status:
Estimated using ARX on time domain data "z".
Fit to estimation data: [97.52;81.46]% (prediction focus) FPE: 0.003468, MSE: 0.08862
To compare the different models obtained we use
compare(z,dcmodel,dcmm,dcarx2)
Finally, we could compare the bodeplots obtained from the input to output one for the different models
by using bode:Firstoutput:
dcmm2 = idss(dcmm); % convert to IDSS for subreferencing Second output:
The two first models are more or less in exact agreement. The ARX-models are not so good, due to the
bias caused by the non-white equation error noise. (We had white measurement noise in the
simulations).
Conclusions
Estimation of models with pre-selected structures can be performed using System Identification toolbox.
In state-space form, parameters may be fixed to their known values or constrained to lie within a
prescribed range. If relationship between parameters or other constraints need to be specified, IDGREY
objects may be used. IDGREY models evaluate a user-specified MATLAB file for estimating statespace system parameters. Multi-variate ARX models offer another option for quickly estimating multioutput models with user-specified structure.
Additional Information
For more information on identification of dynamic systems with System Identification Toolbox visit the
System Identification Toolbox product information page.