Ident Ref PDF
Ident Ref PDF
Reference
Lennart Ljung
R2020a
How to Contact MathWorks
Phone: 508-647-7000
    Functions
1
      Blocks
2
            v
            1
Functions
1     Functions
            absorbDelay
            Replace time delays by poles at z = 0 or phase shift
            Syntax
            sysnd = absorbDelay(sysd)
            [sysnd,G] = absorbDelay(sysd)
            Description
            sysnd = absorbDelay(sysd) absorbs all time delays of the dynamic system model sysd into the
            system dynamics or the frequency response data.
            For discrete-time models (other than frequency response data models), a delay of k sampling periods
            is replaced by k poles at z = 0. For continuous-time models (other than frequency response data
            models), time delays have no exact representation with a finite number of poles and zeros. Therefore,
            use pade to compute a rational approximation of the time delay.
            For frequency response data models in both continuous and discrete time, absorbDelay absorbs all
            time delays into the frequency response data as a phase shift.
            [sysnd,G] = absorbDelay(sysd) returns the matrix G that maps the initial states of the ss
            model sysd to the initial states of the sysnd.
Examples
            z = tf('z',-1);
            sysd = (-0.4*z -0.1)/(z^2 + 1.05*z + 0.08);
            sysd.InputDelay = 3
sysd =
                              -0.4 z - 0.1
                  z^(-3) * -------------------
                           z^2 + 1.05 z + 0.08
            The display of sysd represents the InputDelay as a factor of z^(-3), separate from the system
            poles that appear in the transfer function denominator.
sysnd = absorbDelay(sysd)
1-2
                                                                                         absorbDelay
sysnd =
        -0.4 z - 0.1
  -------------------------
  z^5 + 1.05 z^4 + 0.08 z^3
The display of sysnd shows that the factor of z^(-3) has been absorbed as additional poles in the
denominator.
sysnd.InputDelay
ans = 0
m = idpoly(1,[0 0 0 2 3]);
sys = tf(m)
sys =
The numerator of the transfer function, sys, is [0 2 3] and the transport delay, sys.IODelay, is 2.
This is because the value of the B polynomial, m.B, has 3 leading zeros. The first fixed zero shows
lack of feedthrough in the model. The two zeros after that are treated as input-output delays.
m2 = absorbDelay(m);
sys2 = tf(m2)
sys2 =
2 z^-3 + 3 z^-4
The numerator of sys2 is [0 0 0 2 3] and transport delay is 0. The model m2 treats the leading
zeros as regular coefficients by freeing their values. m2.Structure.B.Free(2:3) is TRUE while
m.Structure.B.Free(2:3) is FALSE.
                                                                                                 1-3
1     Functions
            See Also
            hasdelay | pade | totaldelay
Introduced in R2012a
1-4
                                                                                               advice
advice
Analysis and recommendations for data or estimated linear models
Syntax
advice(data)
advice(model,data)
Description
advice(data) displays the following information about the data in the MATLAB® Command
Window:
• What are the excitation levels of the signals and how does this affect the model orders? See also
  pexcit.
• Does it make sense to remove constant offsets and linear trends from the data? See also detrend.
• Is there an indication of output feedback in the data? See also feedback.
• Would a nonlinear ARX model perform better than a linear ARX model?
advice(model,data) displays the following information about the estimated linear model in the
MATLAB Command Window:
• Does the model capture essential dynamics of the system and the disturbance characteristics?
• Is the model order higher than necessary?
• Is there potential output feedback in the validation data?
Input Arguments
data
model
See Also
detrend | feedback | iddata | pexcit
                                                                                                  1-5
1     Functions
            addreg
            Add custom regressors to nonlinear ARX model
            Syntax
            m = addreg(model,regressors)
            m = addreg(model,regressors,output)
            Description
            m = addreg(model,regressors) adds custom regressors to a nonlinear ARX model by appending
            the CustomRegressors model property. model and m are idnalrx objects. For single-output
            models, regressors is an object array of regressors you create using customreg or polyreg, or a
            cell array of character vectors. For multiple-output models, regressors is 1-by-ny cell array of
            customreg objects or 1-by-ny cell array of cell arrays of character vectors. addreg adds each
            element of the ny cells to the corresponding model output channel. If regressors is a single
            regressor, addreg adds this regressor to all output channels.
Examples
            Create model with additional custom regressors, specified as a cell array of character vectors.
                  m2 = addreg(m1,{'y1(t-2)^2';'u1(t)*y1(t-7)'});
            Regressors:
                y1(t-1)
                y1(t-2)
                y1(t-3)
                y1(t-4)
                u1(t-1)
                u1(t-2)
                y1(t-2)^2
                u1(t)*y1(t-7)
1-6
                                                               addreg
m1 = idnlarx([4 2 1],'wavenet','nlr',[1:3]);
r1 = customreg(@(x)x^2,{'y1'},2)
Custom Regressor:
Expression: y1(t-2)^2
        Function: @(x)x^2
       Arguments: {'y1'}
          Delays: 2
      Vectorized: 0
    TimeVariable: 't'
r2 = customreg(@(x,y)x*y,{'u1','y1'},[0 7])
Custom Regressor:
Expression: u1(t)*y1(t-7)
        Function: @(x,y)x*y
       Arguments: {'u1' 'y1'}
          Delays: [0 7]
      Vectorized: 0
    TimeVariable: 't'
m2 = addreg(m1,[r1 r2]);
getreg(m2)
Regressors:
    y1(t-1)
    y1(t-2)
    y1(t-3)
    y1(t-4)
    u1(t-1)
    u1(t-2)
    y1(t-2)^2
    u1(t)*y1(t-7)
See Also
customreg | getreg | nlarx | polyreg
Topics
“Identifying Nonlinear ARX Models”
Introduced in R2007a
                                                                 1-7
1     Functions
            aic
            Akaike’s Information Criterion for estimated model
            Syntax
            value = aic(model)
            value = aic(model1,...,modeln)
            value = aic( ___ ,measure)
            Description
            value = aic(model) returns the normalized “Akaike's Information Criterion (AIC)” on page 1-11
            value for the estimated model.
            value = aic(model1,...,modeln) returns the normalized AIC values for multiple estimated
            models.
Examples
value = 0.5453
            The value is also computed during model estimation. Alternatively, use the Report property of the
            model to access this value.
            sys.Report.Fit.nAIC
ans = 0.5453
1-8
                                                                                                  aic
Compute the normalized Akaike's Information Criterion (AIC) value. This syntax is equivalent to
aic_raw = aic(sys).
aic_raw = aic(sys,'nAIC')
aic_raw = 0.5453
aic_raw = aic(sys,'aic')
aic_raw = 1.0150e+03
aic_c = aic(sys,'AICc')
aic_c = 1.0153e+03
bic = aic(sys,'BIC')
bic = 1.0372e+03
These values are also computed during model estimation. Alternatively, use the Report.Fit
property of the model to access these values.
sys.Report.Fit
Pick Model with Optimal Tradeoff Between Accuracy and Complexity Using AICc Criterion
Estimate multiple Output-Error (OE) models and use the small sample-size corrected Akaike's
Information Criterion (AICc) value to pick the one with optimal tradeoff between accuracy and
complexity.
load iddata2
nf = 1:4;
nb = 1:4;
nk = 0:4;
                                                                                                  1-9
1   Functions
          Compute the small sample-size corrected AIC values for the models, and return the smallest value.
          V = aic(models{:},'AICc');
          [Vmin,I] = min(V);
          Return the optimal model that has the smallest AICc value.
          models{I}
          ans =
          Discrete-time OE model: y(t) = [B(z)/F(z)]u(t) + e(t)
            B(z) = 1.067 z^-2
          Parameterization:
             Polynomial orders:   nb=1   nf=3   nk=2
             Number of free coefficients: 4
             Use "polydata", "getpvec", "getcov" for parameters and their uncertainties.
          Status:
          Estimated using OE on time domain data "z2".
          Fit to estimation data: 86.53%
          FPE: 0.9809, MSE: 0.9615
          Input Arguments
          model — Identified model
          idtf | idgrey | idpoly | idproc | idss | idnlarx, | idnlhw | idnlgrey
          • idtf
          • idgrey
          • idpoly
          • idproc
          • idss
          • idnlarx, except nonlinear ARX model that includes a binary-tree or neural network nonlinearity
            estimator
          • idnlhw
          • idnlgrey
1-10
                                                                                                     aic
See “Akaike's Information Criterion (AIC)” on page 1-11 for more information.
Output Arguments
value — Value of quality metric
scalar | vector
Value of the quality measure, returned as a scalar or vector. For multiple models, value is a row
vector where value(k) corresponds to the kth estimated model modelk.
More About
Akaike's Information Criterion (AIC)
Akaike's Information Criterion (AIC) provides a measure of model quality obtained by simulating the
situation where the model is tested on a different data set. After computing several different models,
you can compare them using this criterion. According to Akaike's theory, the most accurate model has
the smallest AIC. If you use the same data set for both model estimation and validation, the fit always
improves as you increase the model order and, therefore, the flexibility of the model structure.
where:
                               np + 1
     AICc = AIC + 2np *
                             N − np − 1
• Normalized AIC, defined as:
                         N                               2np
                     1                           T
    nAIC = log det   N   ∑ ε t, θ N   ε t, θ N       +
                                                          N
                         1
                                                                                                    1-11
1   Functions
                                        N
                                    1                           T
                BIC = N * log det   N   ∑ ε t, θ N   ε t, θ N       + N * (ny * log(2π) + 1) + np * log(N)
                                        1
          Tips
          • The software computes and stores all types of Akaike's Information Criterion metrics during model
            estimation. If you want to access these values, see the Report.Fit property of the model.
          References
          [1] Ljung, L. System Identification: Theory for the User, Upper Saddle River, NJ, Prentice-Hall PTR,
                  1999. See sections about the statistical framework for parameter estimation and maximum
                  likelihood method and comparing model structures.
          See Also
          fpe | goodnessOfFit
          Topics
          “Loss Function and Model Quality Metrics”
1-12
                                                                                                  append
append
Group models by appending their inputs and outputs
Syntax
sys = append(sys1,sys2,...,sysN)
Description
sys = append(sys1,sys2,...,sysN) appends the inputs and outputs of the models
sys1,...,sysN to form the augmented model sys depicted below.
For systems with transfer functions H1(s), . . . , HN(s), the resulting system sys has the block-diagonal
transfer function
     H1(s)       0   …    0
        0       H2(s) ⋯   ⋮
        ⋮        ⋮   ⋱    0
        0        ⋯   0 HN(s)
For state-space models sys1 and sys2 with data (A1, B1, C1, D1) and (A2, B2, C2, D2),
append(sys1,sys2) produces the following state-space model:
     ẋ 1       A1 0 x1       B1 0 u1
            =             +
     ẋ 2       0 A2 x2       0 B2 u2
     y1         C1 0 x1       D1 0 u1
            =             +
     y2         0 C2 x2       0 D2 u2
                                                                                                    1-13
1   Functions
          Arguments
          The input arguments sys1,..., sysN can be model objects s of any type. Regular matrices are also
          accepted as a representation of static gains, but there should be at least one model in the input list.
          The models should be either all continuous, or all discrete with the same sample time. When
          appending models of different types, the resulting type is determined by the precedence rules (see
          “Rules That Determine Model Type” (Control System Toolbox) for details).
Examples
          Append the inputs and outputs of sys1, a SISO static gain system, and sys2. The resulting model
          should be a 3-input, 3-output state-space model.
          sys = append(sys1,10,sys2)
sys =
                A =
                      x1   x2
                x1     0    0
                x2     0    1
                B =
                      u1   u2   u3
                x1     1    0    0
                x2     0    0    2
                C =
                      x1   x2
                y1     1    0
                y2     0    0
                y3     0    3
                D =
                      u1   u2   u3
                y1     0    0    0
                y2     0   10    0
                y3     0    0    4
1-14
                                                            append
size(sys)
See Also
connect | feedback | parallel | series
Introduced in R2012a
                                                             1-15
1   Functions
          ar
          Estimate parameters of AR model or ARI model for scalar time series
          Syntax
          sys = ar(y,n)
          sys = ar(y,n,approach,window)
          sys = ar(y,n, ___ ,Name,Value)
          sys = ar(y,n, ___ ,opt)
          [sys,refl] = ar(y,n,approach, ___ )
          Description
          sys = ar(y,n) estimates the parameters of an AR on page 1-24 idpoly model sys of order n
          using a least-squares method. The model properties include covariances (parameter uncertainties)
          and estimation goodness of fit.
          sys = ar(y,n, ___ ,Name,Value) specifies additional options using one or more name-value pair
          arguments. For instance, using the name-value pair argument 'IntegrateNoise',1 estimates an
          ARI on page 1-24 model, which is useful for systems with nonstationary disturbances. Specify
          Name,Value after any of the input argument combinations in the previous syntaxes.
sys = ar(y,n, ___ ,opt) specifies estimation options using the option set opt.
Examples
AR Model
Estimate an AR model and compare its response with the measured output.
Load the data, which contains the time series z9 with noise.
load iddata9 z9
sys = ar(z9,4)
          sys =
          Discrete-time AR model: A(z)y(t) = e(t)
            A(z) = 1 - 0.8369 z^-1 - 0.4744 z^-2 - 0.06621 z^-3 + 0.4857 z^-4
1-16
                                                                                                       ar
Parameterization:
   Polynomial orders:   na=4
   Number of free coefficients: 4
   Use "polydata", "getpvec", "getcov" for parameters and their uncertainties.
Status:
Estimated using AR ('fb/now') on time domain data "z9".
Fit to estimation data: 79.38%
FPE: 0.5189, MSE: 0.5108
The output displays the polynomial containing the estimated parameters alongside other estimation
details. Under Status, Fit to estimation data shows that the estimated model has 1-step-
ahead prediction accuracy above 75%.
You can find additional information about the estimation results by exploring the estimation report,
sys.Report. For instance, you can retrieve the parameter covariance.
covar = sys.Report.Parameters.FreeParCovariance
covar = 4×4
For more information on viewing the estimation report, see “Estimation Report”.
Given a sinusoidal signal with noise, compare the spectral estimates of Burg's method with those
found using the forward-backward approach.
y = sin([1:300]') + 0.5*randn(300,1);
y = iddata(y);
Estimate fourth-order AR models using Burg's method and using the default forward-backward
approach. Plot the model spectra together.
sys_b = ar(y,4,'burg');
sys_fb = ar(y,4);
spectrum(sys_b,sys_fb)
legend('Burg','Forward-Backward')
                                                                                                   1-17
1   Functions
The two responses match closely throughout most of the frequency range.
ARI Model
Load the data, which contains the time series z9 with noise.
load iddata9 z9
y = cumsum(z9.y);
          Estimate an AR model with 'IntegrateNoise' set to true. Use the least-squares method 'ls'.
          Because y is a vector and not an iddata object, specify Ts.
          Ts = z9.Ts;
          sys = ar(y,4,'ls','Ts',Ts,'IntegrateNoise',true);
          Predict the model output using 5-step prediction and compare the result with the integrated output
          signal y.
compare(y,sys,5)
1-18
                                                                                                 ar
Modify the default options so that the function uses the 'ls' approach and does not estimate
covariance.
opt = arOptions('Approach','ls','EstimateCovariance',false)
opt =
Option set for the ar command:
              Approach:     'ls'
                Window:     'now'
            DataOffset:     0
    EstimateCovariance:     0
               MaxSize:     250000
Description of options
                                                                                               1-19
1   Functions
sys = ar(z9,4,opt);
Retrieve reflection coefficients and loss functions when using Burg's method.
          Lattice-based approaches such, as Burg's method 'burg' and geometric lattice 'gl', compute
          reflection coefficients and corresponding loss function values as part of the estimation process. Use a
          second output argument to retrieve these values.
          Estimate a fourth-order AR model using Burg's method and include an output argument for the
          reflection coefficients.
          [sys,refl] = ar(y,4,'burg');
          refl
refl = 2×5
          Input Arguments
          y — Time-series data
          iddata object | double vector
          • An iddata object that contains a single output channel and an empty input channel.
          • A double column vector containing output-channel data. When you specify y as a vector, you must
            also specify the sample time Ts.
          n — Model order
          positive integer
          Model order, specified as a positive integer. The value of n determines the number of A parameters in
          the AR model.
          Example: ar(idy,2) computes a second-order AR model from the single-channel iddata object idy
Algorithm for computing the AR model, specified as one of the following values:
          • 'burg': Burg's lattice-based method. Solves the lattice filter equations using the harmonic mean
            of forward and backward squared prediction errors.
1-20
                                                                                                      ar
• 'fb': (Default) Forward-backward approach. Minimizes the sum of a least-squares criterion for a
  forward model, and the analogous criterion for a time-reversed model.
• 'gl': Geometric lattice approach. Similar to Burg's method, but uses the geometric mean instead
  of the harmonic mean during minimization.
• 'ls': Least-squares approach. Minimizes the standard sum of squared forward-prediction errors.
• 'yw': Yule-Walker approach. Solves the Yule-Walker equations, formed from sample covariances.
All of these algorithms are variants of the least-squares method. For more information, see
“Algorithms” on page 1-25 .
Example: ar(idy,2,'ls') computes an AR model using the least-squares approach
Prewindowing and postwindowing outside the measured time interval (past and future values),
specified as one of the following values:
• 'now': No windowing. This value is the default except when you set approach to 'yw'. Only
  measured data is used to form regression vectors. The summation in the criteria starts at the
  sample index equal to n+1.
• 'pow': Postwindowing. Missing end values are replaced with zeros and the summation is
  extended to time N+n (N is the number of observations).
• 'ppw': Prewindowing and postwindowing. The software uses this value whenever you select the
  Yule-Walker approach 'yw', regardless of your window specification.
• 'prw': Prewindowing. Missing past values are replaced with zeros so that the summation in the
  criteria can start at time equal to zero.
Estimation options for AR model identification, specified as an arOptions option set. opt specifies
the following options:
• Estimation approach
• Data windowing technique
• Data offset
• Maximum number of elements in a segment of data
For more information, see arOptions. For an example, see “Modify Default Options” on page 1-19.
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Example: 'IntegrateNoise',true adds an integrator in the noise source
                                                                                                  1-21
1   Functions
          Ts — Sample time
          1 (default) | positive scalar
          Sample time, specified as the comma-separated pair consisting of 'Ts' and the sample time in
          seconds. If y is a double vector, then you must specify 'Ts'.
          Example: ar(y_signal,2,'Ts',0.08) computes a second-order AR model with sample time of
          0.08 seconds
          Noise-channel integration option for estimating ARI on page 1-24 models, specified as the comma-
          separated pair consisting of 'IntegrateNoise' and a logical. Noise integration is useful in cases
          where the disturbance is nonstationary.
          When using 'IntegrateNoise', you must also integrate the output-channel data. For an example,
          see “ARI Model” on page 1-18.
          Output Arguments
          sys — AR or ARI model
          idpoly model object
          AR on page 1-24 or ARI on page 1-24 model that fits the given estimation data, returned as a
          discrete-time idpoly model object. This model is created using the specified model orders, delays,
          and estimation options.
          Information about the estimation results and options used is stored in the Report property of the
          model. Report has the following fields.
           Report       Description
           Field
           Status       Summary of the model status, which indicates whether the model was created by
                        construction or obtained by estimation.
           Method       Estimation command used.
1-22
                                                                                                   ar
Report       Description
Field
Fit          Quantitative assessment of the estimation, returned as a structure. See “Loss Function
             and Model Quality Metrics” for more information on these quality metrics. The
             structure has the following fields:
             Field         Description
             FitPerce Normalized root mean squared error (NRMSE) measure of how well the
             nt       response of the model fits the estimation data, expressed as the
                      percentage fit = 100(1-NRMSE).
             LossFcn       Value of the loss function when the estimation completes.
             MSE           Mean squared error (MSE) measure of how well the response of the
                           model fits the estimation data.
             FPE           Final prediction error for the model.
             AIC           Raw Akaike Information Criteria (AIC) measure of model quality.
             AICc          Small sample-size corrected AIC.
             nAIC          Normalized AIC.
             BIC           Bayesian Information Criteria (BIC).
Parameter Estimated values of model parameters.
s
OptionsUs Option set used for estimation. If no custom options were configured, this is a set of
ed        default options. See arOptions for more information.
RandState State of the random number stream at the start of estimation. Empty, [], if
          randomization was not used during estimation. For more information, see rng in the
          MATLAB documentation.
                                                                                               1-23
1   Functions
           Report        Description
           Field
           DataUsed      Attributes of the data used for estimation, returned as a structure with the following
                         fields:
                          Field        Description
                          Name         Name of the data set.
                          Type         Data type.
                          Length       Number of data samples.
                          Ts           Sample time.
                          InterSam Input intersample behavior, returned as one of the following values:
                          ple
                                   • 'zoh' — Zero-order hold maintains a piecewise-constant input signal
                                      between samples.
                                       • 'foh' — First-order hold maintains a piecewise-linear input signal
                                         between samples.
                                       • 'bl' — Band-limited behavior specifies that the continuous-time input
                                         signal has zero power above the Nyquist frequency.
                          InputOff Offset removed from time-domain input data during estimation. For
                          set      nonlinear models, it is [].
                          OutputOf Offset removed from time-domain output data during estimation. For
                          fset     nonlinear models, it is [].
          Reflection coefficients and loss functions, returned as a 2-by-2 array. For the two lattice-based
          approaches 'burg' and 'gl', refl stores the reflection coefficients in the first row and the
          corresponding loss function values in the second row. The first column of refl is the zeroth-order
          model, and the (2,1) element of refl is the norm of the time series itself. For an example, see
          “Retrieve Reflection Coefficients for Burg's Method” on page 1-20.
          More About
          AR (Autoregressive) Model
The AR model structure has no input, and is given by the following equation:
A(q)y(t) = e(t)
          This model structure accommodates estimation for scalar time-series data, which have no input
          channel. The structure is a special case of the ARX structure.
          The ARI model is an AR model with an integrator in the noise channel. The ARI model structure is
          given by the following equation:
1-24
                                                                                                         ar
                     1
     A(q)y(t) =           e(t)
                  1 − q−1
Algorithms
AR and ARI model parameters are estimated using variants of the least-squares method. The
following table summarizes the common names for methods with a specific combination of approach
and window argument values.
References
[1] Marple, S. L., Jr. Chapter 8. Digital Spectral Analysis with Applications. Englewood Cliffs, NJ:
       Prentice Hall, 1987.
See Also
arOptions | arx | etfe | forecast | iddata | idpoly | ivar | pem | spa | spectrum
Topics
“What Are Time Series Models?”
“Representing Data in MATLAB Workspace”
“Identify Time-Series Models at the Command Line”
Introduced in R2006a
                                                                                                       1-25
1   Functions
          armax
          Estimate parameters of ARMAX, ARIMAX, ARMA, or ARIMA model using time-domain data
          Syntax
          sys = armax(data,[na nb nc nk])
          sys = armax(data,[na nb nc nk],Name,Value)
sys = armax(data,init_sys)
          Description
          Estimate an ARMAX Model
          sys = armax(data,init_sys) uses the discrete-time linear model init_sys to configure the
          initial parameterization.
          Specify Additional Options
          sys = armax(data, ___ ,opt) incorporates an option set opt that specifies options such as
          estimation objective, handling of initial conditions, regularization, and numerical search method to
          use for estimation. Specify opt after any of the previous input-argument combinations.
Examples
Estimate an ARMAX model and view the fit of the model output to the estimation data.
          Estimate an ARMAX model with second-order A,B, and C polynomials and a transport delay of one
          sample period.
          na = 2;
          nb = 2;
1-26
                                                                                             armax
nc = 2;
nk = 1;
sys = armax(z2,[na nb nc nk])
sys =
Discrete-time ARMAX model: A(z)y(t) = B(z)u(t) + C(z)e(t)
  A(z) = 1 - 1.512 z^-1 + 0.7006 z^-2
Parameterization:
   Polynomial orders:   na=2   nb=2   nc=2   nk=1
   Number of free coefficients: 6
   Use "polydata", "getpvec", "getcov" for parameters and their uncertainties.
Status:
Estimated using ARMAX on time domain data "z2".
Fit to estimation data: 85.89% (prediction focus)
FPE: 1.086, MSE: 1.054
The output displays the polynomial containing the estimated parameters alongside the estimation
details. Under Status, Fit to estimation data shows that the estimated model has 1-step-
ahead prediction accuracy above 80%.
compare(z2,sys)
                                                                                              1-27
1   Functions
The fit of the simulated model to the measured data is nearly the same as the estimation fit.
ARMA Model
Estimate an ARMA model and compare its response with both the measured output and an AR model.
Load the data, which contains the time series z9 with noise.
load iddata9 z9
          na = 4;
          nc = 1;
          sys = armax(z9,[na nc]);
sys_ar = ar(z9,na);
compare(z9,sys,sys_ar)
1-28
                                                                                             armax
Estimate an ARMAX model from measured data and specify estimation options.
Load the data and create an iddata object. Initialize option set opt, and set options for Focus,
SearchMethod, MaxIterations, and Display. Then estimate the ARMAX model using the updated
option set.
load twotankdata;
z = iddata(y,u,0.2);
opt = armaxOptions;
opt.Focus = 'simulation';
opt.SearchMethod = 'lm';
opt.SearchOptions.MaxIterations = 10;
opt.Display = 'on';
sys = armax(z,[2 2 2 1],opt);
The termination conditions for measured component of the model shown in the progress viewer is
that the maximum number of iterations were reached.
To improve results, re-estimate the model using a greater value for MaxIterations, or continue
iterations on the previously estimated model as follows:
                                                                                             1-29
1   Functions
          sys2 = armax(z,sys);
          compare(z,sys,sys2)
where sys2 refines the parameters of sys to improve the fit to data.
Load data.
m1 = armax(m0simdata(1:150),[30 30 30 1]);
Estimate a regularized ARMAX model by determining the Lambda value by trial and error.
          opt = armaxOptions;
          opt.Regularization.Lambda = 1;
          m2 = armax(m0simdata(1:150),[30 30 30 1],opt);
          Obtain a lower order ARMAX model by converting a regularized ARX model and then performing
          order reduction.
1-30
                                                                                              armax
opt1 = arxOptions;
[L,R] = arxRegul(m0simdata(1:150),[30 30 1]);
opt1.Regularization.Lambda = L;
opt1.Regularization.R = R;
m0 = arx(m0simdata(1:150),[30 30 1],opt1);
mr = idpoly(balred(idss(m0),7));
ARIMA Model
Integrate the output signal and use the result to replace the original output signal in z9.
z9.y = cumsum(z9.y);
                                                                                              1-31
1   Functions
          Predict the model output using 10-step ahead prediction, and compare the predicted output with the
          estimation data.
          compare(z9,model,10)
          Load dryer2 data and perform estimation for combinations of polynomial orders na, nb, nc, and
          input delay nk.
          load dryer2;
          z = iddata(y2,u2,0.08,'Tstart',0);
          na = 2:4;
          nc = 1:2;
          nk = 0:2;
          models = cell(1,18);
          ct = 1;
          for i = 1:3
              na_ = na(i);
              nb_ = na_;
              for j = 1:2
1-32
                                                                                             armax
            nc_ = nc(j);
            for k = 1:3
                nk_ = nk(k);
                models{ct} = armax(z,[na_ nb_ nc_ nk_]);
                ct = ct+1;
            end
      end
end
Stack the estimated models and compare their simulated responses to the estimation data z.
models = stack(1,models{:});
compare(z,models)
Estimate an ARMAX model using the previously estimated state-space model to initialize the
parameters.
                                                                                             1-33
1   Functions
sys = armax(z2,sys0);
          Input Arguments
          data — Time-domain estimation data
          iddata object
          Time-domain estimation data, specified as an iddata object. For ARMA and ARIMA time-series
          models, the input channel in data must be empty. For examples, see “ARMA Model” on page 1-28 and
          “ARIMA Model” on page 1-31.
          Polynomial orders and delays for the model, specified as a 1-by-4 vector or vector of matrices [na nb
          nc nk]. The polynomial order is equal to the number of coefficients to estimate in that polynomial.
          For an ARMA or ARIMA time-series model, which has no input, set [na nb nc nk] to [na nc]. For
          an example, see “ARMA Model” on page 1-28.
          • na is the order of the polynomial A(q), specified as an Ny-by-Ny matrix of nonnegative integers.
          • nb is the order of the polynomial B(q) + 1, specified as an Ny-by-Nu matrix of nonnegative
            integers.
          • nc is the order of the polynomial C(q), specified as a column vector of nonnegative integers of
            length Ny.
          • nk is the input-output delay, also known at the transport delay, specified as an Ny-by-Nu matrix of
            nonnegative integers. nk is represented in ARMAX models by fixed leading zeros of the B
            polynomial.
          System for configuring the initial parameterization of sys, specified as a discrete-time linear model.
          You obtain init_sys by either performing an estimation using measured data or by direct
          construction using commands such as idpoly and idss.
          If init_sys is an ARMAX model, armax uses the parameter values of init_sys as the initial guess
          for estimation. To configure initial guesses and constraints for A(q), B(q), and C(q), use the
          Structure property of init_sys. For example:
          • To specify an initial guess for the A(q) term of init_sys, set init_sys.Structure.A.Value as
            the initial guess.
          • To specify constraints for the B(q) term of init_sys:
1-34
                                                                                                    armax
If init_sys is not a polynomial model with the ARMAX structure, the software first converts
init_sys to an ARMAX model. armax uses the parameters of the resulting model as the initial guess
for estimating sys.
If opt is not specified and init_sys was obtained by estimation, then the estimation options from
init_sys.Report.OptionsUsed are used.
For an example, see “Initialize ARMAX Model Parameters Using State-Space Model” on page 1-33.
Estimation options for ARMAX model identification, specified as an armaxOptions option set.
Options specified by opt include the following:
• Initial condition handling — Use this option to determine how the initial conditions are set or
  estimated.
• Input and output data offsets — Use these options to remove offsets from data during estimation.
• Regularization — Use this option to control the tradeoff between bias and variance errors during
  the estimation process.
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Example: 'InputDelay',2 applies an input delay of two sample periods to all input channels
Input delays expressed as integer multiples of the sample time, specified as the comma-separated
pair consisting of 'InputDelay' and one of the following:
• Nu-by-1 vector, where Nu is the number of inputs — Each entry is a numerical value representing
  the input delay for the corresponding input channel.
• Scalar value — Apply the same delay to all input channels.
• 0 — No input delays.
Transport delays for each input-output pair, expressed as integer multiples of the sample time, and
specified as the comma-separated pair consisting of 'IODelay' and one of the following:
• Ny-by-Nu matrix, where Ny is the number of outputs and Nu is the number of inputs — Each entry
  is an integer value representing the transport delay for the corresponding input-output pair.
• Scalar value — Apply the same delay to all input-output pairs.
                                                                                                    1-35
1   Functions
          'IODelay' is useful as a replacement for the nk order. You can factor out max(nk-1,0) lags as the
          'IODelay' value. For nk > 1, armax(na,nb,nk) is equivalent to
          armax(na,nb,1,'IODelay',nk-1).
          Addition of integrators in the noise channel, specified as the comma-separated pair consisting of
          'IntegrateNoise' and a logical vector of length Ny, where Ny is the number of outputs.
                                               C(q)
                A(q)y(t) = B(q)u(t − nk) +           e(t)
                                             1 − q−1
                     1
          where           is the integrator in the noise channel, e(t).
                  1 − q−1
          Output Arguments
          sys — ARMAX model
          idpoly object
          ARMAX model that fits the given estimation data, returned as a discrete-time idpoly object. This
          model is created using the specified model orders, delays, and estimation options.
          Information about the estimation results and options used is stored in the Report property of the
          model. Report has the following fields.
           Report        Description
           Field
           Status        Summary of the model status, which indicates whether the model was created by
                         construction or obtained by estimation.
           Method        Estimation command used.
           InitialCo Handling of initial conditions during model estimation, returned as one of the following
           ndition   values:
                         This field is especially useful to view how the initial conditions were handled when the
                         InitialCondition option in the estimation option set is 'auto'.
1-36
                                                                                              armax
Report       Description
Field
Fit          Quantitative assessment of the estimation, returned as a structure. See “Loss Function
             and Model Quality Metrics” for more information on these quality metrics. The
             structure has the following fields:
             Field         Description
             FitPerce Normalized root mean squared error (NRMSE) measure of how well the
             nt       response of the model fits the estimation data, expressed as the
                      percentage fit = 100(1-NRMSE).
             LossFcn       Value of the loss function when the estimation completes.
             MSE           Mean squared error (MSE) measure of how well the response of the
                           model fits the estimation data.
             FPE           Final prediction error for the model.
             AIC           Raw Akaike Information Criteria (AIC) measure of model quality.
             AICc          Small sample-size corrected AIC.
             nAIC          Normalized AIC.
             BIC           Bayesian Information Criteria (BIC).
Parameter Estimated values of model parameters.
s
OptionsUs Option set used for estimation. If no custom options were configured, this is a set of
ed        default options. See armaxOptions for more information.
RandState State of the random number stream at the start of estimation. Empty, [], if
          randomization was not used during estimation. For more information, see rng in the
          MATLAB documentation.
                                                                                               1-37
1   Functions
           Report      Description
           Field
           DataUsed    Attributes of the data used for estimation, returned as a structure with the following
                       fields:
                        Field        Description
                        Name         Name of the data set.
                        Type         Data type.
                        Length       Number of data samples.
                        Ts           Sample time.
                        InterSam Input intersample behavior, returned as one of the following values:
                        ple
                                 • 'zoh' — Zero-order hold maintains a piecewise-constant input signal
                                    between samples.
                                     • 'foh' — First-order hold maintains a piecewise-linear input signal
                                       between samples.
                                     • 'bl' — Band-limited behavior specifies that the continuous-time input
                                       signal has zero power above the Nyquist frequency.
                        InputOff Offset removed from time-domain input data during estimation. For
                        set      nonlinear models, it is [].
                        OutputOf Offset removed from time-domain output data during estimation. For
                        fset     nonlinear models, it is [].
           Terminati Termination conditions for the iterative search used for prediction error minimization.
           on        Structure with the following fields:
                        Field        Description
                        WhyStop      Reason for terminating the numerical search.
                        Iteratio Number of search iterations performed by the estimation algorithm.
                        ns
                        FirstOrd ∞-norm of the gradient search vector when the search algorithm
                        erOptima terminates.
                        lity
                        FcnCount Number of times the objective function was called.
                        UpdateNo Norm of the gradient search vector in the last iteration. Omitted when the
                        rm       search method is 'lsqnonlin' or 'fmincon'.
                        LastImpr Criterion improvement in the last iteration, expressed as a percentage.
                        ovement Omitted when the search method is 'lsqnonlin' or 'fmincon'.
                        Algorith Algorithm used by 'lsqnonlin' or 'fmincon' search method. Omitted
                        m        when other search methods are used.
                       For estimation methods that do not require numerical search optimization, the
                       Termination field is omitted.
1-38
                                                                                              armax
More About
ARMAX Model
The ARMAX (Autoregressive Moving Average with Extra Input) model structure is:
where
The parameters na, nb, and nc are the orders of the ARMAX model, and nk is the delay. q is the delay
operator. Specifically,
                                      −na
     A(q) = 1 + a1q−1 + … + anaq
                                       −nb + 1
     B(q) = b1 + b2q−1 + … + bnbq
                                     −nc
     C(q) = 1 + c1q−1 + … + cncq
The ARMA (Autoregressive Moving Average) model is a special case of an “ARMAX Model” on page 1-
39 with no input channels. The ARMA single-output model structure is given by the following
equation:
A(q)y(t) = C(q)e(t)
ARIMAX Model
The ARIMAX (Autoregressive Integrated Moving Average with Extra Input) model structure is similar
to the ARMAX model, except that it contains an integrator in the noise source e(t):
                                                                                               1-39
1   Functions
                                                 C(q)
                A(q)y(t) = B(q)u(t − nk) +              e(t)
                                              (1 − q−1)
ARIMA Model
          The ARIMA (Autoregressive Integrated Moving Average) model structure is a reduction of the
          ARIMAX model with no inputs:
                                C(q)
                A(q)y(t) =             e(t)
                             (1 − q−1)
          Algorithms
          An iterative search algorithm minimizes a robustified quadratic prediction error criterion. The
          iterations are terminated when any of the following is true:
You can get information about the stopping criteria using sys.Report.Termination.
          Use the armaxOptions option set to create and configure options affecting the estimation results. In
          particular, set the search algorithm attributes, such as MaxIterations and Tolerance, using the
          'SearchOptions' property.
          When you do not specify initial parameter values for the iterative search as an initial model, they are
          constructed in a special four-stage LS-IV algorithm.
          The cutoff value for the robustification is based on the Advanced.ErrorThreshold estimation
          option and on the estimated standard deviation of the residuals from the initial parameter estimate.
          The cutoff value is not recalculated during the minimization. By default, no robustification is
          performed; the default value of ErrorThreshold option is 0.
          To ensure that only models corresponding to stable predictors are tested, the algorithm performs a
          stability test of the predictor. Generally, both C(q) and F(q) (if applicable) must have all zeros inside
          the unit circle.
          Minimization information is displayed on the screen when the estimation option 'Display' is 'On'
          or 'Full'. When 'Display' is 'Full', both the current and the previous parameter estimates are
          displayed in column-vector form, and the parameters are listed in alphabetical order. Also, the values
          of the criterion function (cost) are given and the Gauss-Newton vector and its norm are displayed.
          When 'Display' is 'On', only the criterion values are displayed.
          Alternatives
          armax does not support continuous-time model estimation. Use tfest to estimate a continuous-time
          transfer function model, or ssest to estimate a continuous-time state-space model.
          armax supports only time-domain data. For frequency-domain data, use oe to estimate an Output-
          Error (OE) model.
1-40
                                                                                                    armax
References
[1] Ljung, L. System Identification: Theory for the User, Second Edition. Upper Saddle River, NJ:
        Prentice-Hall PTR, 1999. See chapter about computing the estimate.
Extended Capabilities
Automatic Parallel Support
Accelerate code by automatically running computation in parallel using Parallel Computing Toolbox™.
Parallel computing support is available for estimation using the lsqnonlin search method (requires
Optimization Toolbox™). To enable parallel computing, use armaxOptions, set SearchMethod to
'lsqnonlin', and set SearchOptions.Advanced.UseParallel to true.
For example:
opt = armaxOptions;
opt.SearchMethod = 'lsqnonlin';
opt.SearchOptions.Advanced.UseParallel = true;
See Also
aic | armaxOptions | arx | bj | compare | fpe | iddata | idpoly | oe | polyest | ssest | tfest
Topics
“What Are Polynomial Models?”
“What Are Time Series Models?”
“Estimate Models Using armax”
“Estimation Report”
“Loss Function and Model Quality Metrics”
“Regularized Estimates of Model Parameters”
Introduced in R2006a
                                                                                                    1-41
1   Functions
          armaxOptions
          Option set for armax
          Syntax
          opt = armaxOptions
          opt = armaxOptions(Name,Value)
          Description
          opt = armaxOptions creates the default options set for armax.
          opt = armaxOptions(Name,Value) creates an option set with the options specified by one or
          more Name,Value pair arguments.
          Input Arguments
          Name-Value Pair Arguments
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Handling of initial conditions during estimation, specified as one of the following values:
          Error to be minimized in the loss function during estimation, specified as the comma-separated pair
          consisting of 'Focus' and one of the following values:
          • 'prediction' — The one-step ahead prediction error between measured and predicted outputs
            is minimized during estimation. As a result, the estimation focuses on producing a good predictor
            model.
          • 'simulation' — The simulation error between measured and simulated outputs is minimized
            during estimation. As a result, the estimation focuses on making a good fit for simulation of model
            response with the current inputs.
          The Focus option can be interpreted as a weighting filter in the loss function. For more information,
          see “Loss Function and Model Quality Metrics”.
1-42
                                                                                           armaxOptions
Weighting prefilter applied to the loss function to be minimized during estimation. To understand the
effect of WeightingFilter on the loss function, see “Loss Function and Model Quality Metrics”.
   Passbands are expressed in rad/TimeUnit for time-domain data and in FrequencyUnit for
   frequency-domain data, where TimeUnit and FrequencyUnit are the time and frequency units
   of the estimation data.
• SISO filter — Specify a single-input-single-output (SISO) linear filter in one of the following ways:
       This option calculates the weighting function as a product of the filter and the input spectrum
       to estimate the transfer function.
Control whether to enforce stability of estimated model, specified as the comma-separated pair
consisting of 'EnforceStability' and either true or false.
This option is not available for multi-output models with a non-diagonal A polynomial array.
Data Types: logical
If EstimateCovariance is true, then use getcov to fetch the covariance matrix from the
estimated model.
Specify whether to display the estimation progress, specified as one of the following values:
• 'on' — Information on model structure and estimation results are displayed in a progress-viewer
  window.
                                                                                                   1-43
1   Functions
          Removal of offset from time-domain input data during estimation, specified as the comma-separated
          pair consisting of 'InputOffset' and one of the following:
          • A column vector of positive integers of length Nu, where Nu is the number of inputs.
          • [] — Indicates no offset.
          • Nu-by-Ne matrix — For multi-experiment data, specify InputOffset as an Nu-by-Ne matrix. Nu
            is the number of inputs, and Ne is the number of experiments.
Each entry specified by InputOffset is subtracted from the corresponding input data.
          Removal of offset from time-domain output data during estimation, specified as the comma-separated
          pair consisting of 'OutputOffset' and one of the following:
Each entry specified by OutputOffset is subtracted from the corresponding output data.
          Options for regularized estimation of model parameters. For more information on regularization, see
          “Regularized Estimates of Model Parameters”.
Specify a positive scalar to add the regularization term to the estimation cost.
                Default: 0
          • R — Weighting matrix.
                Specify a vector of nonnegative numbers or a square positive semi-definite matrix. The length
                must be equal to the number of free parameters of the model.
                For black-box models, using the default value is recommended. For structured and grey-box
                models, you can also specify a vector of np positive numbers such that each entry denotes the
                confidence in the value of the associated parameter.
                The default value of 1 implies a value of eye(npfree), where npfree is the number of free
                parameters.
1-44
                                                                                           armaxOptions
   Default: 1
• Nominal — The nominal value towards which the free parameters are pulled during estimation.
   The default value of zero implies that the parameter values are pulled towards zero. If you are
   refining a model, you can set the value to 'model' to pull the parameters towards the parameter
   values of the initial model. The initial parameter values must be finite for this setting to work.
Default: 0
Numerical search method used for iterative parameter estimation, specified as the comma-separated
pair consisting of 'SearchMethod' and one of the following:
• 'auto' — A combination of the line search algorithms, 'gn', 'lm', 'gna', and 'grad' methods
  is tried in sequence at each iteration. The first descent direction leading to a reduction in
  estimation cost is used.
• 'gn' — Subspace Gauss-Newton least squares search. Singular values of the Jacobian matrix less
  than GnPinvConstant*eps*max(size(J))*norm(J) are discarded when computing the
  search direction. J is the Jacobian matrix. The Hessian matrix is approximated as JTJ. If there is no
  improvement in this direction, the function tries the gradient direction.
• 'gna' — Adaptive subspace Gauss-Newton search. Eigenvalues less than gamma*max(sv) of the
  Hessian are ignored, where sv contains the singular values of the Hessian. The Gauss-Newton
  direction is computed in the remaining subspace. gamma has the initial value
  InitialGnaTolerance (see Advanced in 'SearchOptions' for more information). This value
  is increased by the factor LMStep each time the search fails to find a lower value of the criterion
  in fewer than five bisections. This value is decreased by the factor 2*LMStep each time a search is
  successful without any bisections.
• 'lm' — Levenberg-Marquardt least squares search, where the next parameter value is -pinv(H
  +d*I)*grad from the previous one. H is the Hessian, I is the identity matrix, and grad is the
  gradient. d is a number that is increased until a lower value of the criterion is found.
• 'grad' — Steepest descent least squares search.
• 'lsqnonlin' — Trust-region-reflective algorithm of lsqnonlin. Requires Optimization Toolbox
  software.
• 'fmincon' — Constrained nonlinear solvers. You can use the sequential quadratic programming
  (SQP) and trust-region-reflective algorithms of the fmincon solver. If you have Optimization
  Toolbox software, you can also use the interior-point and active-set algorithms of the fmincon
  solver. Specify the algorithm in the SearchOptions.Algorithm option. The fmincon algorithms
  may result in improved estimation results in the following scenarios:
   • Constrained minimization problems when there are bounds imposed on the model parameters.
   • Model structures where the loss function is a nonlinear or non smooth function of the
     parameters.
   • Multi-output model estimation. A determinant loss function is minimized by default for multi-
     output model estimation. fmincon algorithms are able to minimize such loss functions directly.
     The other search methods such as 'lm' and 'gn' minimize the determinant loss function by
     alternately estimating the noise variance and reducing the loss value for a given noise variance
     value. Hence, the fmincon algorithms can offer better efficiency and accuracy for multi-output
     model estimations.
                                                                                                  1-45
1   Functions
          Option set for the search algorithm, specified as the comma-separated pair consisting of
          'SearchOptions' and a search option set with fields that depend on the value of SearchMethod.
1-46
                                                                                     armaxOptions
                                                                                              1-47
1   Functions
1-48
                                                                                        armaxOptions
                                                                                               1-49
1   Functions
                                      • 'sqp' — Sequential
                                        quadratic programming
                                        algorithm. The algorithm
                                        satisfies bounds at all
                                        iterations, and it can recover
                                        from NaN or Inf results. It is
                                        not a large-scale algorithm.
                                        For more information, see
                                        “Large-Scale vs. Medium-
                                        Scale Algorithms”
                                        (Optimization Toolbox).
                                      • 'trust-region-
                                        reflective' — Subspace
                                        trust-region method based
                                        on the interior-reflective
                                        Newton method. It is a large-
                                        scale algorithm.
                                      • 'interior-point' —
                                        Large-scale algorithm that
                                        requires Optimization
                                        Toolbox software. The
                                        algorithm satisfies bounds at
                                        all iterations, and it can
                                        recover from NaN or Inf
                                        results.
                                      • 'active-set' — Requires
                                        Optimization Toolbox
                                        software. The algorithm can
                                        take large steps, which adds
                                        speed. It is not a large-scale
                                        algorithm.
1-50
                                                                                          armaxOptions
• ErrorThreshold — Specifies when to adjust the weight of large errors from quadratic to linear.
   Errors larger than ErrorThreshold times the estimated standard deviation have a linear weight
   in the loss function. The standard deviation is estimated robustly as the median of the absolute
   deviations from the median of the prediction errors and divided by 0.7. For more information on
   robust norm choices, see section 15.2 of [2].
   Default: 0
• MaxSize — Specifies the maximum number of elements in a segment when input-output data is
  split into segments.
   Default: 250000
• StabilityThreshold — Specifies thresholds for stability tests.
   • s — Specifies the location of the right-most pole to test the stability of continuous-time models.
     A model is considered stable when its right-most pole is to the left of s.
      Default: 0
   • z — Specifies the maximum distance of all poles from the origin to test stability of discrete-
     time models. A model is considered stable if all poles are within the distance z from the origin.
                                                                                                  1-51
1   Functions
                   Default: 1+sqrt(eps)
          • AutoInitThreshold — Specifies when to automatically estimate the initial condition.
                  yp, z − ymeas
                                > AutoInitThreshold
                  yp, e − ymeas
Default: 1.05
          Output Arguments
          opt — Options set for armax
          armaxOptions option set
Examples
opt = armaxOptions;
Create an option set for armax to use the 'simulation' Focus and to set the Display to 'on'.
opt = armaxOptions('Focus','simulation','Display','on');
          opt = armaxOptions;
          opt.Focus = 'simulation';
          opt.Display = 'on';
          Compatibility Considerations
          Renaming of Estimation and Analysis Options
          The names of some estimation and analysis options were changed in R2018a. Prior names still work.
          For details, see the R2018a release note “Renaming of Estimation and Analysis Options”.
1-52
                                                                                          armaxOptions
References
[1] Wills, Adrian, B. Ninness, and S. Gibson. “On Gradient-Based Search for Multivariable System
         Estimates”. Proceedings of the 16th IFAC World Congress, Prague, Czech Republic, July 3–8,
         2005. Oxford, UK: Elsevier Ltd., 2005.
[2] Ljung, L. System Identification: Theory for the User. Upper Saddle River, NJ: Prentice-Hall PTR,
        1999.
See Also
armax | idfilt
Topics
“Loss Function and Model Quality Metrics”
Introduced in R2012a
                                                                                                  1-53
1   Functions
          arOptions
          Option set for ar
          Syntax
          opt = arOptions
          opt = arOptions(Name,Value)
          Description
          opt = arOptions creates the default options set for ar.
          opt = arOptions(Name,Value) creates an option set with the options specified by one or more
          Name,Value pair arguments.
          Input Arguments
          Name-Value Pair Arguments
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Approach
Default: 'fb'
Window
          Window determines how the data outside the measured time interval (past and future values) is
          handled.
          • 'now' — No windowing.
          • 'prw' — Pre-windowing.
1-54
                                                                                              arOptions
• 'pow' — Post-windowing.
• 'ppw' — Pre- and post-windowing.
Default: 'now'
DataOffset
Specify DataOffset as a double scalar. For multiexperiment data, specify DataOffset as a vector
of length Ne, where Ne is the number of experiments. Each entry of the vector is subtracted from the
corresponding data.
MaxSize
Specifies the maximum number of elements in a segment when input/output data is split into
segments.
If larger matrices are needed, the software uses loops for calculations. Use this option to manage the
trade-off between memory management and program execution speed. The original data matrix must
be smaller than the matrix specified by MaxSize.
Default: 250000
Output Arguments
opt
Examples
opt = arOptions;
Create an options set for ar using the least squares algorithm for estimation. Set Window to 'ppw'.
opt = arOptions('Approach','ls','Window','ppw');
                                                                                                 1-55
1   Functions
          opt = arOptions;
          opt.Approach = 'ls';
          opt.Window = 'ppw';
          See Also
          ar
Introduced in R2012a
1-56
                                                                                                     arx
arx
Estimate parameters of ARX, ARIX, AR, or ARI model
Syntax
sys = arx(data,[na nb nk])
sys = arx(data,[na nb nk],Name,Value)
sys = arx(data,[na nb nk], ___ ,opt)
Description
sys = arx(data,[na nb nk]) estimates the parameters of an ARX on page 1-64 or an AR on
page 1-65 idpoly model sys using a least-squares method and the polynomial orders specified in
[na nb nk]. The model properties include covariances (parameter uncertainties) and goodness of fit
between the estimated and measured data.
sys = arx(data,[na nb nk],Name,Value) specifies additional options using one or more name-
value pair arguments. For instance, using the name-value pair argument 'IntegrateNoise',1
estimates an ARIX on page 1-65 or ARI structure model, which is useful for systems with
nonstationary disturbances.
sys = arx(data,[na nb nk], ___ ,opt) specifies estimation options using the option set opt.
Specify opt after all other input arguments.
Examples
ARX Model
Generate output data based on a specified ARX model and use the output data to estimate the model.
Specify a polynomial model sys0 with the ARX structure. The model includes an input delay of one
sample, expressed as a leading zero in the B polynomial.
A = [1 -1.5 0.7];
B = [0 1 0.5];
sys0 = idpoly(A,B);
Generate a measured input signal u that contains random binary noise and an error signal e that
contains normally distributed noise. With these signals, simulate the measured output signal y of
sys0.
u = iddata([],idinput(300,'rbs'));
e = iddata([],randn(300,1));
y = sim(sys0,[u e]);
Combine y and u into a single iddata object z. Estimate a new ARX model using z and the same
polynomial orders and input delay as the original model.
z = [y,u];
sys = arx(z,[2 2 1])
                                                                                                    1-57
1   Functions
          sys =
          Discrete-time ARX model: A(z)y(t) = B(z)u(t) + e(t)
            A(z) = 1 - 1.524 z^-1 + 0.7134 z^-2
          Parameterization:
             Polynomial orders:   na=2   nb=2   nk=1
             Number of free coefficients: 4
             Use "polydata", "getpvec", "getcov" for parameters and their uncertainties.
          Status:
          Estimated using ARX on time domain data "z".
          Fit to estimation data: 81.36% (prediction focus)
          FPE: 1.025, MSE: 0.9846
          The output displays the polynomial containing the estimated parameters alongside other estimation
          details. Under Status, Fit to estimation data shows that the estimated model has 1-step-
          ahead prediction accuracy above 80%.
AR Model
Estimate a time-series AR model using the arx function. An AR model has no measured input.
Load the data, which contains the time series z9 with noise.
load iddata9 z9
sys = arx(z9,4);
Examine the estimated A polynomial parameters and the fit of the estimate to the data.
param = sys.Report.Parameters.ParVector
param = 4×1
                 -0.7923
                 -0.4780
                 -0.0921
                  0.4698
fit = sys.Report.Fit.FitPercent
fit = 79.4835
ARIX Model
Estimate the parameters of an ARIX model. An ARIX model is an ARX model with integrated noise.
1-58
                                                                                                  arx
Specify a polynomial model sys0 with an ARX structure. The model includes an input delay of one
sample, expressed as a leading zero in B.
A = [1 -1.5 0.7];
B = [0 1 0.5];
sys0 = idpoly(A,B);
Simulate the output signal of sys0 using the random binary input signal u and the normally
distributed error signal e.
u = iddata([],idinput(300,'rbs'));
e = iddata([],randn(300,1));
y = sim(sys0,[u e]);
Integrate the output signal and store the result yi in the iddata object zi.
yi = iddata(cumsum(y.y),[]);
zi = [yi,u];
Estimate an ARIX model from zi. Set the name-value pair argument 'IntegrateNoise' to true.
sys = arx(zi,[2 2 1],'IntegrateNoise',true);
Predict the model output using 5-step prediction and compare the result with yi.
compare(zi,sys,5)
                                                                                             1-59
1   Functions
          Use arxRegul to determine regularization constants automatically and use the values for estimating
          an FIR model with an order of 50.
Use the returned lambda and R values for regularized ARX model estimation.
          opt = arxOptions;
          opt.Regularization.Lambda = lambda;
          opt.Regularization.R = R;
          sys = arx(eData,orders,opt);
          Input Arguments
          data — Estimation data
          iddata object | frd object | idfrd object
          Polynomial orders and delays for the model, specified as a 1-by-3 vector or vector of matrices [na nb
          nk]. The polynomial order is equal to the number of coefficients to estimate in that polynomial.
          For an AR or ARI time-series model, which has no input, set [na nb nk] to the scalar na. For an
          example, see “AR Model” on page 1-58.
You can also implement transport delays using the name-value pair argument 'IODelay'.
1-60
                                                                                                      arx
Example: arx(data,[2 1 1]) computes, from an iddata object, a second-order ARX model with
one input channel that has an input delay of one sample.
Estimation options for ARX model identification, specified as an arOptions option set. Options
specified by opt include the following:
• Initial condition handling — Use this option only for frequency-domain data. For time-domain data,
  the signals are shifted such that unmeasured signals are never required in the predictors.
• Input and output data offsets — Use these options to remove offsets from time-domain data during
  estimation.
• Regularization — Use this option to control the tradeoff between bias and variance errors during
  the estimation process.
For more information, see arxOptions. For an example, see “ARX Model with Regularization” on
page 1-59.
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Example: 'IntegrateNoise',true adds an integrator in the noise source s
Input delays expressed as integer multiples of the sample time, specified as the comma-separated
pair consisting of 'InputDelay' and one of the following:
• Nu-by-1 vector, where Nu is the number of inputs — Each entry is a numerical value representing
  the input delay for the corresponding input channel.
• Scalar value — Apply the same delay to all input channels.
Transport delays for each input-output pair, expressed as integer multiples of the sample time, and
specified as the comma-separated pair consisting of 'IODelay' and one of the following:
• Ny-by-Nu matrix, where Ny is the number of outputs and Nu is the number of inputs — Each entry
  is an integer value representing the transport delay for the corresponding input-output pair.
• Scalar value — Apply the same delay is applied to all input-output pairs. This approach is useful
  when the input-output delay parameter nk results in a large number of fixed leading zeros in the B
  polynomial. You can factor out max(nk-1,0) lags by moving those lags from nk into the
  'IODelay' value.
                                                                                                 1-61
1   Functions
                For instance, suppose that you have a system with two inputs, where the first input has a delay of
                three samples and the second input has a delay of six samples. Also suppose that the B
                polynomials for these inputs are order n. You can express these delays using the following:
          Addition of integrators in the noise channel, specified as the comma-separated pair consisting of
          'IntegrateNoise' and a logical vector of length Ny, where Ny is the number of outputs.
          Setting 'IntegrateNoise' to true for a particular output creates an ARIX on page 1-65 or ARI
          model for that channel. Noise integration is useful in cases where the disturbance is nonstationary.
          When using 'IntegrateNoise', you must also integrate the output channel data. For an example,
          see “ARIX Model” on page 1-58.
          Output Arguments
          sys — ARX model
          idpoly object
          ARX model that fits the estimation data, returned as a discrete-time idpoly object. This model is
          created using the specified model orders, delays, and estimation options.
          Information about the estimation results and options used is stored in the Report property of the
          model. Report has the following fields.
           Report         Description
           Field
           Status         Summary of the model status, which indicates whether the model was created by
                          construction or obtained by estimation.
           Method         Estimation command used.
           InitialCo Handling of initial conditions during model estimation, returned as one of the following
           ndition   values:
                          This field is especially useful to view how the initial conditions were handled when the
                          InitialCondition option in the estimation option set is 'auto'.
1-62
                                                                                                   arx
Report       Description
Field
Fit          Quantitative assessment of the estimation, returned as a structure. See “Loss Function
             and Model Quality Metrics” for more information on these quality metrics. The
             structure has the following fields:
             Field         Description
             FitPerce Normalized root mean squared error (NRMSE) measure of how well the
             nt       response of the model fits the estimation data, expressed as the
                      percentage fit = 100(1-NRMSE).
             LossFcn       Value of the loss function when the estimation completes.
             MSE           Mean squared error (MSE) measure of how well the response of the
                           model fits the estimation data.
             FPE           Final prediction error for the model.
             AIC           Raw Akaike Information Criteria (AIC) measure of model quality.
             AICc          Small sample-size corrected AIC.
             nAIC          Normalized AIC.
             BIC           Bayesian Information Criteria (BIC).
Parameter Estimated values of model parameters.
s
OptionsUs Option set used for estimation. If no custom options were configured, this is a set of
ed        default options. See arxOptions for more information.
RandState State of the random number stream at the start of estimation. Empty, [], if
          randomization was not used during estimation. For more information, see rng in the
          MATLAB documentation.
                                                                                               1-63
1   Functions
           Report          Description
           Field
           DataUsed        Attributes of the data used for estimation, returned as a structure with the following
                           fields:
                           Field          Description
                           Name           Name of the data set.
                           Type           Data type.
                           Length         Number of data samples.
                           Ts             Sample time.
                           InterSam Input intersample behavior, returned as one of the following values:
                           ple
                                    • 'zoh' — Zero-order hold maintains a piecewise-constant input signal
                                       between samples.
                                          • 'foh' — First-order hold maintains a piecewise-linear input signal
                                            between samples.
                                          • 'bl' — Band-limited behavior specifies that the continuous-time input
                                            signal has zero power above the Nyquist frequency.
                           InputOff Offset removed from time-domain input data during estimation. For
                           set      nonlinear models, it is [].
                           OutputOf Offset removed from time-domain output data during estimation. For
                           fset     nonlinear models, it is [].
          More About
          ARX Structure
          The ARX model name stands for Autoregressive with Extra Input, because, unlike the AR model, the
          ARX model includes an input term. ARX is also known as Autoregressive with Exogenous Variables,
          where the exogenous variable is the input term. The ARX model structure is given by the following
          equation:
The parameters na and nb are the orders of the ARX model, and nk is the delay.
1-64
                                                                                                      arx
                                    −nb + 1
     B(q) = b1 + b2q−1 + … + bnbq
ARIX Model
The ARIX (Autoregressive Integrated with Extra Input) model is an ARX model with an integrator in
the noise channel. The ARIX model structure is given by the following equation:
                                     1
     A(q)y(t) = B(q)u(t − nk) +           e(t)
                                  1 − q−1
           1
where           is the integrator in the noise channel, e(t).
        1 − q−1
AR Time-Series Models
For time-series data that contains no inputs, one output, and the A polynomial order na, the model
has an AR structure of order na.
A(q)y(t) = e(t)
ARI Model
The ARI (Autoregressive Integrated) model is an AR model with an integrator in the noise channel.
The ARI model structure is given by the following equation:
                     1
     A(q)y(t) =           e(t)
                  1 − q−1
For multiple-input, single-output systems (MISO) with nu inputs, nb and nk are row vectors where the
ith element corresponds to the order and delay associated with the ith input in column vector u(t).
Similarly, the coefficients of the B polynomial are row vectors. The ARX MISO structure is then given
by the following equation:
For multiple-input, multiple-output systems, na, nb, and nk contain one row for each output signal.
In the multiple-output case, arx minimizes the trace of the prediction error covariance matrix, or the
norm
                                                                                                 1-65
1   Functions
                N
                ∑     eT (t)e(t)
                t=1
          To transform this norm to an arbitrary quadratic norm using a weighting matrix Lambda
                N
                ∑     eT (t)Λ−1e(t)
                t=1
          opt = arxOptions('OutputWeight',inv(lambda))
          m = arx(data,orders,opt)
Initial Conditions
          For time-domain data, the signals are shifted such that unmeasured signals are never required in the
          predictors. Therefore, there is no need to estimate initial conditions.
          For frequency-domain data, it might be necessary to adjust the data by initial conditions that support
          circular convolution.
Set the 'InitialCondition' estimation option (see arxOptions) to one of the following values:
          • 'zero' — No adjustment
          • 'estimate' — Perform adjustment to the data by initial conditions that support circular
            convolution
          • 'auto' — Automatically choose 'zero' or 'estimate' based on the data
          Algorithms
          QR factorization solves the overdetermined set of linear equations that constitutes the least-squares
          estimation problem.
          Without regularization, the ARX model parameters vector θ is estimated by solving the normal
          equation
JT J θ = JT y
                      −1 T
          θ = JT J       J y
                             −1 T
          θ = J T J + λR           J y
          where λ and R are the regularization constants. For more information on the regularization constants,
          see arxOptions.
          When the regression matrix is larger than the MaxSize specified in arxOptions, the data is
          segmented and QR factorization is performed iteratively on the data segments.
1-66
                                                                                  arx
See Also
ar | armax | arxOptions | arxRegul | arxstruc | iddata | idfrd | idinput | iv4
Topics
“What Are Polynomial Models?”
“What Are Time Series Models?”
“Estimate Polynomial Models at the Command Line”
“Regularized Estimates of Model Parameters”
“Estimating Models Using Frequency-Domain Data”
                                                                                 1-67
1   Functions
          arxOptions
          Option set for arx
          Syntax
          opt = arxOptions
          opt = arxOptions(Name,Value)
          Description
          opt = arxOptions creates the default options set for arx.
          opt = arxOptions(Name,Value) creates an option set with the options specified by one or more
          Name,Value pair arguments.
          Input Arguments
          Name-Value Pair Arguments
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
          Handling of initial conditions during estimation using frequency-domain data, specified as the
          comma-separated pair consisting of 'InitialCondition' and one of the following values:
          Error to be minimized in the loss function during estimation, specified as the comma-separated pair
          consisting of 'Focus' and one of the following values:
          • 'prediction' — The one-step ahead prediction error between measured and predicted outputs
            is minimized during estimation. As a result, the estimation focuses on producing a good predictor
            model.
          • 'simulation' — The simulation error between measured and simulated outputs is minimized
            during estimation. As a result, the estimation focuses on making a good fit for simulation of model
            response with the current inputs.
          The Focus option can be interpreted as a weighting filter in the loss function. For more information,
          see “Loss Function and Model Quality Metrics”.
1-68
                                                                                               arxOptions
Weighting prefilter applied to the loss function to be minimized during estimation. To understand the
effect of WeightingFilter on the loss function, see “Loss Function and Model Quality Metrics”.
   Passbands are expressed in rad/TimeUnit for time-domain data and in FrequencyUnit for
   frequency-domain data, where TimeUnit and FrequencyUnit are the time and frequency units
   of the estimation data.
• SISO filter — Specify a single-input-single-output (SISO) linear filter in one of the following ways:
       This option calculates the weighting function as a product of the filter and the input spectrum
       to estimate the transfer function.
• Weighting vector — Applicable for frequency-domain data only. Specify a column vector of
  weights. This vector must have the same length as the frequency vector of the data set,
  Data.Frequency. Each input and output response in the data is multiplied by the corresponding
  weight at that frequency.
Control whether to enforce stability of estimated model, specified as the comma-separated pair
consisting of 'EnforceStability' and either true or false.
This option is not available for multi-output models with a non-diagonal A polynomial array.
Data Types: logical
If EstimateCovariance is true, then use getcov to fetch the covariance matrix from the
estimated model.
                                                                                                   1-69
1   Functions
Specify whether to display the estimation progress, specified as one of the following values:
          • 'on' — Information on model structure and estimation results are displayed in a progress-viewer
            window.
          • 'off' — No progress or results information is displayed.
          Removal of offset from time-domain input data during estimation, specified as the comma-separated
          pair consisting of 'InputOffset' and one of the following:
          • A column vector of positive integers of length Nu, where Nu is the number of inputs.
          • [] — Indicates no offset.
          • Nu-by-Ne matrix — For multi-experiment data, specify InputOffset as an Nu-by-Ne matrix. Nu
            is the number of inputs, and Ne is the number of experiments.
Each entry specified by InputOffset is subtracted from the corresponding input data.
          Removal of offset from time-domain output data during estimation, specified as the comma-separated
          pair consisting of 'OutputOffset' and one of the following:
Each entry specified by OutputOffset is subtracted from the corresponding output data.
Weight of prediction errors in multi-output estimation, specified as one of the following values:
          • Positive semidefinite, symmetric matrix (W). The software minimizes the trace of the weighted
            prediction error matrix trace(E'*E*W/N) where:
                • E is the matrix of prediction errors, with one column for each output, and W is the positive
                  semidefinite, symmetric matrix of size equal to the number of outputs. Use W to specify the
                  relative importance of outputs in multiple-output models, or the reliability of corresponding
                  data.
                • N is the number of data samples.
          • [] — No weighting is used. Specifying as [] is the same as eye(Ny), where Ny is the number of
            outputs.
1-70
                                                                                              arxOptions
Options for regularized estimation of model parameters, specified as a structure with the following
fields:
Specify a positive scalar to add the regularization term to the estimation cost.
   Default: 0
• R — Weighting matrix.
   Specify a positive scalar or a positive definite matrix. The length of the matrix must be equal to
   the number of free parameters (np) of the model. For ARX model, np = sum(sum([na nb]).
   Default: 1
• Nominal — This option is not used for ARX models.
Default: 0
• MaxSize — Specifies the maximum number of elements in a segment when input-output data is
  split into segments.
   Default: 250000
• StabilityThreshold — Specifies thresholds for stability tests.
   • s — Specifies the location of the right-most pole to test the stability of continuous-time models.
     A model is considered stable when its right-most pole is to the left of s.
      Default: 0
   • z — Specifies the maximum distance of all poles from the origin to test stability of discrete-
     time models. A model is considered stable if all poles are within the distance z from the origin.
Default: 1+sqrt(eps)
Output Arguments
opt — Options set for arx
arxOptions option set
                                                                                                   1-71
1   Functions
Examples
opt = arxOptions;
Create an options set for arx using zero initial conditions for estimation. Set Display to 'on'.
opt = arxOptions('InitialCondition','zero','Display','on');
          opt = arxOptions;
          opt.InitialCondition = 'zero';
          opt.Display = 'on';
          Compatibility Considerations
          Renaming of Estimation and Analysis Options
          The names of some estimation and analysis options were changed in R2018a. Prior names still work.
          For details, see the R2018a release note “Renaming of Estimation and Analysis Options”.
          See Also
          arx | arxRegul | idfilt
          Topics
          “Loss Function and Model Quality Metrics”
Introduced in R2012a
1-72
                                                                                             arxRegul
arxRegul
Determine regularization constants for ARX model estimation
Syntax
[lambda,R]    =   arxRegul(data,orders)
[lambda,R]    =   arxRegul(data,orders,options)
[lambda,R]    =   arxRegul(data,orders,Name,Value)
[lambda,R]    =   arxRegul(data,orders,options,Name,Value)
Description
[lambda,R] = arxRegul(data,orders) returns the regularization constants used for ARX model
estimation. Use the regularization constants in arxOptions to configure the regularization options
for ARX model estimation.
Examples
Determine Regularization Constants for ARX Model Estimation Using Default Kernel
load iddata1 z1;
orders = [10 10 1];
[Lambda,R] = arxRegul(z1,orders);
The ARX model is estimated using the default regularization kernel TC.
Specify 'DC' as the regularization kernel and obtain a regularized ARX model of order [|10 10 1|].
load iddata1 z1;
orders = [10 10 1];
                                                                                                1-73
1   Functions
          option = arxRegulOptions('RegularizationKernel','DC');
          [Lambda,R] = arxRegul(z1,orders,option);
          Specify to include a noise source integrator in the noise component of the model.
          load iddata1 z1;
          orders = [10 10 1];
          [Lambda,R] = arxRegul(z1,orders,'IntegrateNoise',true);
          Specify the regularization kernel and include a noise source integrator in the noise component of the
          model.
          load iddata1 z1;
          orders = [10 10 1];
          opt = arxRegulOptions('RegularizationKernel','DC');
          [Lambda,R] = arxRegul(z1,orders,opt,'IntegrateNoise',true);
          Input Arguments
          data — Estimation data
          iddata object
          ARX model orders [na nb nc], specified as a matrix of nonnegative integers. See the arx reference
          page for more information on model orders.
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
1-74
                                                                                                 arxRegul
Input delay, specified as a positive, nonzero numeric value representing the number of samples.
Example: [Lambda, R] = arxRegul(z1,orders,'InputDelay',10);
Data Types: double
Noise source integrator, specified as a logical. Specifies whether the noise source e(t) should
contain an integrator. The default is false, indicating the noise integrator is off. To turn it on, change
the value to true.
Example: [Lambda, R] = arxRegul(z1,orders,'IntegrateNoise',true);
Data Types: logical
Output Arguments
lambda — Constant that determines bias versus variance trade-off
positive scalar
Constant that determines the bias versus variance trade-off, returned as a positive scalar.
R — Weighting matrix
vector of nonnegative numbers | square positive semi-definite matrix
Algorithms
Without regularization, the ARX model parameters vector θ is estimated by solving the normal
equation
JT J θ = JT y
           −1 T
θ = JT J     J y
                  −1 T
θ = J T J + λR      J y
where λ and R are the regularization constants. For more information on the regularization constants,
see arxOptions.
                                                                                                    1-75
1   Functions
          References
          [1] T. Chen, H. Ohlsson, and L. Ljung. “On the Estimation of Transfer Functions, Regularizations and
                   Gaussian Processes - Revisited”, Automatica, Volume 48, August 2012.
          See Also
          arx | arxOptions | arxRegulOptions
          Topics
          “Estimate Regularized ARX Model Using System Identification App”
          “Regularized Estimates of Model Parameters”
Introduced in R2013b
1-76
                                                                                    arxRegulOptions
arxRegulOptions
Option set for arxRegul
Syntax
opt = arxRegulOptions
opt = arxRegulOptions(Name,Value)
Description
opt = arxRegulOptions creates a default option set for arxRegul.
opt = arxRegulOptions(Name,Value) creates an options set with the options specified by one or
more name-value pair arguments.
Examples
opt = arxRegulOptions;
opt = arxRegulOptions('RegularizationKernel','DC');
Input Arguments
Name-Value Pair Arguments
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Example: option = arxRegulOptions('RegularizationKernel', 'DC') specifies 'DC' as
the regularization kernel.
                                                                                             1-77
1   Functions
          The specified kernel is used for regularized estimation of impulse response for all input-output
          channels. Regularization reduces variance of estimated model coefficients and produces a smoother
          response by trading variance for bias.
          Offset levels present in the input signals of time-domain estimation data, specified as one of the
          following:
          • An Nu-element column vector, where Nu is the number of inputs. For multi-experiment data,
            specify a Nu-by-Ne matrix, where Ne is the number of experiments. The offset value
            InputOffset(i,j) is subtracted from the ith input signal of the jth experiment.
          • [] — No offsets.
Output signal offset level of time-domain estimation data, specified as one of the following:
          • An Ny-element column vector, where Ny is the number of outputs. For multi-experiment data,
            specify a Ny-by-Ne matrix, where Ne is the number of experiments. The offset value
            OputOffset(i,j) is subtracted from the ith output signal of the jth experiment.
          • [] — No offsets.
          The specified values are subtracted from the output signals before using them for estimation.
          Data Types: double
Advanced options for regularized estimation, specified as a structure with the following fields:
          • MaxSize — Maximum allowable size of Jacobian matrices formed during estimation, specified as a
            large positive number.
                Default: 250e3
          • SearchMethod — Search method for estimating regularization parameters, specified as one of
            the following values:
1-78
                                                                                       arxRegulOptions
Default: 'fmincon'
Output Arguments
opt — Regularization options
arxRegulOptions options set
Compatibility Considerations
Renaming of Estimation and Analysis Options
The names of some estimation and analysis options were changed in R2018a. Prior names still work.
For details, see the R2018a release note “Renaming of Estimation and Analysis Options”.
References
[1] T. Chen, H. Ohlsson, and L. Ljung. “On the Estimation of Transfer Functions, Regularizations and
         Gaussian Processes - Revisited”, Automatica, Volume 48, August 2012.
See Also
arxRegul
Topics
“Regularized Estimates of Model Parameters”
Introduced in R2014a
                                                                                                1-79
1   Functions
          arxstruc
          Compute loss functions for single-output ARX models
          Syntax
          V = arxstruc(ze,zv,NN)
          Arguments
          ze
                Estimation data set can be iddata or idfrd object.
          zv
                Validation data set can be iddata or idfrd object.
          NN
                Matrix defines the number of different ARX-model structures. Each row of NN is of the form:
                nn = [na nb nk]
Description
          Note Use arxstruc for single-output systems only. arxstruc supports both single-input and
          multiple-input systems.
          V = arxstruc(ze,zv,NN) returns V, which contains the loss functions in its first row. The
          remaining rows of V contain the transpose of NN, so that the orders and delays are given just below
          the corresponding loss functions. The last column of V contains the number of data points in ze.
          The output argument V is best analyzed using selstruc. The selection of a suitable model structure
          based on the information in v is normally done using selstruc.
Examples
Simulate the model output using the defined input and error signals.
1-80
                                                                                             arxstruc
y = sim(m0,[u e]);
z = [y,u];
Generate model-order combinations for estimation. Specify a delay of 1 for all models, and a model
order range between 1 and 5 for na and nb.
NN = struc(1:5,1:5,1);
Estimate ARX models and compute the loss function for each model order combination. The input
data is split into estimation and validation data sets.
V = arxstruc(z(1:200),z(201:400),NN);
Select the model order with the best fit to the validation data.
order = selstruc(V,0);
• na = 2:4
• nb = 2:5 for the first input, and 1 or 4 for the second input.
• nk = 1:4 for the first input, and 0 for the second input.
NN = struc(2:4,2:5,[1 4],1:4,0);
Select the model order with the best fit to the validation data.
order = selstruc(V,0);
Tips
Each of ze and zv is an iddata object containing output-input data. Frequency-domain data and
idfrd objects are also supported. Models for each of the model structures defined by NN are
                                                                                                1-81
1   Functions
          estimated using the data set ze. The loss functions (normalized sum of squared prediction errors) are
          then computed for these models when applied to the validation data set zv. The data sets ze and zv
          need not be of equal size. They could, however, be the same sets, in which case the computation is
          faster.
          See Also
          arx | idpoly | ivstruc | selstruc | struc
1-82
                                                                                                balred
balred
Model order reduction
Syntax
rsys = balred(sys,ORDERS)
rsys = balred(sys,ORDERS,BALDATA)
rsys = balred( ___ ,opts)
Description
rsys = balred(sys,ORDERS) computes a reduced-order approximation rsys of the LTI model
sys. The desired order (number of states) for rsys is specified by ORDERS. You can try multiple
orders at once by setting ORDERS to a vector of integers, in which case rsys is a vector of reduced-
order models. balred uses implicit balancing techniques to compute the reduced- order
approximation rsys. Use hsvd to plot the Hankel singular values and pick an adequate
approximation order. States with relatively small Hankel singular values can be safely discarded.
When sys has unstable poles, it is first decomposed into its stable and unstable parts using stabsep,
and only the stable part is approximated. Use balredOptions to specify additional options for the
stable/unstable decomposition.
This command requires Control System Toolbox™ license. sys can only be an identified state-space
model (idss). The reduced-order model is also an idss model.
rsys = balred( ___ ,opts) computes the model reduction using options that you specify using
balredOptions. Options include offset and tolerance options for computing the stable-unstable
decompositions. There also options for emphasizing particular time or frequency intervals. See
balredOptions for details.
Note The order of the approximate model is always at least the number of unstable poles and at
most the minimal order of the original model (number NNZ of nonzero Hankel singular values using
an eps-level relative threshold)
Examples
                                                                                                 1-83
1   Functions
                                   −6
          Exclude the pole at s = 10 from the stable term of the stable/unstable decomposition. To do so, set
          the Offset option of balredOptions to a value larger than the pole you want to exclude.
opt = balredOptions('Offset',.001,'StateElimMethod','Truncate');
rsys = balred(sys,2,opt);
bodeplot(sys,rsys,'r--')
Reduce a high-order model with a focus on the dynamics in a particular frequency range.
          load('highOrderModel.mat','G')
          bodeplot(G)
1-84
                                                                                               balred
G is a 48th-order model with several large peak regions around 5.2 rad/s, 13.5 rad/s, and 24.5 rad/s,
and smaller peaks scattered across many frequencies. Suppose that for your application you are only
interested in the dynamics near the second large peak, between 10 rad/s and 22 rad/s. Focus the
model reduction on the region of interest to obtain a good match with a low-order approximation. Use
balredOptions to specify the frequency interval for balred.
bopt = balredOptions('StateElimMethod','Truncate','FreqIntervals',[10,22]);
GLim10 = balred(G,10,bopt);
GLim18 = balred(G,18,bopt);
Examine the frequency responses of the reduced-order models. Also, examine the difference between
those responses and the original response (the absolute error).
subplot(2,1,1);
bodemag(G,GLim10,GLim18,logspace(0.5,1.5,100));
title('Bode Magnitude Plot')
legend('Original','Order 10','Order 18');
subplot(2,1,2);
bodemag(G-GLim10,G-GLim18,logspace(0.5,1.5,100));
title('Absolute Error Plot')
legend('Order 10','Order 18');
                                                                                                1-85
1   Functions
          With the frequency-limited energy computation, even the 10th-order approximation is quite good in
          the region of interest.
          Alternative Functionality
          App
Model Reducer
          Compatibility Considerations
          MatchDC option honored when specified frequency or time intervals exclude DC
          Behavior changed in R2017b
          When you use balred for model reduction, you can use balredOptions to restrict the computation
          to specified frequency or time intervals. If the StateElimMethod option of balredOptions is set to
          'MatchDC' (the default value), then balred attempts to match the DC gain of the original and
          reduced models, even if the specified intervals exclude DC (frequency = 0 or time = Inf).
1-86
                                                                                                 balred
Prior to R2017b, if you specified time or frequency intervals that excluded DC, balred did not
attempt to match the DC gain of the original and reduced models, even if StateElimMethod =
'MatchDC'.
References
[1] Varga, A., "Balancing-Free Square-Root Algorithm for Computing Singular Perturbation
        Approximations," Proc. of 30th IEEE CDC, Brighton, UK (1991), pp. 1062-1065.
See Also
Functions
balredOptions | hsvd
Apps
Model Reducer
Topics
“Balanced Truncation Model Reduction” (Control System Toolbox)
“Model Reduction Basics” (Control System Toolbox)
                                                                                                 1-87
1   Functions
          bandwidth
          Frequency response bandwidth
          Syntax
          fb = bandwidth(sys)
          fb = bandwidth(sys,dbdrop)
          Description
          fb = bandwidth(sys) returns the bandwidth of the SISO dynamic system model sys. The
          bandwidth is the first frequency where the gain drops below 70.79% (-3 dB) of its DC value. The
          bandwidth is expressed in rad/TimeUnit, where TimeUnit is the TimeUnit property of sys.
Examples
fb = 0.9976
This result shows that the gain of sys drops to 3 dB below its DC value at around 1 rad/s.
          Compute the frequency at which the gain of a system drops to 3.5 dB below its DC value. Create a
          state-space model.
          A =   [-2,-1;1,0];
          B =   [1;0];
          C =   [1,2];
          D =   1;
          sys   = ss(A,B,C,D);
          dbdrop = -3.5;
          fb = bandwidth(sys,dbdrop)
fb = 0.8348
1-88
                                                                                            bandwidth
Find the bandwidth of each entry in a 5-by-1 array of transfer function models. Use a for loop to
create the array, and confirm its dimensions.
sys = tf(zeros(1,1,5));
s = tf('s');
for m = 1:5
    sys(:,:,m) = m/(s^2+s+m);
end
size(sys)
fb = bandwidth(sys)
fb = 5×1
     1.2712
     1.9991
     2.5298
     2.9678
     3.3493
bandwidth returns an array in which each entry is the bandwidth of the corresponding entry in sys.
For instance, the bandwidth of sys(:,:,2) is fb(2).
Input Arguments
sys — Dynamic system
dynamic system model | model array
Dynamic system, specified as a SISO dynamic system model or an array of SISO dynamic system
models. Dynamic systems that you can use include:
If sys is an array of models, bandwidth returns an array of the same size, where each entry is the
bandwidth of the corresponding model in sys. For more information on model arrays, see “Model
Arrays” (Control System Toolbox).
                                                                                                    1-89
1   Functions
          Output Arguments
          fb — Frequency response bandwidth
          scalar | array
          See Also
          bodeplot | dcgain | issiso
1-90
                                                                                                   bj
bj
Estimate Box-Jenkins polynomial model using time domain data
Syntax
sys    =   bj(data, [nb nc nd nf nk])
sys    =   bj(data,[nb nc nd nf nk], Name,Value)
sys    =   bj(data, init_sys)
sys    =   bj(data, ___ , opt)
Description
sys = bj(data, [nb nc nd nf nk]) estimates a Box-Jenkins polynomial model, sys, using the
time-domain data, data. [nb nc nd nf nk] define the orders of the polynomials used for
estimation.
sys = bj(data, init_sys) estimates a Box-Jenkins polynomial using the polynomial model
init_sys to configure the initial parameterization of sys.
sys = bj(data, ___ , opt) estimates a Box-Jenkins polynomial using the option set, opt, to
specify estimation behavior.
Input Arguments
data
Estimation data.
data is an iddata object that contains time-domain input and output signal values.
Default:
[nb nc nd nf nk]
A vector of matrices containing the orders and delays of the Box-Jenkins model. Matrices must
contain nonnegative integers.
                                                                                                1-91
1   Functions
opt
Estimation options.
          • estimation objective
          • initial conditions
          • numerical search method to be used in estimation
init_sys
          init_sys must be an idpoly model with the Box-Jenkins structure that has only B, C, D and F
          polynomials active. bj uses the parameters and constraints defined in init_sys as the initial guess
          for estimating sys.
          Use the Structure property of init_sys to configure initial guesses and constraints for B(q), F(q),
          C(q) and D(q).
          To specify an initial guess for, say, the C(q) term of init_sys, set init_sys.Structure.C.Value
          as the initial guess.
You can similarly specify the initial guess and constraints for the other polynomials.
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
InputDelay
          Input delays. InputDelay is a numeric vector specifying a time delay for each input channel. Specify
          input delays in integer multiples of the sample time Ts. For example, InputDelay = 3 means a
          delay of three sampling periods.
          For a system with Nu inputs, set InputDelay to an Nu-by-1 vector, where each entry is a numerical
          value representing the input delay for the corresponding input channel. You can also set InputDelay
          to a scalar value to apply the same delay to all channels.
1-92
                                                                                                       bj
IODelay
Transport delays. IODelay is a numeric array specifying a separate transport delay for each input/
output pair.
Specify transport delays as integers denoting delay of a multiple of the sample time Ts.
For a MIMO system with Ny outputs and Nu inputs, set IODelay to a Ny-by-Nu array, where each
entry is a numerical value representing the transport delay for the corresponding input/output pair.
You can also set IODelay to a scalar value to apply the same delay to all input/output pairs.
IntegrateNoise
            1
Where,           is the integrator in the noise channel,e(t).
         1 − q−1
Output Arguments
sys
BJ model that fits the estimation data, returned as a discrete-time idpoly object. This model is
created using the specified model orders, delays, and estimation options.
Information about the estimation results and options used is stored in the Report property of the
model. Report has the following fields:
Report           Description
Field
Status           Summary of the model status, which indicates whether the model was created by
                 construction or obtained by estimation.
Method           Estimation command used.
                                                                                                   1-93
1   Functions
           Report       Description
           Field
           InitialCo Handling of initial conditions during model estimation, returned as one of the following
           ndition   values:
                        This field is especially useful to view how the initial conditions were handled when the
                        InitialCondition option in the estimation option set is 'auto'.
           Fit          Quantitative assessment of the estimation, returned as a structure. See “Loss Function
                        and Model Quality Metrics” for more information on these quality metrics. The
                        structure has the following fields:
                        Field         Description
                        FitPerce Normalized root mean squared error (NRMSE) measure of how well the
                        nt       response of the model fits the estimation data, expressed as the
                                 percentage fit = 100(1-NRMSE).
                        LossFcn       Value of the loss function when the estimation completes.
                        MSE           Mean squared error (MSE) measure of how well the response of the
                                      model fits the estimation data.
                        FPE           Final prediction error for the model.
                        AIC           Raw Akaike Information Criteria (AIC) measure of model quality.
                        AICc          Small sample-size corrected AIC.
                        nAIC          Normalized AIC.
                        BIC           Bayesian Information Criteria (BIC).
           Parameter Estimated values of model parameters.
           s
           OptionsUs Option set used for estimation. If no custom options were configured, this is a set of
           ed        default options. See bjOptions for more information.
           RandState State of the random number stream at the start of estimation. Empty, [], if
                     randomization was not used during estimation. For more information, see rng in the
                     MATLAB documentation.
1-94
                                                                                                      bj
Report       Description
Field
DataUsed     Attributes of the data used for estimation, returned as a structure with the following
             fields:
             Field         Description
             Name          Name of the data set.
             Type          Data type.
             Length        Number of data samples.
             Ts            Sample time.
             InterSam Input intersample behavior, returned as one of the following values:
             ple
                      • 'zoh' — Zero-order hold maintains a piecewise-constant input signal
                         between samples.
                           • 'foh' — First-order hold maintains a piecewise-linear input signal
                             between samples.
                           • 'bl' — Band-limited behavior specifies that the continuous-time input
                             signal has zero power above the Nyquist frequency.
             InputOff Offset removed from time-domain input data during estimation. For
             set      nonlinear models, it is [].
             OutputOf Offset removed from time-domain output data during estimation. For
             fset     nonlinear models, it is [].
Terminati Termination conditions for the iterative search used for prediction error minimization.
on        Structure with the following fields:
             Field         Description
             WhyStop       Reason for terminating the numerical search.
             Iteratio Number of search iterations performed by the estimation algorithm.
             ns
             FirstOrd ∞-norm of the gradient search vector when the search algorithm
             erOptima terminates.
             lity
             FcnCount Number of times the objective function was called.
             UpdateNo Norm of the gradient search vector in the last iteration. Omitted when the
             rm       search method is 'lsqnonlin' or 'fmincon'.
             LastImpr Criterion improvement in the last iteration, expressed as a percentage.
             ovement Omitted when the search method is 'lsqnonlin' or 'fmincon'.
             Algorith Algorithm used by 'lsqnonlin' or 'fmincon' search method. Omitted
             m        when other search methods are used.
             For estimation methods that do not require numerical search optimization, the
             Termination field is omitted.
                                                                                                  1-95
1   Functions
Examples
Estimate the parameters of a single-input, single-output Box-Jenkins model from measured data.
          sys is a discrete-time idpoly model with estimated coefficients. The order of sys is as described by
          nb, nc, nd, nf, and nk.
          Use getpvec to obtain the estimated parameters and getcov to obtain the covariance associated
          with the estimated parameters.
Estimate the parameters of a multi-input, single-output Box-Jenkins model from measured data.
          load iddata8
          nb = [2 1 1];
          nc = 1;
          nd = 1;
          nf = [2 1 2];
          nk = [5 10 15];
          sys = bj(z8,[nb nc nd nf nk]);
          sys estimates the parameters of a model with three inputs and one output. Each of the inputs has a
          delay associated with it.
Load data.
m1 = bj(m0simdata(1:150),[15 15 15 15 1]);
1-96
                                                                                                    bj
opt = bjOptions;
opt.Regularization.Lambda = 1;
m2 = bj(m0simdata(1:150),[15 15 15 15 1],opt);
Obtain a lower-order BJ model by converting a regularized ARX model followed by order reduction.
opt1 = arxOptions;
[L,R] = arxRegul(m0simdata(1:150),[30 30 1]);
opt1.Regularization.Lambda = L;
opt1.Regularization.R = R;
m0 = arx(m0simdata(1:150),[30 30 1],opt1);
mr = idpoly(balred(idss(m0),7));
opt2 = compareOptions('InitialCondition','z');
compare(m0simdata(150:end),m1,m2,mr,opt2);
Estimate the parameters of a single-input, single-output Box-Jenkins model while configuring some
estimation options.
                                                                                               1-97
1   Functions
          B = [0 1 0.5];
          C = [1 -1 0.2];
          D = [1 1.5 0.7];
          F = [1 -1.5 0.7];
          sys0 = idpoly(1,B,C,D,F,0.1);
          e = iddata([],randn(200,1));
          u = iddata([],idinput(200));
          y = sim(sys0,[u e]);
          data = [y u];
          Create an estimation option set to refine the parameters of the estimated model.
          opt = bjOptions;
          opt.Display = 'on';
          opt.SearchOptions.MaxIterations = 50;
          opt is an estimation option set that configures the estimation to iterate 50 times at most and display
          the estimation progress.
sys is estimated using init_sys for the initial parameterization for the polynomial coefficients.
data contains the measured data for two inputs and two outputs.
1-98
                                                                                                       bj
 nk = [1 1; 0 0];
 sys = bj(data,[nb nc nd nf nk]);
The polynomial order coefficients contain one row for each output.
sys is a discrete-time idpoly model with two inputs and two outputs.
More About
Box-Jenkins Model Structure
Alternatives
To estimate a continuous-time model, use:
References
[1] Ljung, L. System Identification: Theory for the User, Upper Saddle River, NJ, Prentice-Hall PTR,
        1999.
Extended Capabilities
Automatic Parallel Support
Accelerate code by automatically running computation in parallel using Parallel Computing Toolbox™.
Parallel computing support is available for estimation using the lsqnonlin search method (requires
Optimization Toolbox). To enable parallel computing, use bjOptions, set SearchMethod to
'lsqnonlin', and set SearchOptions.Advanced.UseParallel to true.
For example:
                                                                                                  1-99
1   Functions
          opt = bjOptions;
          opt.SearchMethod = 'lsqnonlin';
          opt.SearchOptions.Advanced.UseParallel = true;
          See Also
          armax | arx | bjOptions | compare | d2c | forecast | iddata | idpoly | iv4 | oe | polyest |
          sim | ssest | tfest
          Topics
          “Regularized Estimates of Model Parameters”
1-100
                                                                                              bjOptions
bjOptions
Option set for bj
Syntax
opt = bjOptions
opt = bjOptions(Name,Value)
Description
opt = bjOptions creates the default options set for bj.
opt = bjOptions(Name,Value) creates an option set with the options specified by one or more
Name,Value pair arguments.
Input Arguments
Name-Value Pair Arguments
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Handling of initial conditions during estimation, specified as one of the following values:
Error to be minimized in the loss function during estimation, specified as the comma-separated pair
consisting of 'Focus' and one of the following values:
• 'prediction' — The one-step ahead prediction error between measured and predicted outputs
  is minimized during estimation. As a result, the estimation focuses on producing a good predictor
  model.
• 'simulation' — The simulation error between measured and simulated outputs is minimized
  during estimation. As a result, the estimation focuses on making a good fit for simulation of model
  response with the current inputs.
The Focus option can be interpreted as a weighting filter in the loss function. For more information,
see “Loss Function and Model Quality Metrics”.
                                                                                                1-101
1   Functions
          Weighting prefilter applied to the loss function to be minimized during estimation. To understand the
          effect of WeightingFilter on the loss function, see “Loss Function and Model Quality Metrics”.
                Passbands are expressed in rad/TimeUnit for time-domain data and in FrequencyUnit for
                frequency-domain data, where TimeUnit and FrequencyUnit are the time and frequency units
                of the estimation data.
          • SISO filter — Specify a single-input-single-output (SISO) linear filter in one of the following ways:
                   This option calculates the weighting function as a product of the filter and the input spectrum
                   to estimate the transfer function.
          Control whether to enforce stability of estimated model, specified as the comma-separated pair
          consisting of 'EnforceStability' and either true or false.
          Data Types: logical
          If EstimateCovariance is true, then use getcov to fetch the covariance matrix from the
          estimated model.
Specify whether to display the estimation progress, specified as one of the following values:
          • 'on' — Information on model structure and estimation results are displayed in a progress-viewer
            window.
1-102
                                                                                            bjOptions
Removal of offset from time-domain input data during estimation, specified as the comma-separated
pair consisting of 'InputOffset' and one of the following:
• A column vector of positive integers of length Nu, where Nu is the number of inputs.
• [] — Indicates no offset.
• Nu-by-Ne matrix — For multi-experiment data, specify InputOffset as an Nu-by-Ne matrix. Nu
  is the number of inputs, and Ne is the number of experiments.
Each entry specified by InputOffset is subtracted from the corresponding input data.
Removal of offset from time-domain output data during estimation, specified as the comma-separated
pair consisting of 'OutputOffset' and one of the following:
Each entry specified by OutputOffset is subtracted from the corresponding output data.
Options for regularized estimation of model parameters. For more information on regularization, see
“Regularized Estimates of Model Parameters”.
Specify a positive scalar to add the regularization term to the estimation cost.
   Default: 0
• R — Weighting matrix.
   Specify a vector of nonnegative numbers or a square positive semi-definite matrix. The length
   must be equal to the number of free parameters of the model.
   For black-box models, using the default value is recommended. For structured and grey-box
   models, you can also specify a vector of np positive numbers such that each entry denotes the
   confidence in the value of the associated parameter.
   The default value of 1 implies a value of eye(npfree), where npfree is the number of free
   parameters.
                                                                                               1-103
1   Functions
                Default: 1
          • Nominal — The nominal value towards which the free parameters are pulled during estimation.
                The default value of zero implies that the parameter values are pulled towards zero. If you are
                refining a model, you can set the value to 'model' to pull the parameters towards the parameter
                values of the initial model. The initial parameter values must be finite for this setting to work.
Default: 0
          Numerical search method used for iterative parameter estimation, specified as the comma-separated
          pair consisting of 'SearchMethod' and one of the following:
          • 'auto' — A combination of the line search algorithms, 'gn', 'lm', 'gna', and 'grad' methods
            is tried in sequence at each iteration. The first descent direction leading to a reduction in
            estimation cost is used.
          • 'gn' — Subspace Gauss-Newton least squares search. Singular values of the Jacobian matrix less
            than GnPinvConstant*eps*max(size(J))*norm(J) are discarded when computing the
            search direction. J is the Jacobian matrix. The Hessian matrix is approximated as JTJ. If there is no
            improvement in this direction, the function tries the gradient direction.
          • 'gna' — Adaptive subspace Gauss-Newton search. Eigenvalues less than gamma*max(sv) of the
            Hessian are ignored, where sv contains the singular values of the Hessian. The Gauss-Newton
            direction is computed in the remaining subspace. gamma has the initial value
            InitialGnaTolerance (see Advanced in 'SearchOptions' for more information). This value
            is increased by the factor LMStep each time the search fails to find a lower value of the criterion
            in fewer than five bisections. This value is decreased by the factor 2*LMStep each time a search is
            successful without any bisections.
          • 'lm' — Levenberg-Marquardt least squares search, where the next parameter value is -pinv(H
            +d*I)*grad from the previous one. H is the Hessian, I is the identity matrix, and grad is the
            gradient. d is a number that is increased until a lower value of the criterion is found.
          • 'grad' — Steepest descent least squares search.
          • 'lsqnonlin' — Trust-region-reflective algorithm of lsqnonlin. Requires Optimization Toolbox
            software.
          • 'fmincon' — Constrained nonlinear solvers. You can use the sequential quadratic programming
            (SQP) and trust-region-reflective algorithms of the fmincon solver. If you have Optimization
            Toolbox software, you can also use the interior-point and active-set algorithms of the fmincon
            solver. Specify the algorithm in the SearchOptions.Algorithm option. The fmincon algorithms
            may result in improved estimation results in the following scenarios:
                • Constrained minimization problems when there are bounds imposed on the model parameters.
                • Model structures where the loss function is a nonlinear or non smooth function of the
                  parameters.
                • Multi-output model estimation. A determinant loss function is minimized by default for multi-
                  output model estimation. fmincon algorithms are able to minimize such loss functions directly.
                  The other search methods such as 'lm' and 'gn' minimize the determinant loss function by
                  alternately estimating the noise variance and reducing the loss value for a given noise variance
                  value. Hence, the fmincon algorithms can offer better efficiency and accuracy for multi-output
                  model estimations.
1-104
                                                                                       bjOptions
Option set for the search algorithm, specified as the comma-separated pair consisting of
'SearchOptions' and a search option set with fields that depend on the value of SearchMethod.
                                                                                         1-105
1   Functions
1-106
                                                                                             bjOptions
                                                                                               1-107
1   Functions
1-108
                                                                         bjOptions
                            • 'sqp' — Sequential
                              quadratic programming
                              algorithm. The algorithm
                              satisfies bounds at all
                              iterations, and it can recover
                              from NaN or Inf results. It is
                              not a large-scale algorithm.
                              For more information, see
                              “Large-Scale vs. Medium-
                              Scale Algorithms”
                              (Optimization Toolbox).
                            • 'trust-region-
                              reflective' — Subspace
                              trust-region method based
                              on the interior-reflective
                              Newton method. It is a large-
                              scale algorithm.
                            • 'interior-point' —
                              Large-scale algorithm that
                              requires Optimization
                              Toolbox software. The
                              algorithm satisfies bounds at
                              all iterations, and it can
                              recover from NaN or Inf
                              results.
                            • 'active-set' — Requires
                              Optimization Toolbox
                              software. The algorithm can
                              take large steps, which adds
                              speed. It is not a large-scale
                              algorithm.
                                                                           1-109
1   Functions
• ErrorThreshold — Specifies when to adjust the weight of large errors from quadratic to linear.
                Errors larger than ErrorThreshold times the estimated standard deviation have a linear weight
                in the loss function. The standard deviation is estimated robustly as the median of the absolute
                deviations from the median of the prediction errors, divided by 0.7. For more information on
                robust norm choices, see section 15.2 of [2].
                Default: 0
          • MaxSize — Specifies the maximum number of elements in a segment when input-output data is
            split into segments.
                Default: 250000
          • StabilityThreshold — Specifies thresholds for stability tests.
                • s — Specifies the location of the right-most pole to test the stability of continuous-time models.
                  A model is considered stable when its right-most pole is to the left of s.
                   Default: 0
                • z — Specifies the maximum distance of all poles from the origin to test stability of discrete-
                  time models. A model is considered stable if all poles are within the distance z from the origin.
1-110
                                                                                              bjOptions
      Default: 1+sqrt(eps)
• AutoInitThreshold — Specifies when to automatically estimate the initial condition.
      yp, z − ymeas
                    > AutoInitThreshold
      yp, e − ymeas
Default: 1.05
Output Arguments
opt — Options set for bj
bjOptions option set
Examples
opt = bjOptions;
Create an options set for bj using zero initial conditions for estimation. Set Display to 'on'.
opt = bjOptions('InitialCondition','zero','Display','on');
opt = bjOptions;
opt.InitialCondition = 'zero';
opt.Display = 'on';
Compatibility Considerations
Renaming of Estimation and Analysis Options
The names of some estimation and analysis options were changed in R2018a. Prior names still work.
For details, see the R2018a release note “Renaming of Estimation and Analysis Options”.
                                                                                                  1-111
1   Functions
References
          [1] Wills, Adrian, B. Ninness, and S. Gibson. “On Gradient-Based Search for Multivariable System
                   Estimates”. Proceedings of the 16th IFAC World Congress, Prague, Czech Republic, July 3–8,
                   2005. Oxford, UK: Elsevier Ltd., 2005.
          [2] Ljung, L. System Identification: Theory for the User. Upper Saddle River, NJ: Prentice-Hall PTR,
                  1999.
          See Also
          bj | idfilt
          Topics
          “Loss Function and Model Quality Metrics”
Introduced in R2012a
1-112
                                                                                             blkdiag
blkdiag
Block-diagonal concatenation of models
Syntax
sys = blkdiag(sys1,sys2,...,sysN)
Description
sys = blkdiag(sys1,sys2,...,sysN) produces the aggregate system
     sys1 0 .. 0
      0 sys2 .   :
       :  . . 0
      0   .. 0 sysN
Examples
Create a SISO continuous-time state-space model with state-space matrices 1,2,3, and 4.
sys2 = ss(1,2,3,4);
Concatenate sys1, a SISO static gain system, and sys2. The resulting model is a 3-input, 3-output
state-space model.
sys = blkdiag(sys1,10,sys2)
sys =
  A =
        x1   x2
   x1    0    0
   x2    0    1
  B =
        u1   u2   u3
   x1    1    0    0
   x2    0    0    2
C =
                                                                                              1-113
1   Functions
                      x1   x2
                 y1    1    0
                 y2    0    0
                 y3    0    3
                D =
                      u1   u2   u3
                 y1    0    0    0
                 y2    0   10    0
                 y3    0    0    4
sys = append(sys1,10,sys2);
          See Also
          append | feedback | parallel | series
Introduced in R2009a
1-114
                                                                                                    bode
bode
Bode plot of frequency response, or magnitude and phase data
Syntax
bode(sys)
bode(sys1,sys2,...,sysN)
bode(sys1,LineSpec1,...,sysN,LineSpecN)
bode( ___ ,w)
[mag,phase,wout] = bode(sys)
[mag,phase,wout] = bode(sys,w)
[mag,phase,wout,sdmag,sdphase] = bode(sys,w)
Description
bode(sys) creates a Bode plot of the frequency response of a dynamic system model sys. The plot
displays the magnitude (in dB) and phase (in degrees) of the system response as a function of
frequency. bode automatically determines frequencies to plot based on system dynamics.
If sys is a multi-input, multi-output (MIMO) model, then bode produces an array of Bode plots, each
plot showing the frequency response of one I/O pair.
• If w is a cell array of the form {wmin,wmax}, then bode plots the response at frequencies ranging
  between wmin and wmax.
• If w is a vector of frequencies, then bode plots the response at each specified frequency.
You can use w with any of the input-argument combinations in previous syntaxes.
[mag,phase,wout] = bode(sys) returns the magnitude and phase of the response at each
frequency in the vector wout. The function automatically determines frequencies in wout based on
system dynamics. This syntax does not draw a plot.
• If w is a cell array of the form {wmin,wmax}, then wout contains frequencies ranging between
  wmin and wmax.
• If w is a vector of frequencies, then wout = w.
                                                                                                1-115
1   Functions
Examples
                          s2 + 0 . 1s + 7 . 5
                H(s) =                        .
                         s4 + 0 . 12s3 + 9s2
bode automatically selects the plot range based on the system dynamics.
          Create a Bode plot over a specified frequency range. Use this approach when you want to focus on
          the dynamics in a particular range of frequencies.
          H = tf([-0.1,-2.4,-181,-1950],[1,3.3,990,2600]);
          bode(H,{1,100})
          grid on
1-116
                                                                                                       bode
The cell array {1,100} specifies the minimum and maximum frequency values in the Bode plot.
When you provide frequency bounds in this way, the function selects intermediate points for
frequency response data.
Alternatively, specify a vector of frequency points to use for evaluating and plotting the frequency
response.
w = [1 5 10 15 20 23 31 40 44 50 85 100];
bode(H,w,'.-')
grid on
                                                                                                  1-117
1   Functions
bode(H,Hd)
1-118
                                                                                                    bode
The Bode plot of a discrete-time system includes a vertical line marking the Nyquist frequency of the
system.
Specify the line style, color, or marker for each system in a Bode plot using the LineSpec input
argument.
                                                                                                   1-119
1   Functions
          The first LineSpec, 'r', specifies a solid red line for the response of H. The second LineSpec,
          'b--', specifies a dashed blue line for the response of Hd.
Compute the magnitude and phase of the frequency response of a SISO system.
          If you do not specify frequencies, bode chooses frequencies based on the system dynamics and
          returns them in the third output argument.
          Because H is a SISO model, the first two dimensions of mag and phase are both 1. The third
          dimension is the number of frequencies in wout.
size(mag)
ans = 1×3
1 1 42
length(wout)
1-120
                                                                                                  bode
ans = 42
Thus, each entry along the third dimension of mag gives the magnitude of the response at the
corresponding frequency in wout.
For this system, bode plots the frequency responses of each I/O channel in a separate plot in a single
figure.
bode(H)
Compute the magnitude and phase of these responses at 20 frequencies between 1 and 10 radians.
w = logspace(0,1,20);
[mag,phase] = bode(H,w);
mag and phase are three-dimensional arrays, in which the first two dimensions correspond to the
output and input dimensions of H, and the third dimension is the number of frequencies. For instance,
examine the dimensions of mag.
                                                                                                1-121
1   Functions
size(mag)
ans = 1×3
2 3 20
          Thus, for example, mag(1,3,10) is the magnitude of the response from the third input to the first
          output, computed at the 10th frequency in w. Similarly, phase(1,3,10) contains the phase of the
          same response.
          Compare the frequency response of a parametric model, identified from input/output data, to a
          nonparametric model identified using the same data.
Using the spa and tfest commands requires System Identification Toolbox™ software.
          bode(sys_np,sys_p,w);
          legend('sys-np','sys-p')
1-122
                                                                                                   bode
You can display the confidence region on the Bode plot by right-clicking the plot and selecting
Characteristics > Confidence Region.
Compute the standard deviation of the magnitude and phase of an identified model. Use this data to
create a 3σ plot of the response uncertainty.
Identify a transfer function model based on data. Obtain the standard deviation data for the
magnitude and phase of the frequency response.
sys_p is an identified transfer function model. sdmag and sdphase contain the standard deviation
data for the magnitude and phase of the frequency response, respectively.
Use the standard deviation data to create a 3σ plot corresponding to the confidence region.
                                                                                                  1-123
1   Functions
          mag = squeeze(mag);
          sdmag = squeeze(sdmag);
          semilogx(w,mag,'b',w,mag+3*sdmag,'k:',w,mag-3*sdmag,'k:');
          Input Arguments
          sys — Dynamic system
          dynamic system model | model array
          Dynamic system, specified as a SISO or MIMO dynamic system model or array of dynamic system
          models. Dynamic systems that you can use include:
                • For tunable control design blocks, the function evaluates the model at its current value for
                  both plotting and returning frequency response data.
                • For uncertain control design blocks, the function plots the nominal value and random samples
                  of the model. When you use output arguments, the function returns frequency response data
                  for the nominal model only.
          • Frequency-response data models such as frd models. For such models, the function plots the
            response at frequencies defined in the model.
1-124
                                                                                                   bode
• Identified LTI models, such as idtf, idss, or idproc models. For such models, the function can
  also plot confidence intervals and return standard deviations of the frequency response. See
  “Bode Plot of Identified Model” on page 1-122.
If sys is an array of models, the function plots the frequency responses of all models in the array on
the same axes.
Line style, marker, and color, specified as a string or vector of one, two, or three characters. The
characters can appear in any order. You do not need to specify all three characteristics (line style,
marker, and color). For example, if you omit the line style and specify the marker, then the plot shows
only the marker and no line. For more information about configuring this argument, see the
LineSpec input argument of the plot function.
Example: 'r--' specifies a red dashed line
Example: '*b' specifies blue asterisk markers
Example: 'y' specifies a yellow line
w — Frequencies
{wmin,wmax} | vector
Frequencies at which to compute and plot frequency response, specified as the cell array
{wmin,wmax} or as a vector of frequency values.
• If w is a cell array of the form {wmin,wmax}, then the function computes the response at
  frequencies ranging between wmin and wmax.
• If w is a vector of frequencies, then the function computes the response at each specified
  frequency. For example, use logspace to generate a row vector with logarithmically spaced
  frequency values.
Specify frequencies in units of rad/TimeUnit, where TimeUnit is the TimeUnit property of the
model.
Output Arguments
mag — Magnitude of system response
3-D array
Magnitude of the system response in absolute units, returned as a 3-D array. The dimensions of this
array are (number of system outputs) × (number of system inputs) × (number of frequency points).
• For SISO systems, mag(1,1,k) gives the magnitude of the response at the kth frequency in w or
  wout. For an example, see “Obtain Magnitude and Phase Data” on page 1-120.
• For MIMO systems, mag(i,j,k) gives the magnitude of the response at the kth frequency from
  the jth input to the ith output. For an example, see “Magnitude and Phase of MIMO System” on
  page 1-121.
magdb = 20*log10(mag)
                                                                                                 1-125
1   Functions
          Phase of the system response in degrees, returned as a 3-D array. The dimensions of this array are
          (number of outputs) × (number of inputs) × (number of frequency points).
          • For SISO systems, mag(1,1,k) gives the phase of the response at the kth frequency in w or wout.
            For an example, see “Obtain Magnitude and Phase Data” on page 1-120.
          • For MIMO systems, mag(i,j,k) gives the phase of the response at the kth frequency from the
            jth input to the ith output. For an example, see “Magnitude and Phase of MIMO System” on page
            1-121.
          wout — Frequencies
          vector
          Frequencies at which the function returns the system response, returned as a column vector. The
          function chooses the frequency values based on the model dynamics, unless you specify frequencies
          using the input argument w.
          Frequency values are in radians per TimeUnit, where TimeUnit is the value of the TimeUnit
          property of sys.
          Estimated standard deviation of the magnitude of the response at each frequency point, returned as a
          3-D array. sdmag has the same dimensions as mag.
          Estimated standard deviation of the phase of the response at each frequency point, returned as a 3-D
          array. sdphase has the same dimensions as phase.
          Tips
          • When you need additional plot customization options, use bodeplot instead.
          Algorithms
          bode computes the frequency response as follows:
                • For continuous-time systems, bode evaluates the frequency response on the imaginary axis s
                  = jω and considers only positive frequencies.
1-126
                                                                                                     bode
    • For discrete-time systems, bode evaluates the frequency response on the unit circle. To
      facilitate interpretation, the command parameterizes the upper half of the unit circle as:
          jωTs                      π
    z=e          ,   0 ≤ ω ≤ ωN =      ,
                                    Ts
       where Ts is the sample time and ωN is the Nyquist frequency. The equivalent continuous-time
                                                                      jωTs
       frequency ω is then used as the x-axis variable. Because H e          is periodic with period 2ωN,
       bode plots the response only up to the Nyquist frequency ωN. If sys is a discrete-time model
       with unspecified sample time, bode uses Ts = 1.
See Also
bodeplot | freqresp | nyquist | spectrum | step
Topics
“Plot Bode and Nyquist Plots at the Command Line”
“Dynamic System Models”
                                                                                                   1-127
1   Functions
          bodemag
          Magnitude-only Bode plot of frequency response
          Syntax
          bodemag(sys)
          bodemag(sys1,sys2,...,sysN)
          bodemag(sys1,LineSpec1,...,sysN,LineSpecN)
          bodemag( ___ ,w)
          Description
          bodemag enables you to generate magnitude-only plots to visualize the magnitude frequency
          response of a dynamic system.
          For a more comprehensive function, see bode. bode provides magnitude and phase information. If
          you have System Identification toolbox, bode also returns the computed values, including statistical
          estimates.
          bodemag(sys) creates a Bode magnitude plot of the frequency response of the dynamic system
          model sys. The plot displays the magnitude (in dB) of the system response as a function of frequency.
          bodemag automatically determines frequencies to plot based on system dynamics.
          If sys is a multi-input, multi-output (MIMO) model, then bodemag produces an array of Bode
          magnitude plots in which each plot shows the frequency response of one I/O pair.
          • If w is a cell array of the form {wmin,wmax}, then bodemag plots the response at frequencies
            ranging between wmin and wmax.
          • If w is a vector of frequencies, then bodemag plots the response at each specified frequency.
You can use this syntax with any of the input-argument combinations in previous syntaxes.
Examples
Create a Bode magnitude plot of the following continuous-time SISO dynamic system.
                        s2 + 0 . 1s + 7 . 5
                Hs =
                       s4 + 0 . 12s3 + 9s2
1-128
                                                                                          bodemag
bodemag automatically selects the plot range based on the system dynamics.
Create a Bode magnitude plot over a specified frequency range. Use this approach when you want to
focus on the dynamics in a particular range of frequencies.
H = tf([-0.1,-2.4,-181,-1950],[1,3.3,990,2600]);
bodemag(H,{1,100})
grid on
                                                                                            1-129
1   Functions
          The cell array {1,100} specifies the minimum and maximum frequency values in the Bode
          magnitude plot. When you provide frequency bounds in this way, the function selects intermediate
          points for frequency response data.
          Alternatively, specify a vector of frequency points to use for evaluating and plotting the frequency
          response.
          w = [1 5 10 15 20 23 31 40 44 50 85 100];
          bodemag(H,w,'.-')
          grid on
1-130
                                                                                         bodemag
Create a Bode magnitude plot that displays the responses of both systems.
bodemag(H,Hd)
                                                                                           1-131
1   Functions
          The Bode magnitude plot of a discrete-time system includes a vertical line marking the Nyquist
          frequency of the system.
          Specify the color, linestyle, or marker for each system in a Bode magnitude plot using the LineSpec
          input arguments.
1-132
                                                                                               bodemag
The first LineSpec argument 'r' specifies a solid red line for the response of H. The second
LineSpec argument 'b--' specifies a dashed blue line for the response of Hd.
For this system, bodemag plots the magnitude-only frequency responses of each I/O channel in a
separate plot in a single figure.
bodemag(H)
                                                                                                1-133
1   Functions
          Input Arguments
          sys — Dynamic system
          dynamic system model | model array
          Dynamic system, specified as a SISO or MIMO dynamic system model or array of dynamic system
          models. Dynamic systems that you can use include:
                • For tunable control design blocks, the function evaluates the model at its current value for
                  both plotting and returning frequency response data.
                • For uncertain control design blocks, the function plots the nominal value and random samples
                  of the model. When you use output arguments, the function returns frequency response data
                  for the nominal model only.
          • Frequency-response data models such as frd models. For such models, the function plots the
            response at frequencies defined in the model.
          • Identified LTI models, such as idtf, idss, or idproc models.
          If sys is an array of models, the function plots the frequency responses of all models in the array on
          the same axes.
1-134
                                                                                                 bodemag
Line style, marker, and color, specified as a string or vector of one, two, or three characters. The
characters can appear in any order. You do not need to specify all three characteristics (line style,
marker, and color). For example, if you omit the line style and specify the marker, then the plot shows
only the marker and no line. For more information about configuring this argument, see the
LineSpec input argument of the plot function.
Example: 'r--' specifies a red dashed line
Example: '*b' specifies blue asterisk markers
Example: 'y' specifies a yellow line
w — Frequencies
{wmin,wmax} | vector
Frequencies at which to compute and plot frequency response, specified as the cell array
{wmin,wmax} or as a vector of frequency values.
• If w is a cell array of the form {wmin,wmax}, then the function computes the index at frequencies
  ranging between wmin and wmax.
• If w is a vector of frequencies, then the function computes the index at each specified frequency.
  For example, use logspace to generate a row vector with logarithmically spaced frequency
  values.
Specify frequencies in units of rad/TimeUnit, where TimeUnit is the TimeUnit property of the
model.
Algorithms
bodemag computes the frequency response as follows:
    • For continuous-time systems, bodemag evaluates the frequency response on the imaginary
      axis s = jω and considers only positive frequencies.
    • For discrete-time systems, bodemag evaluates the frequency response on the unit circle. To
      facilitate interpretation, the command parameterizes the upper half of the unit circle as:
          jωTs                      π
    z=e          ,   0 ≤ ω ≤ ωN =      ,
                                    Ts
       where Ts is the sample time and ωN is the Nyquist frequency. The equivalent continuous-time
                                                                      jωTs
       frequency ω is then used as the x-axis variable. Because H e          is periodic with period 2ωN,
       bodemag plots the response only up to the Nyquist frequency ωN. If sys is a discrete-time
       model with unspecified sample time, bodemag uses Ts = 1.
See Also
bode | bodeplot | freqresp | nyquist | spectrum | step
                                                                                                   1-135
1   Functions
          Topics
          “Plot Bode and Nyquist Plots at the Command Line”
          “Dynamic System Models”
Introduced in R2012a
1-136
                                                                                                        bodeoptions
         bodeoptions
         Create list of Bode plot options
         Syntax
         P = bodeoptions
         P = bodeoptions('cstprefs')
         Description
         P = bodeoptions returns a default set of plot options for use with the bodeplot. You can use
         these options to customize the Bode plot appearance using the command line. This syntax is useful
         when you want to write a script to generate plots that look the same regardless of the preference
         settings of the MATLAB session in which you run the script.
         P = bodeoptions('cstprefs') initializes the plot options with the options you selected in the
         Control System and System Identification Toolbox Preferences Editor. For more information about the
         editor, see “Toolbox Preferences Editor”. This syntax is useful when you want to change a few plot
         options but otherwise use your default preferences. A script that uses this syntax may generate
         results that look different when run in a session with different preferences.
Option                      Description
Title, XLabel, YLabel       Label text and style, specified as a structure with the following fields:
                            • FontSize Default: 8
                            • FontWeight — Default: 'Normal'
                            • Font Angle — Default: 'Normal'
                            • Color — Vector of RGB values ranging from 0 to 1. Default: [0,0,0]
Grid                        Show or hide the grid
                            Specified as one of the following values: 'off' | 'on'
                            Default: 'off'
                                                                                                            1-137
1   Functions
Option                    Description
GridColor                 Color of the grid lines
                          Specified as one of the following: Vector of RGB values in the range [0,1] |
                          character vector of color name | 'none'. For example, for yellow color, specify as
                          one of the following: [1 1 0], 'yellow', or 'y'.
                          Default: [0.15,0.15,0.15]
XlimMode, YlimMode        Axis limit modes. Default: 'auto'
Xlim, Ylim                Axes limits, specified as an array of the form [min,max]
IOGrouping                Grouping of input-output pairs
                          Specified as one of the following values: 'none' |'inputs'|'outputs'|'all'
                          Default: 'none'
InputLabels,              Input and output label styles
OutputLabels
InputVisible,             Visibility of input and output channels
OutputVisible
ConfidenceRegionNumbe Number of standard deviations to use to plotting the response confidence region
rSD                   (identified models only).
Default: 1.
1-138
                                                                                bodeoptions
Option            Description
FreqUnits         Frequency units, specified as one of the following values:
                  • 'Hz'
                  • 'rad/second'
                  • 'rpm'
                  • 'kHz'
                  • 'MHz'
                  • 'GHz'
                  • 'rad/nanosecond'
                  • 'rad/microsecond'
                  • 'rad/millisecond'
                  • 'rad/minute'
                  • 'rad/hour'
                  • 'rad/day'
                  • 'rad/week'
                  • 'rad/month'
                  • 'rad/year'
                  • 'cycles/nanosecond'
                  • 'cycles/microsecond'
                  • 'cycles/millisecond'
                  • 'cycles/hour'
                  • 'cycles/day'
                  • 'cycles/week'
                  • 'cycles/month'
                  • 'cycles/year'
FreqScale         Frequency scale
                  Specified as one of the following values: 'linear' | 'log'
                  Default: 'log'
MagUnits          Magnitude units
                  Specified as one of the following values: 'dB' | 'abs'
                  Default: 'dB'
MagScale          Magnitude scale
                  Specified as one of the following values: 'linear' | 'log'
                  Default: 'linear'
MagVisible        Magnitude plot visibility
                  Specified as one of the following values: 'on' | 'off'
                  Default: 'on'
MagLowerLimMode   Enables a lower magnitude limit
                  Specified as one of the following values: 'auto' | 'manual'
                  Default: 'auto'
MagLowerLim       Specifies the lower magnitude limit
                                                                                    1-139
1   Functions
Option                       Description
PhaseUnits                   Phase units
                             Specified as one of the following values: 'deg' | 'rad'
                             Default: 'deg'
PhaseVisible                 Phase plot visibility
                             Specified as one of the following values: 'on' | 'off'
                             Default: 'on'
PhaseWrapping                Enables phase wrapping
                             Specified as one of the following values: 'on' | 'off'
                             When you set PhaseWrapping to 'on', the plot wraps accumulated phase at the
                             value specified by the PhaseWrappingBranch property.
                             Default: 'off'
PhaseWrappingBranch          Phase value at which the plot wraps accumulated phase when PhaseWrapping is
                             set to 'on'.
                             Default: –180 (phase wraps into the interval [–180º,180º))
PhaseMatching                Enables phase matching
                             Specified as one of the following values: 'on' | 'off'
                             Default: 'off'
PhaseMatchingFreq            Frequency for matching phase
PhaseMatchingValue           The value to which phase responses are matched closely
Examples
          Create a Bode plot that suppresses the phase plot and uses frequency units Hz instead of the default
          radians/second. Otherwise, the plot uses the settings that are saved in the toolbox preferences.
opts = bodeoptions('cstprefs');
          opts.PhaseVisible = 'off';
          opts.FreqUnits = 'Hz';
h = bodeplot(tf(1,[1,1]),opts);
1-140
                                                                                             bodeoptions
Depending on your own toolbox preferences, the plot you obtain might look different from this plot.
Only the properties that you set explicitly, in this example PhaseVisible and FreqUnits, override
the toolbox preferences.
Create a Bode plot that uses 14-point red text for the title. This plot should look the same, regardless
of the preferences of the MATLAB session in which it is generated.
opts = bodeoptions;
opts.Title.FontSize = 14;
opts.Title.Color = [1 0 0];
opts.FreqUnits = 'Hz';
h = bodeplot(tf(1,[1,1]),opts);
                                                                                                  1-141
1   Functions
          Because opts begins with a fixed set of options, the plot result is independent of the toolbox
          preferences of the MATLAB session.
          See Also
          bode | bodeplot | getoptions | setoptions | showConfidence
Introduced in R2012a
1-142
                                                                                               bodeplot
bodeplot
Plot Bode frequency response with additional plot customization options
Syntax
h = bodeplot(sys)
bodeplot(sys)
bodeplot(sys1,sys2,...)
bodeplot(AX,...)
bodeplot(..., plotoptions)
bodeplot(sys,w)
Description
h = bodeplot(sys) plot the Bode magnitude and phase of the dynamic system model sys and
returns the plot handle h to the plot. You can use this handle to customize the plot with the
getoptions and setoptions commands.
bodeplot(sys) draws the Bode plot of the model sys. The frequency range and number of points
are chosen automatically.
bodeplot(sys1,'r',sys2,'y--',sys3,'gx')
bodeplot(..., plotoptions) plots the Bode response with the options specified in
plotoptions. Type
help bodeoptions
for a list of available plot options. See “Match Phase at Specified Frequency” on page 1-145 for an
example of phase matching using the PhaseMatchingFreq and PhaseMatchingValue options.
bodeplot(sys,w) draws the Bode plot for frequencies specified by w. When w = {wmin,wmax},
the Bode plot is drawn for frequencies between wmin and wmax (in rad/TimeUnit, where TimeUnit
is the time units of the input dynamic system, specified in the TimeUnit property of sys.). When w is
a user-supplied vector w of frequencies, in rad/TimeUnit, the Bode response is drawn for the specified
frequencies.
Examples
                                                                                                1-143
1   Functions
          sys = rss(5);
          h = bodeplot(sys);
Change the units to Hz and suppress the phase plot. To do so, edit properties of the plot handle, h.
setoptions(h,'FreqUnits','Hz','PhaseVisible','off');
1-144
                                                           bodeplot
                                                            1-145
1   Functions
          Fix the phase at 1 rad/s to 750 degrees. To do so, get the plot properties. Then alter the properties
          PhaseMatchingFreq and PhaseMatchingValue to match a phase to a specified frequency.
          p = getoptions(h);
          p.PhaseMatching = 'on';
          p.PhaseMatchingFreq = 1;
          p.PhaseMatchingValue = 750;
setoptions(h,p);
1-146
                                                                                              bodeplot
The first bode plot has a phase of -45 degrees at a frequency of 1 rad/s. Setting the phase matching
options so that at 1 rad/s the phase is near 750 degrees yields the second Bode plot. Note that,
however, the phase can only be -45 + N*360, where N is an integer, and so the plot is set to the
nearest allowable phase, namely 675 degrees (or 2*360 - 45 = 675).
Compare the frequency responses of identified state-space models of order 2 and 6 along with their 2
σ confidence regions.
load iddata1
sys1 = n4sid(z1, 2);
sys2 = n4sid(z1, 6);
Both models produce about 70% fit to data. However, sys2 shows higher uncertainty in its frequency
response, especially close to Nyquist frequency as shown by the plot:
w = linspace(8,10*pi,256);
h = bodeplot(sys1,sys2,w);
setoptions(h,'PhaseMatching','on','ConfidenceRegionNumberSD',2);
                                                                                                1-147
1   Functions
          Right-click the plot and select Characteristics > Confidence Region to turn on the confidence
          region characteristic. Alternatively, type showConfidence(h) to plot the confidence region.
          Compare the frequency response of a parametric model, identified from input/output data, to a
          nonparametric model identified using the same data. Identify parametric and non-parametric models
          based on data.
          spa and tfest require System Identification Toolbox™ software. sys_np is a nonparametric
          identified model. sys_p is a parametric identified model.
          opt = bodeoptions;
          opt.PhaseMatching = 'on';
          bodeplot(sys_np,sys_p,w,opt);
1-148
                                                                                              bodeplot
Tips
You can change the properties of your plot, for example the units. For information on the ways to
change properties of your plots, see “Ways to Customize Plots” (Control System Toolbox).
See Also
bode | bodeoptions | getoptions | setoptions | showConfidence
                                                                                               1-149
1   Functions
          c2d
          Convert model from continuous to discrete time
          Syntax
          sysd = c2d(sysc,Ts)
          sysd = c2d(sysc,Ts,method)
          sysd = c2d(sysc,Ts,opts)
          [sysd,G] = c2d( ___ )
          Description
          sysd = c2d(sysc,Ts) discretizes the continuous-time dynamic system model sysc using zero-
          order hold on the inputs and a sample time of Ts.
          [sysd,G] = c2d( ___ ), where sysc is a state-space model, returns a matrix, G that maps the
          continuous initial conditions x0 and u0 of the state-space model to the discrete-time initial state vector
          x[0].
Examples
                                    s−1
                H s = e−0 . 3s                 .
                                 s2 + 4s + 5
          This system has an input delay of 0.3 s. Discretize the system using the triangle (first-order-hold)
          approximation with sample time Ts = 0.1 s.
step(H,'-',Hd,'--')
1-150
                                                                                                      c2d
Discretize the following delayed transfer function using zero-order hold on the input, and a 10-Hz
sampling rate.
                             10
       H s = e−0 . 25s                  .
                         s2 + 3s + 10
h = tf(10,[1 3 10],'IODelay',0.25);
hd = c2d(h,0.1)
hd =
In this example, the discretized model hd has a delay of three sampling periods. The discretization
algorithm absorbs the residual half-period delay into the coefficients of hd.
                                                                                                1-151
1   Functions
step(h,'--',hd,'-')
Create a continuous-time state-space model with two states and an input delay.
          sys = ss(tf([1,2],[1,4,2]));
          sys.InputDelay = 2.7
sys =
                A =
                      x1    x2
                x1    -4    -2
                x2     1     0
                B =
                      u1
                x1     2
                x2     0
                C =
                       x1     x2
                y1    0.5      1
1-152
                                                                                                       c2d
  D =
        u1
   y1    0
Discretize the model using the Tustin discretization method and a Thiran filter to model fractional
delays. The sample time Ts = 1 second.
opt = c2dOptions('Method','tustin','FractDelayApproxOrder',3);
sysd1 = c2d(sys,1,opt)
sysd1 =
  A =
                  x1         x2           x3            x4            x5
   x1        -0.4286    -0.5714     -0.00265       0.06954         2.286
   x2         0.2857     0.7143    -0.001325       0.03477         1.143
   x3              0          0      -0.2432        0.1449       -0.1153
   x4              0          0         0.25             0             0
   x5              0          0            0         0.125             0
  B =
              u1
   x1   0.002058
   x2   0.001029
   x3          8
   x4          0
   x5          0
  C =
                  x1         x2           x3            x4            x5
   y1         0.2857     0.7143    -0.001325       0.03477         1.143
  D =
              u1
   y1   0.001029
The discretized model now contains three additional states x3, x4, and x5 corresponding to a third-
order Thiran filter. Since the time delay divided by the sample time is 2.7, the third-order Thiran filter
('FractDelayApproxOrder' = 3) can approximate the entire time delay.
                                                                                                   1-153
1   Functions
sys2d = tfest(z1,2,'Ts',0.1);
          Compare the response of the discretized continuous-time transfer function model, sys1d, and the
          directly estimated discrete-time model, sys2d.
compare(z1,sys1d,sys2d)
Discretize an identified state-space model to build a one-step ahead predictor of its response.
          load iddata2
          sysc = ssest(z2,4);
predict(sysc,z2)
1-154
                                                                                          c2d
sysd = c2d(sysc,0.1,'zoh');
[A,B,C,D,K] = idssdata(sysd);
Predictor = ss(A-K*C,[K B-K*D],C,[0 D],0.1);
Predictor is a two-input model which uses the measured output and input signals ([z1.y z1.u])
to compute the 1-step predicted response of sysc.
Simulate the predictor model to get the same response as the predict command.
lsim(Predictor,[z2.y,z2.u])
                                                                                        1-155
1   Functions
The simulation of the predictor model gives the same response as predict(sysc,z2).
          Input Arguments
          sysc — Continuous-time dynamic system
          dynamic system model
          Continuous-time model, specified as a dynamic system model such as idtf, idss, or idpoly. sysc
          cannot be a frequency response data model. sysc can be a SISO or MIMO system, except that the
          'matched' discretization method supports SISO systems only.
          sysc can have input/output or internal time delays; however, the 'matched', 'impulse', and
          'least-squares' methods do not support state-space models with internal time delays.
          Ts — Sample time
          positive scalar
          Sample time, specified as a positive scalar that represents the sampling period of the resulting
          discrete-time system. Ts is in TimeUnit, which is the sysc.TimeUnit property.
1-156
                                                                                                        c2d
• 'zoh' — Zero-order hold (default). Assumes the control inputs are piecewise constant over the
  sample time Ts.
• 'foh' — Triangle approximation (modified first-order hold). Assumes the control inputs are
  piecewise linear over the sample time Ts.
• 'impulse' — Impulse invariant discretization
• 'tustin' — Bilinear (Tustin) method. To specify this method with frequency prewarping
  (formerly known as the 'prewarp' method), use the PrewarpFrequency option of c2dOptions.
• 'matched' — Zero-pole matching method
• 'least-squares' — Least-squares method
For information about the algorithms for each conversion method, see “Continuous-Discrete
Conversion Methods”.
Discretization options, specified as a c2dOptions object. For example, specify the prewarp
frequency, order of the Thiran filter or discretization method as an option.
Output Arguments
sysd — Discrete-time model
dynamic system model
Discrete-time model, returned as a dynamic system model of the same type as the input system sysc.
• Includes both measured and noise components of sysc. The innovations variance λ of the
  continuous-time identified model sysc, stored in its NoiseVarianceproperty, is interpreted as
  the intensity of the spectral density of the noise spectrum. The noise variance in sysd is thus λ/Ts.
• Does not include the estimated parameter covariance of sysc. If you want to translate the
  covariance while discretizing the model, use translatecov.
Mapping of continuous-time initial conditions x0 and u0 of the state-space model sysc to the discrete-
time initial state vector x[0], returned as a matrix. The mapping of initial conditions to the initial state
vector is as follows:
                x0
    x 0 =G⋅
                u0
                                                                                                     1-157
1   Functions
          For state-space models with time delays, c2d pads the matrix G with zeroes to account for additional
          states introduced by discretizing those delays. See “Continuous-Discrete Conversion Methods” for a
          discussion of modeling time delays in discretized systems.
          See Also
          c2dOptions | d2c | d2d | thiran | translatecov
          Topics
          “Dynamic System Models”
          “Transforming Between Discrete-Time and Continuous-Time Representations”
          “Continuous-Discrete Conversion Methods”
1-158
                                                                                            c2dOptions
c2dOptions
Create option set for continuous- to discrete-time conversions
Syntax
opts = c2dOptions
opts = c2dOptions('OptionName', OptionValue)
Description
opts = c2dOptions returns the default options for c2d.
Input Arguments
Name-Value Pair Arguments
Method
'zoh'                  Zero-order hold, where c2d assumes the control inputs are piecewise constant
                       over the sample time Ts.
'foh'                  Triangle approximation (modified first-order hold), where c2d assumes the
                       control inputs are piecewise linear over the sample time Ts. (See [1] on page
                       1-160, p. 228.)
'impulse'              Impulse-invariant discretization.
'tustin'               Bilinear (Tustin) approximation. By default, c2d discretizes with no prewarp
                       and rounds any fractional time delays to the nearest multiple of the sample
                       time. To include prewarp, use the PrewarpFrequency option. To approximate
                       fractional time delays, use theFractDelayApproxOrder option.
'matched'              Zero-pole matching method. (See [1] on page 1-160, p. 224.) By default, c2d
                       rounds any fractional time delays to the nearest multiple of the sample time.
                       To approximate fractional time delays, use the FractDelayApproxOrder
                       option.
'least-squares'        Least-squares method. Minimize the error between the frequency responses
                       of the continuous-time and discrete-time systems up to the Nyquist frequency.
For information about the algorithms for each conversion method, see “Continuous-Discrete
Conversion Methods”.
Default: 'zoh'
                                                                                                1-159
1   Functions
PrewarpFrequency
          Prewarp frequency for 'tustin' method, specified in rad/TimeUnit, where TimeUnit is the time
          units, specified in the TimeUnit property, of the discretized system. Takes positive scalar values. A
          value of 0 corresponds to the standard 'tustin' method without prewarp.
Default: 0
FractDelayApproxOrder
          Maximum order of the Thiran filter used to approximate fractional delays in the 'tustin' and
          'matched' methods. Takes integer values. A value of 0 means that c2d rounds fractional delays to
          the nearest integer multiple of the sample time.
Default: 0
Examples
          sys1 = rss(3,2,2);
          sys2 = rss(4,4,1);
Create an option set for c2d to use the Tustin discretization method and 3.4 rad/s prewarp frequency.
opt = c2dOptions('Method','tustin','PrewarpFrequency',3.4);
Discretize the models, sys1 and sys2, using the same option set, but different sample times.
          dsys1 = c2d(sys1,0.1,opt);
          dsys2 = c2d(sys2,0.2,opt);
References
          [1] Franklin, G.F., Powell, D.J., and Workman, M.L., Digital Control of Dynamic Systems (3rd Edition),
                  Prentice Hall, 1997.
          See Also
          c2d
Introduced in R2012a
1-160
                                                                                             canon
canon
Canonical state-space realization
Syntax
csys = canon(sys,type)
csys = canon(sys,'modal',condt)
Description
csys = canon(sys,type) transforms the linear model sys into a canonical state-space model
csys. type specifies whether csys is in modal or companion form.
For information on controllable and observable canonical forms, see “Canonical State-Space
Realizations”.
[csys,T]= canon( ___ ) also returns the state-coordinate transformation matrix T that relates the
states of the state-space model sys to the states of csys.
Examples
     α̇   −0 . 313 56 . 7 0 α       0 . 232
     q̇ = −0 . 0139 −0 . 426 0 q + 0 . 0203 δ
     θ̇       0      56 . 7 0 θ         0
                    α
          y = 0 0 1 q + 0 δ
                    θ
Load the model data to the workspace and create the state-space model sys.
load('aircraftPitchSSModel.mat');
sys = ss(A,B,C,D)
sys =
  A =
               x1         x2        x3
   x1      -0.313       56.7         0
                                                                                             1-161
1   Functions
                 x2   -0.0139        -0.426         0
                 x3         0          56.7         0
                B =
                          u1
                 x1    0.232
                 x2   0.0203
                 x3        0
                C =
                      x1   x2   x3
                 y1    0    0    1
                D =
                      u1
                 y1    0
csys = canon(sys,'companion')
csys =
                A =
                                x1             x2           x3
                 x1              0              0   -1.709e-16
                 x2              1              0      -0.9215
                 x3              0              1       -0.739
                B =
                      u1
                 x1    1
                 x2    0
                 x3    0
                C =
                           x1           x2         x3
                 y1         0        1.151    -0.6732
                D =
                      u1
                 y1    0
1-162
                                                                                              canon
     ẋ   0 1             0     0   x   0
     ẍ   0 −0 . 1        3     0   ẋ  2
        =                              + u
     θ̇   0 0              0    1   θ   0
     θ̈   0 −0 . 5        30    0   θ̇  5
                           x
                1 0 0 0 ẋ  0
          y =              + u
                0 0 1 0 θ   0
                           θ̇
Convert sys to modal canonical form and extract the transformation matrix.
[csys,T] = canon(sys,'modal')
csys =
  A =
                x1        x2            x3        x4
   x1            0         0             0         0
   x2            0     5.453             0         0
   x3            0         0        -5.503         0
   x4            0         0             0     -0.05
  B =
              u1
   x1      1.875
   x2     -6.009
   x3      6.386
   x4     -2.409
  C =
                     x1          x2                 x3          x4
   y1                16   -0.007321          -0.007411       12.45
   y2                 0    -0.07388           -0.07344    -0.01038
  D =
          u1
   y1      0
   y2      0
T = 4×4
csys is the modal canonical form of sys, while T represents the transformation between the state
vectors of sys and csys.
                                                                                             1-163
1   Functions
For this example, consider the following system with doubled poles and clusters of close poles:
                                               s−1 s+1
                sys s = 100                                      2            2
                              s s + 10 s + 10 . 0001 s − 1 + i       s− 1−i
Create a zpk model of this system and convert it to modal canonical form using the string 'modal'.
ans = 7×7
                     0          0            0           0            0          0          0
                     0     1.0000       1.0000           0            0          0          0
                     0    -1.0000       1.0000      2.0548            0          0          0
                     0          0            0      1.0000       1.0000          0          0
                     0          0            0     -1.0000       1.0000          0          0
                     0          0            0           0            0   -10.0000     8.0573
                     0          0            0           0            0          0   -10.0001
csys1.B
ans = 7×1
                 0.3200
                -0.0066
                 0.0540
                -0.1950
                 1.0637
                      0
                 4.0378
          sys has a pair of poles at s = -10 and s = -10.0001, and two complex poles of multiplicity 2 at s =
          1+i and s = 1-i. As a result, the modal form csys1 is a state-space model with a block of size 2 for
          the two poles near s = -10, and a block of size 4 for the complex eigenvalues.
          Now, separate the two poles near s = -10 by increasing the value of the condition number of the
          block-diagonalizing transformation. Use a value of 1e10 for this example.
          csys2 = canon(sys,'modal',1e10);
          csys2.A
ans = 7×7
                     0          0            0           0            0          0         0
                     0     1.0000       1.0000           0            0          0         0
                     0    -1.0000       1.0000      2.0548            0          0         0
                     0          0            0      1.0000       1.0000          0         0
                     0          0            0     -1.0000       1.0000          0         0
                     0          0            0           0            0   -10.0000         0
1-164
                                                                                                 canon
0 0 0 0 0 0 -10.0001
format shortE
csys2.B
ans = 7×1
   3.2000e-01
  -6.5691e-03
   5.4046e-02
  -1.9502e-01
   1.0637e+00
   3.2533e+05
   3.2533e+05
The A matrix of csys2 includes separate diagonal elements for the poles near s = -10. Increasing the
condition number results in some very large values in the B matrix.
The file icEngine.mat contains one data set with 1500 input-output samples collected at the a
sampling rate of 0.04 seconds. The input u(t) is the voltage (V) controlling the By-Pass Idle Air Valve
(BPAV), and the output y(t) is the engine speed (RPM/100).
Use the data in icEngine.mat to create a state-space model with identifiable parameters.
load icEngine.mat
z = iddata(y,u,0.04);
sys = n4sid(z,4,'InputDelay',2);
csys = canon(sys,'companion');
Obtain the covariance of the resulting form by running a zero-iteration update to model parameters.
opt = ssestOptions;
opt.SearchOptions.MaxIterations = 0;
csys = ssest(z,csys,opt);
h = bodeplot(sys,csys,'r.');
showConfidence(h)
                                                                                                 1-165
1   Functions
          Input Arguments
          sys — Dynamic system
          dynamic system model
          Dynamic system, specified as a SISO, or MIMO dynamic system model. Dynamic systems that you can
          use include:
          • Continuous-time or discrete-time numeric LTI models, such as tf, zpk, ss, or pid models.
          • Generalized or uncertain LTI models such as genss or uss models. (Using uncertain models
            requires Robust Control Toolbox software.)
                • current values of the tunable components for tunable control design blocks.
                • nominal model values for uncertain control design blocks.
          • Identified LTI models, such as idtf, idss, idproc, idpoly, and idgrey models.
1-166
                                                                                                    canon
The companion canonical form is the same as the observable canonical form. For information on
controllable and observable canonical forms, see “Canonical State-Space Realizations”.
• Modal Form
   In modal form, A is a block-diagonal matrix. The block size is typically 1-by-1 for real eigenvalues
   and 2-by-2 for complex eigenvalues. However, if there are repeated eigenvalues or clusters of
   nearby eigenvalues, the block size can be larger.
For example, for a system with eigenvalues (λ1, σ ± jω, λ2), the modal A matrix is of the form
     λ1 0 0 0
     0 σ ω 0
     0 −ω σ 0
     0   0 0 λ2
• Companion Form
   In the companion realization, the characteristic polynomial of the system appears explicitly in the
   rightmost column of the A matrix. For a system with characteristic polynomial
P(s) = sn + α1sn − 1 + … + αn − 1s + αn
       0    0   0   …   0   −αn
       1    0   0   …   0   −αn − 1
       0    1   0   …   0   −αn − 2
    A=
       0    0   1   …   0   −αn − 3
         ⋮ ⋮ ⋮ ⋱ ⋮   ⋮
         0 0 0 … 1 −α1
   The companion transformation requires that the system is controllable from the first input. The
   transformation to companion form is based on the controllability matrix which is almost always
   numerically singular for mid-range orders. Hence, avoid using it when possible.
   The companion canonical form is the same as the observable canonical form. For more
   information on observable and controllable canonical forms, see “Canonical State-Space
   Realizations”.
Increase condt to reduce the size of the eigenvalue clusters in the A matrix of csys. Setting condt
= Inf diagonalizes matrix A.
                                                                                                  1-167
1   Functions
          Output Arguments
          csys — Canonical state-space form of the dynamic model
          ss model object
          Canonical state-space form of the dynamic model, returned as an ss model object. csys is a state-
          space realization of sys in the canonical form specified by type.
          T — Transformation matrix
          matrix
          Transformation matrix, returned as an n-by-n matrix, where n is the number of states. T is the
          transformation between the state vector x of the state-space model sys and the state vector xc of
          csys:
xc = Tx
          Limitations
          • You cannot use frequency-response data models to convert to canonical state-space form.
          • The companion form is poorly conditioned for most state-space computations, that is, the
            transformation to companion form is based on the controllability matrix which is almost always
            numerically singular for mid-range orders. Hence, avoid using it when possible.
          Algorithms
          The canon command uses the bdschur command to convert sys into modal form and to compute
          the transformation T. If sys is not a state-space model, canon first converts it to state space using
          ss.
          The reduction to companion form uses a state similarity transformation based on the controllability
          matrix [1].
          References
          [1] Kailath, T. Linear Systems, Prentice-Hall, 1980.
          See Also
          ctrb | ctrbf | genss | idgrey | idpoly | idproc | idss | idtf | pid | ss | ss2ss | tf | uss | zpk
          Topics
          “Canonical State-Space Realizations”
1-168
                                                                                        chgFreqUnit
chgFreqUnit
Change frequency units of frequency-response data model
Syntax
sys_new = chgFreqUnit(sys,newfrequnits)
Description
sys_new = chgFreqUnit(sys,newfrequnits) changes units of the frequency points in sys to
newfrequnits. Both Frequency and FrequencyUnit properties of sys adjust so that the
frequency responses of sys and sys_new match.
Input Arguments
sys
newfrequnits
• 'rad/TimeUnit'
• 'cycles/TimeUnit'
• 'rad/s'
• 'Hz'
• 'kHz'
• 'MHz'
• 'GHz'
• 'rpm'
rad/TimeUnit and cycles/TimeUnit express frequency units relative to the system time units
specified in the TimeUnit property.
Default: 'rad/TimeUnit'
Output Arguments
sys_new
Frequency-response data model of the same type as sys with new units of frequency points. The
frequency response of sys_new is same as sys.
Examples
                                                                                            1-169
1   Functions
          The data file AnalyzerData has column vectors freq and resp. These vectors contain 256 test
          frequencies and corresponding complex-valued frequency response points, respectively. The default
          frequency units of sys is rad/TimeUnit, where TimeUnit is the system time units.
          The magnitude and phase of sys and sys1 match because chgFreqUnit command changes the
          units of frequency points in sys without modifying system behavior.
          Change the FrequencyUnit property of sys to compare the Bode response with the original system.
          sys2 = sys;
          sys2.FrequencyUnit = 'rpm';
1-170
                                                                                       chgFreqUnit
bodeplot(sys,'r',sys2,'gx');
legend('sys','sys2');
Changing the FrequencyUnit property changes the system behavior. Therefore, the Bode responses
of sys and sys2 do not match. For example, the original corner frequency at about 2 rad/s changes
to approximately 2 rpm (or 0.2 rad/s).
Tips
• Use chgFreqUnit to change the units of frequency points without modifying system behavior.
See Also
chgTimeUnit | frd | idfrd
Topics
“Specify Frequency Units of Frequency-Response Data Model” (Control System Toolbox)
Introduced in R2012a
                                                                                           1-171
1   Functions
          chgTimeUnit
          Change time units of dynamic system
          Syntax
          sys_new = chgTimeUnit(sys,newtimeunits)
          Description
          sys_new = chgTimeUnit(sys,newtimeunits) changes the time units of sys to newtimeunits.
          The time- and frequency-domain characteristics of sys and sys_new match.
          Input Arguments
          sys
newtimeunits
          • 'nanoseconds'
          • 'microseconds'
          • 'milliseconds'
          • 'seconds'
          • 'minutes'
          • 'hours'
          • 'days'
          • 'weeks'
          • 'months'
          • 'years'
Default: 'seconds'
          Output Arguments
          sys_new
          Dynamic system model of the same type as sys with new time units. The time response of sys_new is
          same as sys.
          If sys is an identified linear model, both the model parameters as and their minimum and maximum
          bounds are scaled to the new time units.
1-172
                                                                                        chgTimeUnit
Examples
num = [4 2];
den = [1 3 10];
sys = tf(num,den);
By default, the time unit of sys is 'seconds'. Create a new model with the time units changed to
minutes.
sys1 = chgTimeUnit(sys,'minutes');
This command sets the TimeUnit property of sys1 to 'minutes', without changing the dynamics.
To confirm that the dynamics are unchanged, compare the step responses of sys and sys1.
stepplot(sys,'r',sys1,'y--');
legend('sys','sys1');
If you change the TimeUnit property of the system instead of using chgTimeUnit, the dynamics of
the system do change. To see this, change the TimeUnit property of a copy of sys and compare the
step response with the original system.
                                                                                             1-173
1   Functions
          sys2 = sys;
          sys2.TimeUnit = 'minutes';
          stepplot(sys,'r',sys2,'gx');
          legend('sys','sys2');
          The step responses of sys and sys2 do not match. For example, the original rise time of 0.04 seconds
          changes to 0.04 minutes.
          Tips
          • Use chgTimeUnit to change the time units without modifying system behavior.
          See Also
          chgFreqUnit | frd | idpoly | idproc | idss | idtf | pid | ss | tf | zpk
          Topics
          “Specify Model Time Units” (Control System Toolbox)
Introduced in R2012a
1-174
                                                                                               clone
clone
Copy online parameter estimation System object
Syntax
obj_clone = clone(obj)
Description
obj_clone = clone(obj) creates a copy of the online parameter estimation System object™, obj,
with the same property values. If the object you clone is locked, the new object is also locked.
Note If you want to copy an existing System object and then modify properties of the copied object,
use the clone command. Do not create additional objects using syntax obj2 = obj. Any changes
made to the properties of the new System object created this way (obj2) also change the properties
of the original System object (obj).
Examples
Create a System object™ for online estimation of an ARX model with default properties.
obj = recursiveARX
obj =
  recursiveARX with properties:
                             A:      []
                             B:      []
                      InitialA:      [1 2.2204e-16]
                      InitialB:      [0 2.2204e-16]
           ParameterCovariance:      []
    InitialParameterCovariance:      [2x2 double]
              EstimationMethod:      'ForgettingFactor'
              ForgettingFactor:      1
              EnableAdaptation:      true
                       History:      'Infinite'
               InputProcessing:      'Sample-based'
                      DataType:      'double'
Use clone to generate an object with the same properties as the original object.
obj2 = clone(obj)
obj2 =
  recursiveARX with properties:
                                                                                              1-175
1   Functions
                                         A:    []
                                         B:    []
                                  InitialA:    [1 2.2204e-16]
                                  InitialB:    [0 2.2204e-16]
                       ParameterCovariance:    []
                InitialParameterCovariance:    [2x2 double]
                          EstimationMethod:    'ForgettingFactor'
                          ForgettingFactor:    1
                          EnableAdaptation:    true
                                   History:    'Infinite'
                           InputProcessing:    'Sample-based'
                                  DataType:    'double'
          Input Arguments
          obj — System object for online parameter estimation
          recursiveAR object | recursiveARMA object | recursiveARX object | recursiveARMAX object |
          recursiveOE object | recursiveBJ object | recursiveLS object
System object for online parameter estimation, created using one of the following commands:
          • recursiveAR
          • recursiveARMA
          • recursiveARX
          • recursiveARMAX
          • recursiveOE
          • recursiveBJ
          • recursiveLS
          Output Arguments
          obj_clone — Copy of online estimation System object
          System object
          Copy of online estimation System object, obj, returned as a System object with the same properties
          as obj.
          See Also
          isLocked | recursiveAR | recursiveARMA | recursiveARMAX | recursiveARX | recursiveBJ |
          recursiveLS | recursiveOE | release | reset | step
          Topics
          “What Is Online Estimation?”
Introduced in R2015b
1-176
                                                                                                  clone
clone
Copy online state estimation object
Syntax
obj_clone = clone(obj)
Description
obj_clone = clone(obj) creates a copy of the online state estimation object obj with the same
property values.
If you want to copy an existing object and then modify properties of the copied object, use the clone
command. Do not create additional objects using syntax obj2 = obj. Any changes made to the
properties of the new object created in this way (obj2) also change the properties of the original
object (obj).
Examples
Create an extended Kalman filter object for a van der Pol oscillator with two states and one output. To
create the object, use the previously written and saved state transition and measurement functions,
vdpStateFcn.m and vdpMeasurementFcn.m. Specify the initial state values for the two states as
[2;0].
obj = extendedKalmanFilter(@vdpStateFcn,@vdpMeasurementFcn,[2;0])
obj =
  extendedKalmanFilter with properties:
        HasAdditiveProcessNoise:       1
             StateTransitionFcn:       @vdpStateFcn
    HasAdditiveMeasurementNoise:       1
                 MeasurementFcn:       @vdpMeasurementFcn
     StateTransitionJacobianFcn:       []
         MeasurementJacobianFcn:       []
                          State:       [2x1 double]
                StateCovariance:       [2x2 double]
                   ProcessNoise:       [2x2 double]
               MeasurementNoise:       1
Use clone to generate an object with the same properties as the original object.
obj2 = clone(obj)
obj2 =
  extendedKalmanFilter with properties:
HasAdditiveProcessNoise: 1
                                                                                                1-177
1   Functions
                         StateTransitionFcn:     @vdpStateFcn
                HasAdditiveMeasurementNoise:     1
                             MeasurementFcn:     @vdpMeasurementFcn
                 StateTransitionJacobianFcn:     []
                     MeasurementJacobianFcn:     []
                                      State:     [2x1 double]
                            StateCovariance:     [2x2 double]
                               ProcessNoise:     [2x2 double]
                           MeasurementNoise:     1
obj2.MeasurementNoise = 2;
Verify that the MeasurementNoise property of original object obj remains unchanged and equals 1.
obj.MeasurementNoise
ans = 1
          Input Arguments
          obj — Object for online state estimation
          extendedKalmanFilter object | unscentedKalmanFilter object | particleFilter object
          Object for online state estimation of a nonlinear system, created using one of the following
          commands:
          • extendedKalmanFilter
          • unscentedKalmanFilter
          • particleFilter
          Output Arguments
          obj_clone — Clone of online state estimation object
          extendedKalmanFilter object | unscentedKalmanFilter object | particleFilter object
          See Also
          correct | extendedKalmanFilter | initialize | particleFilter | predict |
          unscentedKalmanFilter
          Topics
          “What Is Online Estimation?”
Introduced in R2016b
1-178
                                                                                           compare
compare
Compare identified model output and measured output
Syntax
compare(data,sys)
compare(data,sys,kstep)
compare(data,sys,LineSpec,kstep)
compare(data,sys1,...,sysN,kstep)
compare(data,sys1,LineSpec1,...,sysN,LineSpecN,kstep)
compare( ___ ,opt)
Description
Plot Results
compare(data,sys) simulates the response of a dynamic system model, and superimposes that
response over plotted measurement data. The plot also displays the normalized root mean square
(NRMSE) measure of the goodness of the fit between simulated response and measurement data. Use
this function when you want to evaluate a set of candidate models identified from the same
measurement data, or when you want to validate a model you have selected. You can use compare
with time-domain or frequency-domain models and data.
compare(data,sys,kstep) also predicts the response of sys, using a prediction horizon specified
by kstep. Prediction uses output measurements as well as input measurements to project a future
response. kstep represents the number of time samples between the timepoint of each output
measurement and the timepoint of the resulting predicted response. For more information on
prediction, see “Simulate and Predict Identified Model Output”.
compare(data,sys,LineSpec,kstep) also specifies the line type, marker symbol, and color for
the model response.
compare( ___ ,opt) configures the comparison using an option set. Options include initial condition
handling, data offsets, and data selection. You can use this syntax with any of the previous input-
argument combinations.
Return Results
[y,fit,x0] = compare( ___ ) returns the model response, y, goodness of fit value, fit, and the
initial states, x0. No plot is generated. You can use this syntax with any of the previous input-
argument combinations. However, line specifications are ignored, because there is no plotting.
                                                                                             1-179
1   Functions
Examples
          Identify a linear model and visualize the simulated model response with the data from which it was
          generated.
Load input/output measurements z1, and identify a third-order state-space model sys.
Use compare to simulate the sys response and plot it alongside the data z1.
          figure
          compare(z1,sys)
          The plot illustrates the differences between the model response and the original data. The percentage
          shown in the legend is the NRMSE fitness value. It represents how close the predicted model output
          is to the data.
To change display options in the plot, right-click the plot to access the context menu. For example:
1-180
                                                                                               compare
• To plot the error between the predicted output and measured output, select Error Plot.
• To view the confidence region for the simulated response, select Characteristics ->
  ConfidenceRegion.
• To specify number of standard deviations to plot, double-click the plot and open the Property
  Editor dialog box. In the Options tab, specify the number of standard deviations in Confidence
  Region for Identified Models. The default value is 1 standard deviation.
Identify a linear model and visualize the predicted model response with the data from which it was
computed.
Now use compare to plot the predicted response. Prediction differs from simulation in that it uses
both measured input and measured output when computing the system response. The prediction
horizon defines how far in the future to predict, relative to your current measured output point. For
this example, set the prediction horizon kstep to 10 steps, and use compare to plot the predicted
response against the original measurement data.
kstep = 10;
compare(z1,sys,kstep)
                                                                                                 1-181
1   Functions
          In this plot, each sys data point represents the predicted output associated with output measurement
          data that was taken at least 10 steps earlier. For instance, the point at t = 15s is based on output
          measurements taken at or prior to t = 5s. The calculation of this t = 15s sys data point also uses
          input measurements up to t = 15s, just as a simulation would.
          The plot illustrates the differences between the model response and the original data. The percentage
          shown in the legend is the NRMSE fitness value. It represents how closely the predicted model output
          matches the data.
          To change display and simulation options in the plot, right-click the plot to access the context menu.
          For example, to plot the error between the predicted output and measured output, select Error Plot
          from the context menu. To change the prediction horizon value, or to toggle between simulation and
          prediction, select Prediction Horizon from the context menu.
          Identify several model types for the same data, and compare the results to see which best fits the
          data.
          Load the data, which contains iddata object z1 with single input and output.
          load iddata1;
From z1, identify a model for each of the following linear forms:
1-182
                                                                                                  compare
Using compare, plot the simulated responses for the three models with z1.
compare(z1,sys_armax,sys_ss,sys_tf)
For this set of data, along with the default settings for all the models, the transfer-function form has
the best NRMSE fit. However, the fits for all models are within about 1% of each other.
You can interactively control which model responses are displayed in the plot by right-clicking on the
plot and hovering over Systems.
Compare the outputs of multiple estimated models of differing types to measured frequency-domain
data.
                                                                                                   1-183
1   Functions
          For this example, estimate a process model and an output-error polynomial from frequency response
          data.
          load demofr % frequency response data
          zfr = AMP.*exp(1i*PHA*pi/180);
          Ts = 0.1;
          data = idfrd(zfr,W,Ts);
          sys1 = procest(data,'P2UDZ');
          sys2 = oe(data,[2 2 1]);
          sys1, an idproc model, is a continuous-time process model. sys2, an idpoly model, is a discrete-
          time output-error model.
          The two models have NRMSE fit values that are nearly equal with respect to the data from which
          they were calculated.
Modify default behavior when you compare an estimated model to measured data.
1-184
                                                                                                   compare
Suppose you want your initial conditions to be zero. The default for compare is to estimate initial
conditions from the data.
Create an option set to specify the initial condition handling. To use zero for initial conditions, specify
'z' for the 'InitialCondition' option.
opt = compareOptions('InitialCondition','z');
Compare the estimated transfer function model output to the measured data using the comparison
option set.
compare(z1,sys,opt)
Input Arguments
data — Validation data
iddata object | idfrd object | frd object
If sys is:
                                                                                                    1-185
1   Functions
          • An iddata object, then data must be an iddata object with matching domain, number of
            experiments and time or frequency vectors
          • A frequency-response data (FRD) model (defined as either idfrd or frd), then data must also be
            FRD
          • A parametric model (such as idss), then data can be iddata or FRD
          data can represent either time-domain or frequency-domain data when comparing with linear
          models. data must be time-domain data when comparing with a nonlinear model.
          • “Compare Predicted Response of Identified Time-Domain Model to Measured Data” on page 1-181
          • “Compare Multiple Estimated Models to Measured Frequency-Domain Data” on page 1-183
Identified model, specified as a dynamic system model, an iddata object, or a model array.
          When the time or frequency units of data do not match the units of sys, compare rescales sys to
          match the units of data.
          compare ignores kstep when sys is an iddata object, an FRD model, or a dynamic system with no
          noise component. compare also ignores kstep when using frequency response validation data.
          If you specify kstep that is greater than the number of data samples, compare sets kstep to Inf
          and provides a warning message.
          For more information on simulation and prediction, see “Simulate and Predict Identified Model
          Output”.
          For an example, see “Compare Predicted Response of Identified Time-Domain Model to Measured
          Data” on page 1-181.
          Line style, marker, and color of both the line and marker, specified as a character vector, such as 'b'
          or 'b+:'.
          For more information about configuring LineSpec, see the Linespec input argument of plot. For
          an example, see “Compare Multiple Estimated Models to Measured Frequency-Domain Data” on page
          1-183.
1-186
                                                                                             compare
• “Compare Estimated Model to Data and Specify Comparison Options” on page 1-184
• “Resolve Fit Value Differences Between Model Identification and compare Command”
Output Arguments
y — Model response
iddata object | idfrd object | cell array | array
Model response, returned as an iddata object, an idfrd object, a cell array, or an array. The output
depends on the models and data you provide, as follows:
• For a single model and single-experiment data set, y is an iddata object or idfrd object
• For multimodel comparisons, y is a cell array with one iddata or idfrd object entry for each
  input model
• For multiexperiment data, y is a cell array with one entry for each experiment
• For multimodel comparisons using multiexperiment data, y is an Nsys-by-Nexp cell array, where Nsys
  is the number of models, and Nexp is the number of experiments
• If sys is a model array, y is an array with an element corresponding to each model in sys and
  experiment in data. For more information on model arrays, see stack
If kstep is not specified or is Inf, then compare returns the simulated response in y.
Otherwise, compare returns the predicted response. Measured output values in data up to time tn-
kstep are used to predict the output of sys at time tn. For more information on simulation and
prediction, see “Simulate and Predict Identified Model Output”.
The compare response computation requires specification of initial condition handling. By default,
compare estimates the initial conditions to maximize the fit to data. See compareOptions for more
information on how compare determines the initial conditions to use.
NRMSE fitness value indicator of how well the simulated or predicted model response matches the
measurement data, returned as a vector, a matrix, or a cell array. The output depends on the models
and data you provide, as follows:
                                                                                              1-187
1   Functions
          • If data is an iddata object, fit is a vector of length Ny, where Ny is the number of outputs
          • If data is an FRD model, fit is an Ny-by-Nu matrix, where Nu is the number of inputs in data
          • For a single model and single-experiment data set, fit is a vector or matrix
          • For multimodel comparisons, fit is a cell array with one entry for each input model
          • For multiexperiment data, fit is a cell array with one entry for each experiment
          • For multimodel comparisons using multiexperiment data, fit is an Nsys-by-Nexp cell array, where
            Nsys is the number of models, and Nexp is the number of experiments
          • If sys is a model array, fit is an array with an element corresponding to each model in sys and
            experiment in data
                                   y−y
                fit = 100 1 −                ,
                                y − mean y
          For FRD models — compare calculates fit by comparing the complex frequency response. The fits
          of the magnitude and phase curves shown in the compare plot are not computed by compare
          separately.
          Initial conditions used to compute system response, returned as an empty array, a vector, or a cell
          array. The output depends on the models and data you provide, as follows:
          • When sys is an frd or iddata object, x0 is the empty array [ ], because initial conditions cannot
            be used with these objects
          • For a single model and single-experiment data set, x0 is a vector
          • For multimodel comparisons, x0 is a cell array, with one vector or matrix entry for each input
            model
          • For multiexperiment data, x0 is a cell array, with one entry for each experiment
          • For multimodel comparisons using multiexperiment data, x0 is an Nsys-by-Nexp cell array, where
            Nsys is the number of models, and Nexp is the number of experiments
          • If sys is a model array, x0 is an array with an element corresponding to each model in sys and
            experiment in data
          By default, compare uses findstates to estimate x0. To change this behavior, set the
          'InitialCondition' option in opt (see compareOptions). If you have input/output history that
          immediately precedes your start point, you can set 'InitialCondition' to that history data.
          compare then uses data2state to compute the end state of the history data, and thus the start
          state for the simulation. Other choices include setting initial conditions to zero, or to specific values
          that you have determined previously. For more information about finding initial conditions, see
          “Estimate Initial Conditions for Simulating Identified Models”.
          If you are using an estimation model that does not explicitly use states, compare first converts the
          model to its state-space representation and then maps the data to states. For more information, see
          compareOptions.
1-188
                                                                                               compare
Tips
• The NRMSE fit result you obtain with compare may not precisely match the fit value reported in
  model identification. These differences typically arise from mismatches in initial conditions, and in
  the differences in the prediction horizon defaults for identification and for validation. The
  differences are generally small, and should not impact your model selection and validation
  workflow. For more information, see “Resolve Fit Value Differences Between Model Identification
  and compare Command”.
• compare matches the input/output channels in data and sys based on the channel names. Thus,
  it is possible to evaluate models that do not use all the input channels that are available in data.
  This flexibility allows you to compare multiple models which were each identified independently
  from different sets of input/output channels.
• The compare plot allows you to vary key parameters. For example, you can interactively control:
To access the controls, right-click the plot to bring up the options menu.
See Also
chgFreqUnit | chgTimeUnit | compareOptions | forecast | goodnessOfFit | plot | predict |
sim
Topics
“Compare Simulated Output with Measured Validation Data”
“Validating Models After Estimation”
“Model Validation”
“Estimate Initial Conditions for Simulating Identified Models”
Introduced in R2006a
                                                                                                 1-189
1   Functions
          compareOptions
          Option set for compare
          Syntax
          opt = compareOptions
          opt = compareOptions(Name,Value)
          Description
          opt = compareOptions creates the default options set for compare.
          opt = compareOptions(Name,Value) creates an option set with the options specified by one or
          more Name,Value pair arguments.
          Input Arguments
          Name-Value Pair Arguments
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Samples
          Specify Samples as a vector containing the data sample indices. For multiexperiment data, use a cell
          array of Ne vectors, where Ne is the number of experiments.
InitialCondition
                For nonlinear grey-box models, only those initial states i that are designated as free in the model
                (sys.InitialStates(i).Fixed = false) are estimated. To estimate all the states of the
                model, first specify all the Nx states of the idnlgrey model sys as free.
                for i = 1:Nx
                sys.InitialStates(i).Fixed = false;
                end
                Similarly, to fix all the initial states to values specified in sys.InitialStates, first specify all
                the states as fixed in the sys.InitialStates property of the nonlinear grey-box model.
1-190
                                                                                        compareOptions
• 'd' — Similar to 'e', but absorbs nonzero delays into the model coefficients. The delays are first
  converted to explicit model states, and the initial values of those states are also estimated and
  returned.
       Field       Description
       Input       Input history, specified as a matrix with Nu columns, where Nu is the number of
                   input channels. For time series models, use []. The number of rows must be
                   greater than or equal to the model order.
       Output      Output history, specified as a matrix with Ny columns, where Ny is the number of
                   output channels. The number of rows must be greater than or equal to the model
                   order.
   For multi-experiment data, configure the initial conditions separately for each experiment by
   specifying InitialCondition as a structure array with Ne elements. To specify the same initial
   conditions for all experiments, use a single structure.
   The software uses data2state to map the historical data to states. If your model is not idss,
   idgrey, idnlgrey, or idnlarx, the software first converts the model to its state-space
   representation and then maps the data to states. If conversion of your model to idss is not
   possible, the estimated states are returned empty.
• x0obj — Specification object created using idpar. Use this object for discrete-time state-space
  (idss and idgrey) and nonlinear grey-box (idnlgrey) models only. Use x0obj to impose
  constraints on the initial states by fixing their value or specifying minimum or maximum bounds.
Default: 'e'
InputOffset
Removes offset from time domain input data for model response computation.
For multiexperiment data, specify InputOffset as a Nu-by-Ne matrix. Nu is the number of inputs
and Ne is the number of experiments.
Each entry specified by InputOffset is subtracted from the corresponding input data.
Default: []
OutputOffset
Removes offset from time-domain output data for model response prediction.
                                                                                                1-191
1   Functions
          For multiexperiment data, specify OutputOffset as a Ny-by-Ne matrix. Ny is the number of outputs
          and Ne is the number of experiments.
          Each entry specified by OutputOffset is subtracted from the corresponding output data before
          computing the model response. After computing the model response, the software adds the offset to
          the response to give the final model response.
Default: []
OutputWeight
          • [] — No weighting is used. This option is the same as using eye(Ny) for the output weight. Ny is
            the number of outputs.
          • 'noise' — Inverse of the noise variance stored with the model.
          • Matrix of doubles — A positive semi-definite matrix of dimension Ny-by-Ny. Ny is the number of
            outputs.
Default: []
          Output Arguments
          opt
Examples
opt = compareOptions;
Create an options set for compare using zero initial conditions. Set the input offset to 5.
opt = compareOptions('InitialCondition','z','InputOffset',5);
1-192
                              compareOptions
opt = compareOptions;
opt.InitialCondition = 'z';
opt.InputOffset = 5;
See Also
compare
Introduced in R2012a
                                     1-193
1   Functions
          correct
          Correct state and state estimation error covariance using extended or unscented Kalman filter, or
          particle filter and measurements
          Syntax
          [CorrectedState,CorrectedStateCovariance] = correct(obj,y)
          [CorrectedState,CorrectedStateCovariance] = correct(obj,y,Um1,...,Umn)
          Description
          The correct command updates the state and state estimation error covariance of an
          extendedKalmanFilter, unscentedKalmanFilter or particleFilter object using measured
          system outputs. To implement extended or unscented Kalman filter, or particle filter, use the correct
          and predict commands together. If the current output measurement exists, you can use correct
          and predict. If the measurement is missing, you can only use predict. For information about the
          order in which to use the commands, see “Using predict and correct Commands” on page 1-201.
          Use this syntax if the measurement function h that you specified in obj.MeasurementFcn has one of
          the following forms:
          Where y(k), x(k), and v(k) are the measured output, states, and measurement noise of the system
          at time step k. The only inputs to h are the states and measurement noise.
Use this syntax if the measurement function h has one of the following forms:
1-194
                                                                                                     correct
correct command passes these inputs to the measurement function to calculate the estimated
outputs.
Examples
Estimate the states of a van der Pol oscillator using an extended Kalman filter algorithm and
measured output data. The oscillator has two states and one output.
Create an extended Kalman filter object for the oscillator. Use previously written and saved state
transition and measurement functions, vdpStateFcn.m and vdpMeasurementFcn.m. These
functions describe a discrete-approximation to a van der Pol oscillator with the nonlinearity
parameter mu equal to 1. The functions assume additive process and measurement noise in the
system. Specify the initial state values for the two states as [1;0]. This is the guess for the state value
at initial time k, based on knowledge of system outputs until time k-1, x[k k − 1].
obj = extendedKalmanFilter(@vdpStateFcn,@vdpMeasurementFcn,[1;0]);
Load the measured output data y from the oscillator. In this example, use simulated static data for
illustration. The data is stored in the vdp_data.mat file.
load vdp_data.mat y
Specify the process noise and measurement noise covariances of the oscillator.
obj.ProcessNoise = 0.01;
obj.MeasurementNoise = 0.16;
Implement the extended Kalman filter algorithm to estimate the states of the oscillator by using the
correct and predict commands. You first correct x[k k − 1] using measurements at time k to get
x[k k]. Then, you predict the state value at the next time step x[k + 1 k] using x[k k], the state
estimate at time step k that is estimated using measurements until time k.
To simulate real-time data measurements, use the measured data one time step at a time. Compute
the residual between the predicted and actual measurement to assess how well the filter is
performing and converging. Computing the residual is an optional step. When you use residual,
place the command immediately before the correct command. If the prediction matches the
measurement, the residual is zero.
After you perform the real-time commands for the time step, buffer the results so that you can plot
them after the run is complete.
for k = 1:size(y)
    [Residual,ResidualCovariance] = residual(obj,y(k));
                                                                                                     1-195
1   Functions
                [CorrectedState,CorrectedStateCovariance] = correct(obj,y(k));
                [PredictedState,PredictedStateCovariance] = predict(obj);
                 residBuf(k,:) = Residual;
                 xcorBuf(k,:) = CorrectedState';
                 xpredBuf(k,:) = PredictedState';
end
          When you use the correct command, obj.State and obj.StateCovariance are updated with
          the corrected state and state estimation error covariance values for time step k, CorrectedState
          and CorrectedStateCovariance. When you use the predict command, obj.State and
          obj.StateCovariance are updated with the predicted values for time step k+1, PredictedState
          and PredictedStateCovariance. When you use the residual command, you do not modify any
          obj properties.
          In this example, you used correct before predict because the initial state value was x[k k − 1], a
          guess for the state value at initial time k based on system outputs until time k-1. If your initial state
          value is x[k − 1 k − 1], the value at previous time k-1 based on measurements until k-1, then use the
          predict command first. For more information about the order of using predict and correct, see
          “Using predict and correct Commands” on page 1-201.
          plot(xcorBuf(:,1), xcorBuf(:,2))
          title('Estimated States')
1-196
                                                                                                 correct
Plot the actual measurement, the corrected estimated measurement, and the residual. For the
measurement function in vdpMeasurementFcn, the measurement is the first state.
M = [y,xcorBuf(:,1),residBuf];
plot(M)
grid on
title('Actual and Estimated Measurements, Residual')
legend('Measured','Estimated','Residual')
The estimate tracks the measurement closely. After the initial transient, the residual remains
relatively small throughout the run.
Load the van der Pol ODE data, and specify the sample time.
vdpODEdata.mat contains a simulation of the van der Pol ODE with nonlinearity parameter mu=1,
using ode45, with initial conditions [2;0]. The true state was extracted with sample time dt =
0.05.
load ('vdpODEdata.mat','xTrue','dt')
tSpan = 0:dt:5;
                                                                                                 1-197
1   Functions
          Get the measurements. For this example, a sensor measures the first state with a Gaussian noise with
          standard deviation 0.04.
          sqrtR = 0.04;
          yMeas = xTrue(:,1) + sqrtR*randn(numel(tSpan),1);
Create a particle filter, and set the state transition and measurement likelihood functions.
myPF = particleFilter(@vdpParticleFilterStateFcn,@vdpMeasurementLikelihoodFcn);
Initialize the particle filter at state [2; 0] with unit covariance, and use 1000 particles.
initialize(myPF,1000,[2;0],eye(2));
          myPF.StateEstimationMethod = 'mean';
          myPF.ResamplingMethod = 'systematic';
Estimate the states using the correct and predict commands, and store the estimated states.
          xEst = zeros(size(xTrue));
          for k=1:size(xTrue,1)
              xEst(k,:) = correct(myPF,yMeas(k));
              predict(myPF);
          end
Plot the results, and compare the estimated and true states.
          figure(1)
          plot(xTrue(:,1),xTrue(:,2),'x',xEst(:,1),xEst(:,2),'ro')
          legend('True','Estimated')
1-198
                                                                                               correct
Consider a nonlinear system with input u whose state x and measurement y evolve according to the
following state transition and measurement equations:
                                2
    y[k] = x[k] + 2 * u[k] + v[k]
The process noise w of the system is additive while the measurement noise v is nonadditive.
Create the state transition function and measurement function for the system. Specify the functions
with an additional input u.
f = @(x,u)(sqrt(x+u));
h = @(x,v,u)(x+2*u+v^2);
f and h are function handles to the anonymous functions that store the state transition and
measurement functions, respectively. In the measurement function, because the measurement noise
is nonadditive, v is also specified as an input. Note that v is specified as an input before the
additional input u.
                                                                                               1-199
1   Functions
          Create an extended Kalman filter object for estimating the state of the nonlinear system using the
          specified functions. Specify the initial value of the state as 1 and the measurement noise as
          nonadditive.
obj = extendedKalmanFilter(f,h,1,'HasAdditiveMeasurementNoise',false);
obj.MeasurementNoise = 0.01;
          You can now estimate the state of the system using the predict and correct commands. You pass
          the values of u to predict and correct, which in turn pass them to the state transition and
          measurement functions, respectively.
Correct the state estimate with measurement y[k]=0.8 and input u[k]=0.2 at time step k.
correct(obj,0.8,0.2)
predict(obj,0.2)
Retrieve the error, or residual, between the prediction and the measurement.
          Input Arguments
          obj — Extended or unscented Kalman filter, or particle filter object
          extendedKalmanFilter object | unscentedKalmanFilter object | particleFilter object
          Extended or unscented Kalman filter, or particle filter object for online state estimation, created using
          one of the following commands:
          Measured system output at the current time step, specified as an N-element vector, where N is the
          number of measurements.
          Additional input arguments to the measurement function of the system, specified as input arguments
          of any type. The measurement function, h, is specified in the MeasurementFcn or
          MeasurementLikelihoodFcn property of obj. If the function requires input arguments in addition
          to the state and measurement noise values, you specify these inputs in the correct command
          syntax. correct command passes these inputs to the measurement or the measurement likelihood
          function to calculate estimated outputs. You can specify multiple arguments.
1-200
                                                                                                    correct
For example, suppose that your measurement or measurement likelihood function calculates the
estimated system output y using system inputs u and current time k, in addition to the state x:
y(k) = h(x(k),u(k),k)
Then when you perform online state estimation at time step k, specify these additional inputs in the
correct command syntax:
[CorrectedState,CorrectedStateCovariance] = correct(obj,y,u(k),k);
Output Arguments
CorrectedState — Corrected state estimate
vector
Corrected state estimate, returned as a vector of size M, where M is the number of states of the
system. If you specify the initial states of obj as a column vector then M is returned as a column
vector, otherwise M is returned as a row vector.
For information about how to specify the initial states of the object, see the
extendedKalmanFilter, unscentedKalmanFilter and particleFilter reference pages.
Corrected state estimation error covariance, returned as an M-by-M matrix, where M is the number
of states of the system.
More About
Using predict and correct Commands
After you have created an extended or unscented Kalman filter, or particle filter object, obj, to
implement the estimation algorithms, use the correct and predict commands together.
At time step k, correct command returns the corrected value of states and state estimation error
covariance using measured system outputs y[k] at the same time step. If your measurement function
has additional input arguments Um, you specify these as inputs to the correct command. The
command passes these values to the measurement function.
[CorrectedState,CorrectedCovariance] = correct(obj,y,Um)
The correct command updates the State and StateCovariance properties of the object with the
estimated values, CorrectedState and CorrectedCovariance.
The predict command returns the prediction of state and state estimation error covariance at the
next time step. If your state transition function has additional input arguments Us, you specify these
as inputs to the predict command. The command passes these values to the state transition
function.
[PredictedState,PredictedCovariance] = predict(obj,Us)
The predict command updates the State and StateCovariance properties of the object with the
predicted values, PredictedState and PredictedCovariance.
                                                                                                    1-201
1   Functions
          If the current output measurement exists at a given time step, you can use correct and predict. If
          the measurement is missing, you can only use predict. For details about how these commands
          implement the algorithms, see “Extended and Unscented Kalman Filter Algorithms for Online State
          Estimation”.
          The order in which you implement the commands depends on the availability of measured data y, Us,
          and Um for your system:
          • correct then predict — Assume that at time step k, the value of obj.State is x [k k − 1]. This
            value is the state of the system at time k, estimated using measured outputs until time k-1. You
            also have the measured output y[k] and inputs Us[k] and Um[k] at the same time step.
                Then you first execute the correct command with measured system data y[k] and additional
                inputs Um[k]. The command updates the value of obj.State to be x [k k], the state estimate for
                time k, estimated using measured outputs up to time k. When you then execute the predict
                command with input Us[k], obj.State now stores x [k + 1 k]. The algorithm uses this state
                value as an input to the correct command in the next time step.
          • predict then correct — Assume that at time step k, the value of obj.State is x [k − 1 k − 1].
            You also have the measured output y[k] and input Um[k] at the same time step but you have
            Us[k-1] from the previous time step.
                Then you first execute the predict command with input Us[k-1]. The command updates the
                value of obj.State to x [k k − 1]. When you then execute the correct command with input
                arguments y[k] and Um[k], obj.State is updated with x [k k]. The algorithm uses this state
                value as an input to the predict command in the next time step.
          Thus, while in both cases the state estimate for time k, x [k k] is the same, if at time k you do not
          have access to the current state transition function inputs Us[k], and instead have Us[k-1], then use
          predict first and then correct.
          For an example of estimating states using the predict and correct commands, see “Estimate
          States Online Using Extended Kalman Filter” on page 1-195 or “Estimate States Online using Particle
          Filter” on page 1-989.
          See Also
          clone | extendedKalmanFilter | initialize | particleFilter | predict | residual |
          unscentedKalmanFilter
          Topics
          “Nonlinear State Estimation Using Unscented Kalman Filter and Particle Filter”
          “Generate Code for Online State Estimation in MATLAB”
          “What Is Online Estimation?”
          “Extended and Unscented Kalman Filter Algorithms for Online State Estimation”
Introduced in R2016b
1-202
                                                                                                       cra
cra
Estimate impulse response using prewhitened-based correlation analysis
Syntax
ir=cra(data)
[ir,R,cl] = cra(data,M,na,plot)
Description
ir=cra(data) estimates the impulse response for the time-domain data, data.
The cra command first computes an autoregressive model for the input u as A(q)u(t) = e(t), where e
is uncorrelated (white) noise, q is the time-shift operator, and A(q) is a polynomial of order na. The
command then filters u and output data y with A(q) to obtain the prewhitened data. The command
then computes and plots the covariance functions of the prewhitened y and u and the cross-
correlation function between them. Positive values of the lag variable then correspond to an influence
from u to later values of y. In other words, significant correlation for negative lags is an indication of
feedback from y to u in the data. A properly scaled version of this correlation function is also an
estimate of the system impulse response. This is also plotted along with 99% confidence levels. The
output argument ir is this impulse response estimate, so that its first entry corresponds to lag zero.
(Negative lags are excluded in ir.) In the plot, the impulse response is scaled so that it corresponds
to an impulse of height 1/T and duration T, where T is the sample time of the data.
Input Arguments
data
Input-output data.
data should contain data for a single-input, single-output experiment. For the multivariate case,
apply cra to two signals at a time, or use impulse.
M specifies the number of lags for which the covariance/correlation functions are computed. These
are from -M to M, so that the length of R is 2M+1. The impulse response is computed from 0 to M.
Default: 20
na
                                                                                                   1-203
1   Functions
Use na = 0 to obtain the covariance and correlation functions of the original data sequences.
Default: 10
plot
Default: 1
          Output Arguments
          ir
The first entry of ir corresponds to lag zero. (Negative lags are excluded in ir.)
Covariance/correlation information.
cl
Examples
Compare a second-order ARX model's impulse response with the one obtained by correlation analysis.
          load iddata1
          z = z1;
          ir = cra(z);
          m = arx(z,[2 2 1]);
          imp = [1;zeros(20,1)];
          irth = sim(m,imp);
          subplot(211)
1-204
                                                                                                cra
plot([ir irth])
title('Impulse Responses')
subplot(212)
plot([cumsum(ir),cumsum(irth)])
title('Step Responses')
Alternatives
An often better alternative to cra is impulseest, which use a high-order FIR model to estimate the
impulse response.
See Also
impulse | impulseest | spa | step
                                                                                             1-205
1   Functions
          customnet
          Custom nonlinearity estimator for nonlinear ARX and Hammerstein-Wiener models
          Syntax
          C=customnet(H)
          C=customnet(H,PropertyName,PropertyValue)
          Description
          customnet is an object that stores a custom nonlinear estimator with a user-defined unit function.
          This custom unit function uses a weighted sum of inputs to compute a scalar output.
          Construction
          C=customnet(H) creates a nonlinearity estimator object with a user-defined unit function using the
          function handle H. H must point to a function of the form [f,g,a] = function_name(x), where f
          is the value of the function, g = df/dx, and a indicates the unit function active range. g is
          significantly nonzero in the interval [-a a]. Hammerstein-Wiener models require that your custom
          nonlinearity have only one input and one output.
          customnet Properties
          You can include property-value pairs in the constructor to specify the object.
          After creating the object, you can use get or dot notation to access the object property values. For
          example:
You can also use the set function to set the value of particular properties. For example:
For example:
customnet(H,'NumberOfUnits',5)
1-206
                                                                                                       customnet
For example:
                                customnet(H,'LinearTerm','on')
Parameters                      A structure containing the parameters in the nonlinear expansion, as follows:
                                Typically, the values of this structure are set by estimating a model with a
                                customnet nonlinearity.
UnitFcn                         Stores the function handle that points to the unit function.
          Examples
          Define custom unit function and save it in gaussunit.m:
                                                                                                          1-207
1   Functions
          Tips
          Use customnet to define a nonlinear function y = F(x), where y is scalar and x is an m-dimensional
          row vector. The unit function is based on the following function expansion with a possible linear term
          L:
where f is a unit function that you define using the function handle H.
          P and Q are m-by-p and m-by-q projection matrices, respectively. The projection matrices P and Q are
          determined by principal component analysis of estimation data. Usually, p=m. If the components of x
          in the estimation data are linearly dependent, then p<m. The number of columns of Q, q, corresponds
          to the number of components of x used in the unit function.
          When used to estimate nonlinear ARX models, q is equal to the size of the NonlinearRegressors
          property of the idnlarx object. When used to estimate Hammerstein-Wiener models, m=q=1 and Q is
          a scalar.
          r is a 1-by-m vector and represents the mean value of the regressor vector computed from estimation
          data.
L is a p-by-1 vector.
          The function handle of the unit function of the custom net must have the form [f,g,a] =
          function_name(x). This function must be vectorized, which means that for a vector or matrix x,
          the output arguments f and g must have the same size as x and be computed element-by-element.
          Algorithms
          customnet uses an iterative search technique for estimating parameters.
          See Also
          evaluate | nlarx | nlhw
          Topics
          “Identifying Nonlinear ARX Models”
          “Identifying Hammerstein-Wiener Models”
Introduced in R2007a
1-208
                                                                                            customreg
customreg
Custom regressor for nonlinear ARX models
Syntax
C=customreg(Function,Variables)
C=customreg(Function,Variables,Delays,Vectorized)
Description
customreg class represents arbitrary functions of past inputs and outputs, such as products, powers,
and other MATLAB expressions of input and output variables.
You can specify custom regressors in addition to or instead of standard regressors for greater
flexibility in modeling your data using nonlinear ARX models. For example, you can define regressors
like tan(u(t-1)), u(t-1)2, and u(t-1)*y(t-3).
For simpler regressor expressions, specify custom regressors directly in the app or in the nlarx
estimation command. For more complex expressions, create a customreg object for each custom
regressor and specify these objects as inputs to the estimation. Regardless of how you specify custom
regressors, the toolbox represents these regressors as customreg objects. Use getreg to list the
expressions of all standard and custom regressors in your model.
A special case of custom regressors involves polynomial combinations of past inputs and outputs. For
example, it is common to capture nonlinearities in the system using polynomial expressions like y(t
−1)2, u(t−1)2, y(t−2)2, y(t−1)*y(t−2), y(t−1)*u(t−1), y(t− 2)*u(t−1). At the command line, use the
polyreg command to generate polynomial-type regressors automatically by computing all
combinations of input and output variables up to a specified degree. polyreg produces customreg
objects that you specify as inputs to the estimation.
The nonlinear ARX model (idnlarx object) stores all custom regressors as the CustomRegressors
property. You can list all custom regressors using m.CustomRegressors, where m is a nonlinear ARX
model. For MIMO models, to retrieve the rth custom regressor for output ky, use
m.CustomRegressors{ky}(r).
Use the Vectorized property to specify whether to compute custom regressors using vectorized
form during estimation. If you know that your regressor formulas can be vectorized, set Vectorized
to 1 to achieve better performance. To better understand vectorization, consider the custom
regressor function handle z=@(x,y)x^2*y. x and y are vectors and each variable is evaluated over a
time grid. Therefore, z must be evaluated for each (xi,yi) pair, and the results are concatenated to
produce a z vector:
for k = 1:length(x)
    z(k) = x(k)^2*y(k)
end
The above expression is a nonvectorized computation and tends to be slow. Specifying a Vectorized
computation uses MATLAB vectorization rules to evaluate the regressor expression using matrices
instead of the FOR-loop and results in faster computation:
                                                                                               1-209
1   Functions
          Construction
          C=customreg(Function,Variables) specifies a custom regressor for a nonlinear ARX model. C is
          a customreg object that stores custom regressor. Function is a function of input and output
          variables. Variables represent the names of model inputs and outputs in the function Function.
          Each input and output name must coincide with the InputName and OutputName properties of the
          corresponding idnlarx object. The size of Variables must match the number of Function inputs.
          For multiple-output models with p outputs, the custom regressor is a p-by-1 cell array or an array of
          customreg object, where the kyth entry defines the custom regressor for output ky. You must add
          these regressors to the model by assigning the CustomRegressors model property or by using
          addreg.
          Properties
          After creating the object, you can use get or dot notation to access the object property values. For
          example:
You can also use the set function to set the value of particular properties. For example:
set(C,'Vectorized',1)
For example:
                                  cr = @(x,y) x*y
Variables                         Cell array of character vectors that represent the names of model input and
                                  output variables in the function Function. Each input and output name must
                                  coincide with the InputName and OutputName properties of the idnlarx
                                  object—the model for which you define custom regressors. The size of
                                  Variables must match the number of Function inputs.
C = customreg(cr,{'y1','u1'},[2 3])
1-210
                                                                                                     customreg
                                 C = customreg(cr,{'y1','u1'},[2 3])
Vectorized                       Assignable values:
Examples
load iddata1
C = {'u1(t-1)*sin(y1(t-3))','u1(t-2)^3'};
m = nlarx(z1,[2 2 1],'linear','CustomRegressors',C);
load iddata1
         m = nlarx(z1,[2 2 1],'linear','CustomRegressors',...
                   {'u1(t-1)*sin(y1(t-3))','u1(t-2)^3'});
load iddata1
                                                                                                        1-211
1   Functions
m = idnlarx([2 2 1]);
m2 = addreg(m,C);
load iddata1
m = nlarx(z1,[2 2 1],'sigmoidnet','CustomReg',C);
          See Also
          addreg | getreg | idnlarx | nlarx | polyreg
          Topics
          “Identifying Nonlinear ARX Models”
Introduced in R2007a
1-212
                                                                                                  d2c
d2c
Convert model from discrete to continuous time
Syntax
sysc = d2c(sysd)
sysc = d2c(sysd,method)
sysc = d2c(sysd,opts)
[sysc,G] = d2c( ___ )
Description
sysc = d2c(sysd) converts a the discrete-time dynamic system model sysd to a continuous-time
model using zero-order hold on the inputs.
[sysc,G] = d2c( ___ ), where sysd is a state-space model, returns a matrix G that maps the
states xd[k] of the discrete-time state-space model to the states xc(t) of sysc.
Examples
                  z−1
       Hz =
              z2 + z + 0 . 3
H = tf([1 -1],[1 1 0.3],0.1);
Hc =
   121.7 s + 1.081e-13
  ---------------------
  s^2 + 12.04 s + 776.7
Discretize the resulting model, Hc, with the default zero-order hold method and sample time 0.1s to
return the original discrete model, H.
c2d(Hc,0.1)
                                                                                               1-213
1   Functions
ans =
                    z - 1
                -------------
                z^2 + z + 0.3
Hc2 = d2c(H,'tustin');
Discretize the resulting model, Hc2, to get back the original discrete-time model, H.
c2d(Hc2,0.1,'tustin');
          load iddata1
          sys1d = tfest(z1,2,'Ts',0.1);
          sys1c = d2c(sys1d,'zoh');
sys2c = tfest(z1,2);
Compare the response of sys1c and the directly estimated continuous-time model, sys2c.
compare(z1,sys1c,sys2c)
1-214
                                                                                                  d2c
load iddata1
sysd = tfest(z1,2,'Ts',0.1);
sysc = d2c(sysd,'zoh');
sys1c has no covariance information. The d2c operation leads to loss of covariance data of identified
models.
Regenerate the covariance information using a zero iteration update with the same estimation
command and estimation data.
opt = tfestOptions;
opt.SearchOptions.MaxIterations = 0;
sys1c = tfest(z1,sysc,opt);
h = bodeplot(sysd,sys1c);
showConfidence(h,3)
                                                                                               1-215
1   Functions
          The uncertainties of sys1c and sysd are comparable up to the Nyquist frequency. However, sys1c
          exhibits large uncertainty in the frequency range for which the estimation data does not provide any
          information.
          If you do not have access to the estimation data, use the translatecov command which is a Gauss-
          approximation formula based translation of covariance across model type conversion operations.
          Input Arguments
          sysd — Discrete-time dynamic system
          dynamic system model
Discrete-time model, specified as a dynamic system model such as idtf, idss, or idpoly.
          You cannot directly use an idgrey model whose FunctionType is 'd' with d2c. Convert the model
          into idss form first.
          • 'zoh' — Zero-order hold on the inputs. Assumes that the control inputs are piecewise constant
            over the sampling period.
1-216
                                                                                                     d2c
• 'foh' — Linear interpolation of the inputs (modified first-order hold). Assumes that the control
  inputs are piecewise linear over the sampling period.
• 'tustin' — Bilinear (Tustin) approximation to the derivative. To specify this method with
  frequency prewarping (formerly known as the 'prewarp' method), use the PrewarpFrequency
  option of d2cOptions.
• 'matched' — Zero-pole matching method (for SISO systems only). See [1] .
For information about the algorithms for each d2c conversion method, see “Continuous-Discrete
Conversion Methods”.
Discrete-to-continuous time conversion options, created using d2cOptions. For example, specify the
prewarp frequency or the conversion method as an option.
Output Arguments
sysc — Continuous-time model
dynamic system model
Continuous-time model, returned as a dynamic system model of the same type as the input system
sysd.
• Includes both the measured and noise components of sysd. If the noise variance is λ in sysd,
  then the continuous-time model sysc has an indicated level of noise spectral density equal to
  Ts*λ.
• Does not include the estimated parameter covariance of sysd. If you want to translate the
  covariance while converting the model, use translatecov.
Mapping of the states xd[k] of the state-space model sysd to the states xc(t) of sysc, returned as
a matrix. The mapping of the states is as follows:
                 xd k
    xc kTs = G           .
                    uk
Given an initial condition x0 for sysd and an initial input u0 = u[0], the corresponding initial
condition for sysc (assuming u[k] = 0 for k < 0 is:
               x0
    xc 0 = G        .
               u0
References
[1] Franklin, G.F., Powell,D.J., and Workman, M.L., Digital Control of Dynamic Systems (3rd Edition),
        Prentice Hall, 1997.
                                                                                                   1-217
1   Functions
          [2] Kollár, I., G.F. Franklin, and R. Pintelon, "On the Equivalence of z-domain and s-domain Models in
                   System Identification," Proceedings of the IEEE® Instrumentation and Measurement
                   Technology Conference, Brussels, Belgium, June, 1996, Vol. 1, pp. 14-19.
          See Also
          c2d | d2cOptions | d2d | logm | translatecov
          Topics
          “Dynamic System Models”
          “Transforming Between Discrete-Time and Continuous-Time Representations”
          “Continuous-Discrete Conversion Methods”
1-218
                                                                                             d2cOptions
d2cOptions
Create option set for discrete- to continuous-time conversions
Syntax
opts = d2cOptions
opts = d2cOptions(Name,Value)
Description
opts = d2cOptions returns the default options for d2c.
opts = d2cOptions(Name,Value) creates an option set with the options specified by one or more
Name,Value pair arguments.
Input Arguments
Name-Value Pair Arguments
method
'zoh'                  Zero-order hold, where d2c assumes that the control inputs are piecewise
                       constant over the sample time Ts.
'foh'                  Linear interpolation of the inputs (modified first-order hold). Assumes that the
                       control inputs are piecewise linear over the sampling period.
'tustin'               Bilinear (Tustin) approximation. By default, d2c converts with no prewarp. To
                       include prewarp, use the PrewarpFrequency option.
'matched'              Zero-pole matching method. (See [1] on page 1-220, p. 224.)
For information about the algorithms for each d2c conversion method, see “Continuous-Discrete
Conversion Methods”.
Default: 'zoh'
PrewarpFrequency
Prewarp frequency for 'tustin' method, specified in rad/TimeUnit, where TimeUnit is the time
units, specified in the TimeUnit property, of the discrete-time system. Specify the prewarp frequency
as a positive scalar value. A value of 0 corresponds to the 'tustin' method without prewarp.
Default: 0
Output Arguments
opts — Option set for d2c
d2cOptions option set
                                                                                                 1-219
1   Functions
Examples
                           z+1
                H(z) =   2
                         z +z+1
Create the discrete-time transfer function with a sample time of 0.1 seconds.
          Specify the discretization method as bilinear (Tustin) approximation and the prewarp frequency as 20
          rad/seconds.
opts = d2cOptions('Method','tustin','PrewarpFrequency',20);
Convert the discrete-time model to continuous-time using the specified discretization method.
Hc = d2c(Hd,opts);
You can use the discretization option set opts to discretize additional models using the same options.
References
          [1] Franklin, G.F., Powell,D.J., and Workman, M.L., Digital Control of Dynamic Systems (3rd Edition),
                  Prentice Hall, 1997.
          See Also
          d2c
Introduced in R2012a
1-220
                                                                                                d2d
d2d
Resample discrete-time model
Syntax
sys1 = d2d(sys, Ts)
sys1 = d2d(sys, Ts, 'method')
sys1 = d2d(sys, Ts, opts)
Description
sys1 = d2d(sys, Ts) resamples the discrete-time dynamic system model sys to produce an
equivalent discrete-time model sys1 with the new sample time Ts (in seconds), using zero-order hold
on the inputs.
sys1 = d2d(sys, Ts, 'method') uses the specified resampling method 'method':
For information about the algorithms for each d2d conversion method, see “Continuous-Discrete
Conversion Methods”.
sys1 = d2d(sys, Ts, opts) resamples sys using the option set with d2dOptions.
Examples
              z − 0.7
       Hz =
              z − 0.5
H = zpk(0.7,0.5,1,0.1);
H2 = d2d(H,0.05)
H2 =
  (z-0.8243)
  ----------
  (z-0.7071)
                                                                                             1-221
1   Functions
H3 = d2d(H2,0.1)
H3 =
                (z-0.7)
                -------
                (z-0.5)
          Suppose that you estimate a discrete-time output-error polynomial model with sample time
          commensurate with the estimation data (0.1 seconds). However, your deployment application
          requires a faster sampling frequency (0.01 seconds). You can use d2d to resample your estimated
          model.
          load iddata1 z1
          z1.Ts
ans = 0.1000
z1 is an iddata object containing the estimation input-output data with sample time 0.1 seconds.
ans = 0.1000
          sys2 = d2d(sys,0.01);
          sys2.Ts
ans = 0.0100
          Tips
          • Use the syntax sys1 = d2d(sys,Ts,'method') to resample sys using the default options for
            'method'. To specify tustin resampling with a frequency prewarp, use the syntax sys1 =
            d2d(sys,Ts,opts). For more information, see d2dOptions.
          • When sys is an identified (IDLTI) model, sys1 does not include the estimated parameter
            covariance of sys. If you want to translate the covariance while converting the model, use
            translatecov.
1-222
                                                     d2d
See Also
c2d | d2c | d2dOptions | translatecov | upsample
                                                   1-223
1   Functions
          d2dOptions
          Create option set for discrete-time resampling
          Syntax
          opts = d2dOptions
          opts = d2dOptions('OptionName', OptionValue)
          Description
          opts = d2dOptions returns the default options for d2d.
This table summarizes the options that the d2d command supports.
          Input Arguments
          Name-Value Pair Arguments
Method
           'zoh'                 Zero-order hold, where d2d assumes that the control inputs are piecewise
                                 constant over the sample time Ts.
           'tustin'              Bilinear (Tustin) approximation. By default, d2d resamples with no prewarp.
                                 To include prewarp, use the PrewarpFrequency option.
          For information about the algorithms for each d2d conversion method, see “Continuous-Discrete
          Conversion Methods”.
Default: 'zoh'
PrewarpFrequency
          Prewarp frequency for 'tustin' method, specified in rad/TimeUnit, where TimeUnit is the time
          units, specified in the TimeUnit property, of the resampled system. Takes positive scalar values. The
          prewarp frequency must be smaller than the Nyquist frequency before and after resampling. A value
          of 0 corresponds to the standard 'tustin' method without prewarp.
Default: 0
Examples
1-224
                                                                                          d2dOptions
Create the following discrete-time transfer function with sample time 0.1 seconds.
                 z+1
      H(z) =   2
               z +z+1
Specify the discretization method as bilinear Tustin method with a prewarping frequency of 20 rad/
seconds.
opts = d2dOptions('Method','tustin','PrewarpFrequency',20);
h2 = d2d(h1,0.05,opts);
You can use the option set opts to resample additional models using the same options.
See Also
d2d
Introduced in R2012a
                                                                                              1-225
1   Functions
          damp
          Natural frequency and damping ratio
          Syntax
          damp(sys)
          [wn,zeta] = damp(sys)
          [wn,zeta,p] = damp(sys)
          Description
          damp(sys) displays the damping ratio, natural frequency, and time constant of the poles of the linear
          model sys. For a discrete-time model, the table also includes the magnitude of each pole. The poles
          are sorted in increasing order of frequency values.
          [wn,zeta] = damp(sys) returns the natural frequencies wn, and damping ratios zeta of the poles
          of sys.
Examples
                           2s2 + 5s + 1
                sys(s) =                .
                           s3 + 2s − 3
sys = tf([2,5,1],[1,0,2,-3]);
Display the natural frequencies, damping ratios, time constants, and poles of sys.
damp(sys)
          The poles of sys contain an unstable pole and a pair of complex conjugates that lie int he left-half of
          the s-plane. The corresponding damping ratio for the unstable pole is -1, which is called a driving
          force instead of a damping force since it increases the oscillations of the system, driving the system
          to instability.
1-226
                                                                                                  damp
For this example, consider the following discrete-time transfer function with a sample time of 0.01
seconds:
              5z2 + 3z + 1
sys(z) =                     .
           z3 + 6z2 + 4z + 4
sys =
     5 z^2 + 3 z + 1
  ---------------------
  z^3 + 6 z^2 + 4 z + 4
Display information about the poles of sys using the damp command.
damp(sys)
The Magnitude column displays the discrete-time pole magnitudes. The Damping, Frequency, and
Time Constant columns display values calculated using the equivalent continuous-time poles.
For this example, create a discrete-time zero-pole-gain model with two outputs and one input. Use
sample time of 0.1 seconds.
sys = zpk({0;-0.5},{0.3;[0.1+1i,0.1-1i]},[1;2],0.1)
sys =
                2 (z+0.5)
   2:      -------------------
                                                                                                1-227
1   Functions
Compute the natural frequency and damping ratio of the zero-pole-gain model sys.
[wn,zeta] = damp(sys)
wn = 3×1
                12.0397
                14.7114
                14.7114
zeta = 3×1
                 1.0000
                -0.0034
                -0.0034
          Each entry in wn and zeta corresponds to combined number of I/Os in sys. zeta is ordered in
          increasing order of natural frequency values in wn.
          For this example, compute the natural frequencies, damping ratio and poles of the following state-
          space model:
                      −2 −1          1 1
                 A=         ,   B=        ,   C= 1 0,    D = 0 1] .
                       1 −2          2 −1
Use damp to compute the natural frequencies, damping ratio and poles of sys.
[wn,zeta,p] = damp(sys)
wn = 2×1
                 2.2361
                 2.2361
zeta = 2×1
0.8944
1-228
                                                                                                   damp
0.8944
p = 2×1 complex
  -2.0000 + 1.0000i
  -2.0000 - 1.0000i
The poles of sys are complex conjugates lying in the left half of the s-plane. The corresponding
damping ratio is less than 1. Hence, sys is an underdamped system.
Input Arguments
sys — Linear dynamic system
dynamic system model
Linear dynamic system, specified as a SISO, or MIMO dynamic system model. Dynamic systems that
you can use include:
damp assumes
   • current values of the tunable components for tunable control design blocks.
   • nominal model values for uncertain control design blocks.
Output Arguments
wn — Natural frequency of each pole
vector
Natural frequency of each pole of sys, returned as a vector sorted in ascending order of frequency
values. Frequencies are expressed in units of the reciprocal of the TimeUnit property of sys.
If sys is a discrete-time model with specified sample time, wn contains the natural frequencies of the
equivalent continuous-time poles. If the sample time is not specified, then damp assumes a sample
time value of 1 and calculates wn accordingly. For more information, see “Algorithms” on page 1-230.
Damping ratios of each pole, returned as a vector sorted in the same order as wn.
If sys is a discrete-time model with specified sample time, zeta contains the damping ratios of the
equivalent continuous-time poles. If the sample time is not specified, then damp assumes a sample
time value of 1 and calculates zeta accordingly. For more information, see “Algorithms” on page 1-
230.
                                                                                                   1-229
1   Functions
          Poles of the dynamic system model, returned as a vector sorted in the same order as wn. p is the
          same as the output of pole(sys), except for the order. For more information on poles, see pole.
          Algorithms
          damp computes the natural frequency, time constant, and damping ratio of the system poles as
          defined in the following table:
          If the sample time is not specified, then damp assumes a sample time value of 1 and calculates zeta
          accordingly.
          See Also
          dsort | eig | esort | pole | pzmap | zero
1-230
                                                                                                data2state
data2state
Map past data to states of state-space and nonlinear ARX models
Syntax
X = data2state(sys,PastData)
[X,XCov] = data2state(sys,PastData)
Description
X = data2state(sys,PastData) maps the past data to the states of a state-space or a nonlinear
ARX model sys. X contains the state values at the time instant immediately after the most recent
data sample in PastData. The software computes the state estimates by minimizing the 1-step ahead
prediction error between predicted response and output signal in PastData.
data2state is useful for continued model simulation. That is, suppose you have simulated a model
up to a certain time instant and would like to then simulate the model for future inputs. Use
data2state to estimate states of the model at the beginning of the second simulation.
Examples
Compute the mapped states of an identified model, and use the states as initial state values for model
simulation.
Now simulate the model using only the first-half of the input signal.
Input1 = Input(1:150);
y_1 = sim(sys,Input1);
Continue the simulation with the second-half of the input signal such that the results show no
discontinuity owing to initial-condition-induced transients. To do so, first construct a past data set
                                                                                                    1-231
1   Functions
          comprising of the input and simulated output from the first-half of the input signal. Then calculate the
          state values corresponding to the start of the second-half of the input signal (t = 151).
          PastData = [y_1,Input1];
          X = data2state(sys,PastData);
          X contains the state values at the time instant immediately after the most recent data sample in
          PastData. This time point is also the start of the future data (second-half of the input signal).
FutureData = Input(151:end);
Simulate the model using the second-half of the input signal and X as initial conditions.
          opt = simOptions('InitialCondition',X);
          y_2 = sim(sys,FutureData,opt);
          plot(y_all,y_2,'r.')
          legend('Simulation using all input data',...
              'Separate simulation of second-half of input data')
1-232
                                                                                             data2state
load iddata1 z1
PastData = z1;
sys2 = idss(sys);
[X,XCov] = data2state(sys2,PastData);
X is the state value at the time instant immediately after the most recent data sample in PastData.
load motorizedcamera;
z = iddata(y,u,0.02,'Name','Motorized Camera','TimeUnit','s');
mw1 = nlarx(z,[ones(2,2),ones(2,6),ones(2,6)],'wavenet');
nx = order(mw1);
X = data2state(mw1,PastData);
X is the state value at the time instant immediately after the most recent data sample in PastData.
Simulate the model using the remaining input data, and specify the initial conditions for simulation.
InputSignal = z.u(nx+1:end,:);
opt = simOptions;
opt.InitialCondition = X;
sim(mw1,InputSignal,opt)
                                                                                                 1-233
1   Functions
          Input Arguments
          sys — Identified model
          idss | idgrey | idnlgrey | idnlarx
Identified model whose current states are estimated, specified as one of the following:
          • iddata object — The number of samples must be greater than or equal to the model order. To
            determine model order, use order.
                When sys is continuous-time, specify PastData as an iddata object. X then corresponds to the
                discretized (c2d) version of the model, where the discretization method is stored in the
                InterSampleproperty of PastData.
1-234
                                                                                            data2state
   • Input — Past input data, specified as an N-by-Nu matrix, where N is great than or equal to the
     model order.
   • Output — Past output data, specified as an N-by-Ny matrix, where N is great than or equal to
     the model order.
The data samples in PastData should be in the order of increasing time. That is, the last row in
PastData should correspond to the latest time.
Output Arguments
X — Mapped states of model
row vector
Mapped states of model, returned as a row vector of size equal to the number of states. X contains
the state value at the time instant immediately after the most recent data sample in PastData. That
is, if PastData is an iddata object, X is the state value at time t =
PastData.SamplingInstants(end)+PastData.Ts.
Estimated covariance of state values, returned as a matrix of size Nx-by-Nx, where Nx is the number
of states.
See Also
findstates | getDelayInfo | idnlarx/findop | order | sim
Introduced in R2008a
                                                                                               1-235
1   Functions
          db2mag
          Convert decibels (dB) to magnitude
          Syntax
          y = db2mag(ydb)
          Description
          y = db2mag(ydb) returns the corresponding magnitude y for a given decibel (dB) value ydb. The
          relationship between magnitude and decibels is ydb = 20 ∗ log10(y).
          See Also
          mag2db
Introduced in R2008a
1-236
                                                                                                 dcgain
dcgain
Low-frequency (DC) gain of LTI system
Syntax
k = dcgain(sys)
Description
k = dcgain(sys) computes the DC gain k of the LTI model sys.
Continuous Time
The continuous-time DC gain is the transfer function value at the frequency s = 0. For state-space
models with matrices (A, B, C, D), this value is
K = D – CA–1B
Discrete Time
The discrete-time DC gain is the transfer function value at z = 1. For state-space models with
matrices (A, B, C, D), this value is
K = D + C(I – A)–1B
Examples
                s−1
              1
             s2 + s + 3
    Hs =
          1     s+2
         s+1    s−3
Compute the DC gain of the transfer function. For continuous-time models, the DC gain is the
transfer function value at the frequency s = 0.
K = dcgain(H)
K = 2×2
    1.0000      -0.3333
    1.0000      -0.6667
The DC gain for each input-output pair is returned. K(i,j) is the DC gain from input j to output i.
                                                                                                 1-237
1   Functions
load iddata1 z1
Estimate a process model from the data. Specify that the model has one pole and a time delay term.
sys = procest(z1,'P1D')
          sys =
          Process model with transfer function:
                       Kp
            G(s) = ---------- * exp(-Td*s)
                    1+Tp1*s
                    Kp = 9.0754
                   Tp1 = 0.25655
                    Td = 0.068
          Parameterization:
              {'P1D'}
             Number of free coefficients: 3
             Use "getpvec", "getcov" for parameters and their uncertainties.
          Status:
          Estimated using PROCEST on time domain data "z1".
          Fit to estimation data: 44.85%
          FPE: 6.02, MSE: 5.901
K = dcgain(sys)
K = 9.0754
sys.Kp
ans = 9.0754
          Tips
          The DC gain is infinite for systems with integrators.
          See Also
          evalfr | norm
Introduced in R2012a
1-238
                                                                                            deadzone
deadzone
Create a dead-zone nonlinearity estimator object
Syntax
NL = deadzone
NL = deadzone('ZeroInterval',[a,b])
Description
NL = deadzone creates a default dead-zone nonlinearity estimator object for estimating
Hammerstein-Wiener models. The interval in which the dead-zone exists (zero interval) is set to [NaN
NaN]. The initial value of the zero interval is determined from the estimation data range, during
estimation using nlhw. Use dot notation to customize the object properties, if needed.
Object Description
deadzone is an object that stores the dead-zone nonlinearity estimator for estimating Hammerstein-
Wiener models.
Use deadzone to define a nonlinear function y = F(x, θ), where y and x are scalars, and θ represents
the parameters a and b, which define the zero interval.
    a ≤ x < b              F(x) = 0
    x < a                   F(x) = x − a
    x ≥ b                   F(x) = x − b
For example, in the following plot, the dead-zone is in the interval [-4,4].
                                                                                               1-239
1   Functions
Examples
NL = deadzone;
NL.ZeroInterval = [-4,5];
          load twotankdata;
          z = iddata(y,u,0.2,'Name','Two tank system');
          z1 = z(1:1000);
Create a deadzone object, and specify the initial guess for the zero-interval.
1-240
                                                                                              deadzone
m = nlhw(z1,[2 3 0],[],OutputNL);
load motorizedcamera;
z = iddata(y,u,0.02,'Name','Motorized Camera','TimeUnit','s');
Orders = [ones(2,6),ones(2,6),ones(2,6)];
InputNL = saturation;
OutputNL = [deadzone,wavenet];
sys = nlhw(z,Orders,InputNL,OutputNL);
To see the shape of the estimated input and output nonlinearities, plot the nonlinearities.
plot(sys)
                                                                                                1-241
1   Functions
Click on the input and output nonlinearity blocks on the top of the plot to see the nonlinearities.
          Input Arguments
          [a,b] — Zero interval
          [NaN NaN] (default) | 2–element row vector
          The dead-zone nonlinearity is initialized at the interval [a,b]. The interval values are adjusted to the
          estimation data by nlhw. To remove the lower limit, set a to -Inf. The lower limit is not adjusted
1-242
                                                                                                deadzone
during estimation. To remove the upper limit, set b to Inf. The upper limit is not adjusted during
estimation.
When the interval is [NaN NaN], the initial value of the zero interval is determined from the
estimation data range during estimation using nlhw.
Example: [-2 1]
Properties
ZeroInterval
Output Arguments
NL — Dead-zone nonlinearity estimator object
deadzone object
See Also
nlhw
Introduced in R2007a
                                                                                                  1-243
1   Functions
          delayest
          Estimate time delay (dead time) from data
          Syntax
          nk = delayest(Data)
          nk = delayest(Data,na,nb,nkmin,nkmax,maxtest)
          Description
          nk = delayest(Data) estimates time delay from data. Data is an iddata object containing the
          input-output data. It can also be an idfrd object defining frequency-response data. Only single-
          output data can be handled. nk is returned as an integer or a row vector of integers, containing the
          estimated time delay in samples from the input(s) to the output in Data.
1-244
                                                                                                detrend
detrend
Subtract offset or trend from time-domain signals contained in iddata objects
Syntax
data_d = detrend(data)
data_d = detrend(data,Type)
[data_d,T_r] = detrend( ___ )
data_d = detrend(data,1,brkpt)
Description
detrend subtracts offsets or linear trends from time-domain input-output data represented in
iddata objects. detrend either computes the trend data to subtract, or subtracts the trend that you
specify.
For a more general detrending function that does not require iddata objects, see detrend.
data_d = detrend(data) computes and subtracts the mean value from each time-domain signal in
data. The iddata objects data_d and data each contain input and output data originating from
SISO, MIMO, or multiexperiment datasets.
data_d = detrend(data,Type) subtracts the trend you specify in Type. You can specify a mean-
value, linear, or custom trend.
[data_d,T_r] = detrend( ___ ) also returns the subtracted trend as a TrendInfo object, T_r.
You can obtain T_r with any of the input-argument combinations in previous syntaxes.
data_d = detrend(data,1,brkpt) computes and subtracts the piecewise-linear trends for data
with segmented trends, using the breakpoints that you define with brkpt.
With this syntax, you cannot retrieve the resulting piecewise-linear trend information as an output.
Examples
Remove biases from steady-state signals in an iddata object by using detrend to compute and
subtract the mean values of the input and output.
Load the input and output time series data y2 and u2. Construct the iddata object data2, using the
data and a sample time of 0.08 seconds.
load dryer2 y2 u2
data2 = iddata(y2,u2,0.08);
                                                                                                1-245
1   Functions
          Use detrend to both compute the mean values and subtract them from input and output signals. Use
          the input argument Tr to store the computed trend information. Plot the original data and detrended
          data together.
          [data2_d,Tr] = detrend(data2);
          plot(data2,data2_d)
          legend('Original Data','Detrended Data')
          The detrended data has shifted by about 5 units. Inspect Tr to obtain the precise mean values that
          detrend computed and subtracted. These values are returned in the InputOffset and
          OutputOffset properties.
Tr
The mean of the original input is higher than the mean of the original output.
1-246
                                                                                              detrend
Remove the linear trend from a signal in an iddata object, and overlay the trendline on a before-
and-after data plot.
Load and plot signal data from the file lintrend2. For this example, only output data is provided in
iddata object dataL.
The plot shows a clear linear trend in the data. Use detrend linear option (Type = 1) to subtract the
trend from the data. detrend fits the data and determines the linear trend to subtract. Include the
TrendInfo object Tr as an output argument so you can see what detrend subtracts.
[dataL_d,Tr] = detrend(dataL,1);
hold on
plot(dataL_d,'g')
legend('Original','Detrended','Location','northwest')
                                                                                               1-247
1   Functions
The linear trend has been removed. Inspect Tr to get more information about the removed trend.
Tr
          The OutputOffset and the OutputSlope properties provide the parameters of the line that
          detrend removed. You can reconstruct this line, and then overlay it on the before-and-after data plot.
          The SamplingInstants property of DataL provides the timepoints associated with the data.
m = Tr.OutputSlope
m = 19.3830
b = Tr.OutputOffset
b = 0.8888
          t = dataL.SamplingInstants;
          TrLn = m*t+b;
          plot(t,TrLn,'r')
          legend('Original','Detrended','Trendline','Location','northwest')
1-248
                                                                                             detrend
Remove known offsets from an input-output signal pair contained in an iddata object.
Detrend can compute and subtract the mean values for input and output signals, resulting in zero-
mean detrended signals. However, if you already know you have specific data offsets beforehand, you
can have detrend subtract these from your signals instead. Specifying the offsets also allows you to
retain a non-zero operating point in the detrend result.
Load SISO data containing vectors u2 and y2. For this example, suppose that you know both signals
have an offset of 4 from the expected operating point of 1. Combine these vectors into an iddata
object, using a sample time of 0.08 seconds, and plot it.
load dryer2 u2 y2
data = iddata(y2,u2,0.08);
plot(data)
                                                                                              1-249
1   Functions
          The known offset of 4 (from operating point 1) is visible in the plots. You can construct a TrendInfo
          object to capture this offset, using the function getTrend.
Create the TrendInfo object, and then set its offset properties.
          T = getTrend(data);
          T.InputOffset = 4;
          T.OutputOffset = 4
Use detrend to subtract the offset from the data. Plot it alongside the original data.
          data_d = detrend(data,T);
          hold on
          plot(data_d)
          legend('Original','Detrended')
1-250
                                                                                                  detrend
Detrend data with segmented piecewise-linear trends by specifying breakpoints to delimit the
segments.
Most of the detrend syntaxes assume and compute a single trend for each of the signals. However,
in some cases there are discontinuities in the linear trends, caused by test configuration changes,
environmental conditions, or other influences. When the signal displays such segmentation, you can
have detrend operate on the test segments independently. To do so, specify breakpoints in the
brkpt input argument. These are the indices to the timepoints in the signal at which linear trends
change slope.
You may know these breakpoints up front, based on changes that you know occurred during data
collection. Alternatively, you may need to approximate them by inspecting the data itself.
Load the data, inspect its structure and contents, and plot it. This data consists of output data only in
the iddata object dataLb2.
load brkTrend dataLb2
dataLb2
dataLb2 =
                                                                                                   1-251
1   Functions
plot(dataLb2)
          For this example, the data has known breakpoints at indices [100 300]. Applying the sample time
          (property Ts), these breakpoints correspond to the actual timepoints as follows:
          brkpt=[100 300];
          brkpt_time = brkpt*dataLb2.Ts
brkpt_time = 1×2
0.3906 1.1719
dataLb2_d = detrend(dataLb2,1,brkpt);
          plot(dataLb2,dataLb2_d)
          legend('Original Data','Detrended Data')
1-252
                                                                                             detrend
Apply a unique set of breakpoints to each experiment when you detrend a Multiexperiment dataset.
Experiments within a multiexperiment dataset may contain unique linear trending discontinuities.
You can apply a unique set of breakpoints to each experiment by expressing them in a cell array.
datmult =
Time domain data set containing 3 experiments.
                                                                                               1-253
1   Functions
exp3 350 1
bp1,bp2,bp3
bp1 = 1×2
50 200
bp2 = 100
bp3 =
[]
          Plot the data. There are significant differences among the streams, and they drift at different rates
          from zero mean.
          plot(datmult)
          legend
          For this set of experiments, it is known that there is unique trending for each run and unique
          discontinuities indicated by the bp vectors.
1-254
                                                                                               detrend
detrend can incorporate these unique characteristics if the bp information is provided as a cell
array.
Apply detrend and plot the result, using the same scale as the original plot.
datmult_d = detrend(datmult,1,bpcell);
figure
plot(datmult_d)
axis([0,inf,-15,30])
legend
The experimental data are now better aligned, and do not drift significantly away from zero mean.
Apply different trend types to the input and output signals contained in an iddata object.
                                                                                               1-255
1   Functions
          Detrend assumes that the same type of trend applies to both input and output signals. In some
          cases, there may be a trend type that is present in only one signal. You can perform detrend
          individually on each signal by extracting the signals into separate iddata objects. Apply detrend to
          each object using its individual signal trend type. Then reassemble the results back into a single
          detrended iddata object.
iodatab =
          plot(iodatab)
          hold on
          Both input and output plots show a bias. However, the output plot also shows an inverted V-shape
          trend that is not present in the input data.
1-256
                                                                                             detrend
Separate the input data and the output data into separate objects for detrending, using the iddata
general data-selection form (see “Representing Time- and Frequency-Domain Data Using iddata
Objects”):
data(samples,outputchannels,inputchannels)
idatab = iodatab(:,[],:);
odatab = iodatab(:,:,[]);
Remove the bias from the input data, using detrend to calculate and subtract the mean.
idatab_d = detrend(idatab,0);
Remove the bias and the inverted-V trend from the output data, using the midpoint index 500 as a
breakpoint.
odatab_d = detrend(odatab,1,500);
Combine the detrended input and output data into a single iddata object.
iodatab_d = [odatab_d,idatab_d];
The input and output data now contain neither bias nor V-shape trend.
                                                                                              1-257
1   Functions
          Input Arguments
          data — Time-domain input-output data
          iddata object
          Specified as an iddata object containing one or more sets of time-domain signals. The iddata
          object can contain SISO, MIMO, or multiexperiment data. The signal sets can contain either input and
          output data, or output data only.
          • An integer row vector — For single-experiment SISO and MIMO datasets. Doing so applies a
            single set of breakpoints to all input and output signals. For an example, see “Remove Segmented
            Linear Trends from Signals by using Breakpoints” on page 1-251.
          • A cell array containing individually-sized integer row vectors — For multiple-experiment datasets.
            Doing so applies a unique set of breakpoints to the output and input signals for each experiment.
            For an example, see “Detrend Multiexperiment Signals using Multiple-Breakpoint Sets” on page 1-
            253.
          Output Arguments
          data_d — Detrended signals
          iddata object
          Detrended signals, returned as an iddata object. Dimensions of the contents are the same as
          dimensions of the contents of data.
Trend data subtracted from data to produce data_d, returned as a TrendInfo object .
When you use brkpt to specify multiple trends, you cannot retrieve the computed trend data.
          See Also
          getTrend | iddata | idfilt | retrend
1-258
                           detrend
                           1-259
1   Functions
          diff
          Difference signals in iddata objects
          Syntax
          zdi = diff(z)
          zdi = diff(z,n)
          Description
          zdi = diff(z) and zdi = diff(z,n) return the difference signals in iddata objects. z is a time-
          domain iddata object. diff(z) and diff(z,n) apply this command to each of the input/output
          signals in z.
1-260
                                                                                  Estimate Process Model
Description
The Estimate Process Model task lets you interactively estimate and validate a process model for
SISO systems. You can define and vary the model structure and specify optional parameters, such as
initial condition handling and search methods. The task automatically generates MATLAB code for
your live script. For more information about Live Editor tasks generally, see “Add Interactive Tasks to
a Live Script” (MATLAB).
Process models are simple continuous-time transfer functions that describe the linear system
dynamics. Process model elements include static gain, time constants, time delays, integrator, and
process zero.
Process models are popular for describing system dynamics in numerous industries and are
applicable to various production environments. The advantages of these models are that they are
simple, they support transport delay estimation, and the model coefficients are easy to interpret as
poles and zeros. For more information about process model estimation, see “What Is a Process
Model?”
The Estimate Process Model task is independent of the more general System Identification app.
Use the System Identification app when you want to compute and compare estimates for multiple
model structures.
To get started, load experiment data that contains input and output data into your MATLAB
workspace and then import that data into the task. Then select a model structure to estimate. The
task gives you controls and plots that help you experiment with different model structures and
compare how well the output of each model fits the measurements.
Related Functions
The code that Estimate Process Model generates uses the following functions.
• iddata
• idfrd
   frd
• procest
• procestOptions
• compare
The code that Estimate Process Model generates uses the following functions.
                                                                                                 1-261
1   Functions
          • iddata
          • idfrd
                frd
          • procest
          • procestOptions
          • compare
          • On the Live Editor tab, select Task > Estimate Process Model.
          • In a code block in your script, type a relevant keyword, such as process or estimate. Select
            Estimate Process Model from the suggested command completions.
Examples
          Use the Estimate Process Model Live Editor Task to estimate a state-space model and compare the
          model output to the measurement data.
Set Up Data
          load iddata1 z1
          z1
z1 =
In the Select data section, set Data Type to Data Object and set Estimation Object to z1.
1-262
                                                                                Estimate Process Model
The data object contains the input and output variable names as well as the sample time, so you do
not have to specify them.
                                                                                               1-263
1   Functions
          In the Specify model structure section, the default option is One Pole with no delay, zero, or
          integrator. Equations below the parameters in this section display the specified structure.
          In the Specify estimation initialization section, initialization parameters matching the parameters
          in your model structure allow you to set starting points for estimation. If you select Fix, the
          parameter remains fixed to the value you specify. For this example, do not specify initialization. The
          task then uses default values for starting points.
In the Specify optional parameters section, the default options for process estimation are set.
          Execute the task from the Live Editor tab using Run. A plot displays the estimation data, the
          estimated model output, and the fit percentage.
Experiment with the parameter settings and see how they influence the fit.
For instance, add delay to the One Pole structure and run the task.
1-264
                                                                               Estimate Process Model
The estimation fit improves, although the fit percentage is still below 50%.
Try a different model structure. In Specify model structure, select Underdamped Pair with no
delay and run the task.
                                                                                              1-265
1   Functions
Generate Code
          To display the code that the task generates, click   at the bottom of the parameter section. The
          code that you see reflects the current parameter configuration of the task.
Use separate estimation and validation data so that you can validate the estimated process model.
1-266
                                                                                    Estimate Process Model
Set Up Data
Load the measurement data iddata1 into your MATLAB workspace and examine its contents.
load iddata1 z1
z1
z1 =
u = z1.u;
y = z1.y;
Split the data into two sets, with one half for estimation and one half for validation. The original data
set has 300 samples, so each new data set has 150 samples.
u_est    =   u(1:150);
u_val    =   u(151:300);
y_est    =   y(1:150);
y_val    =   y(151:300);
In the Select data section, set Data Type to Time. Set the sample time to 0.1 seconds, which is the
sample time in the original iddata object z1. Select the appropriate data sets for estimation and
validation.
                                                                                                   1-267
1   Functions
          The example “Estimate Process Model with Live Editor Task” on page 1-262 achieves the best results
          using the model structure Underdamped Pair. Choose the same option for this example.
          Execute the task from the Live Editor tab using Run. Executing the task creates two plots.The first
          plot shows the estimation results and the second plot shows the validation results.
1-268
Estimate Process Model
               1-269
1   Functions
          The fit to the estimation data is somewhat worse than in “Estimate Process Model with Live Editor
          Task” on page 1-262. Estimation in the current example has only half the data with which to estimate
          the model. The fit to the validation data, which represents the goodness of the model more generally,
          is better than the fit to the estimation data.
          Parameters
          Select Data
          The task accepts single-channel numeric measurement values that are uniformly sampled in time.
          Data can be packaged as numeric arrays (Time or Frequency type) or in a data object, such as an
          iddata or idfrd object.
The data type you choose determines the additional parameters you must specify.
          • Time — Specify Sample Time and Start Time in the time units that you select.
          • Frequency — Specify Frequency by selecting the variable name of a frequency vector in your
            MATLAB workspace. Specify the units for this frequency vector. Specify Sample Time in seconds.
          • Data Object — Specify no additional parameters, because the data object already contains
            information on time or frequency sampling.
          Estimation Input and Estimation Output — Variable names of input and output data
          for estimation
          valid variable names
          Select the input and output variable names from the MATLAB workspace choices. Use these
          parameters when Data Type is Time or Frequency.
          Estimation Object — Variable name of data object containing input and output data to be
          used for estimation
          valid variable name
          Select the data object variable name from the MATLAB workspace choices. Use this parameter when
          Data Type is Data Object.
          Validation Input (u) and Validation Output (y) — Variable names of input and
          output data to be used for validation
          valid variable names
          Select the input and output variable names, or the data object name, from the workspace choices.
          Use these parameters when Data Type is Time or Frequency. Specifying validation data is optional
          but recommended.
          Validation Object — Variable name of data object containing input and output data for
          validation
          valid variable name
          Select the data object variable name from the MATLAB workspace choices. Use this parameter when
          Data Type is Data Object. Specifying validation data is optional but recommended.
1-270
                                                                                   Estimate Process Model
The task allows you to specify one of four basic structures. These structures range from a simple first-
order process to a more dynamic second-order or third-order process with complex conjugate
(underdamped) poles.
• One Pole
• Two Real Poles
• Underdamped Pair
• Underdamped Pair + Real Pole
Include transport delay, or input-to-output delay, of one sample. The transport delay is also known as
dead time.
Specify initial values for the estimation and whether these values are to be fixed or estimated. The
values to specify depend on the model structure and your specifications for Delay and Zero. Below
Specify model structure, the task displays the equation that represents the specified system. This
equation contains all of the parameters that can be estimated, and that you can initialize or fix. The
possible parameters are:
• Kp — Static gain
• Tp1 — Time constant for first real pole
• Tp2 — Time constant for second real pole
• Tω — Time constant for complex poles, equal to the inverse of the natural frequency
• ζ — Damping coefficient for complex poles
• Td — Transport delay
• Tz — Time constant for the process zero
All time-based parameters are in the time units you select for Sample Time.
                                                                                                  1-271
1   Functions
Fit focus specifies what error to minimize in the loss function during estimation.
          • Prediction — Minimize the one-step-ahead prediction error between measured and predicted
            outputs. This estimation approach focuses on producing a good predictor model for the estimation
            inputs and outputs. Prediction focus generally produces the best estimation results because it
            uses both input and output measurements, thus accounting for disturbances.
          • Simulation — Minimize the error between measured and simulation outputs. This estimation
            approach focuses on producing a simulated model response that has a good fit with the estimation
            inputs and outputs. Simulation focus is generally best for validation, especially with data sets not
            used for the original estimation.
          Set this option when you want to choose a specific method for initializing the model. With the default
          setting of Auto, the software chooses the method based on the estimation data. Choices are:
          Input intersampling is a property of the input data. The task uses this property when estimating
          process models. Specify Input Intersampling when your data type is Time or Frequency. If you
          are using an iddata object, the object already contains the intersampling information. Choices for
          this property are:
          • Auto — For each iteration, the software cycles through the methods until it finds the first
            direction descent that leads to a reduction in estimation cost.
          • Gauss-Newton — Subspace Gauss-Newton least-squares search.
          • Levenberg-Marquardt — Levenberg-Marquardt least-squares search.
          • Adaptive Gauss-Newton —Adaptive subspace Gauss-Newton search.
          • Gradient Search — Steepest descent least-squares search.
1-272
                                                                                  Estimate Process Model
Set the maximum number of iterations during error minimization. The iterations stop when Max.
Iterations is reached or another stopping criterion is satisfied, such as Tolerance.
When the percentage of expected improvement is less than Tolerance, the iterations stop.
Set this option when you want to apply a weighting prefilter to the loss function that the task
minimizes when you estimate the model. When you select an option, you must also select the
associated variable in your workspace that contains the filter information. The available options
depend on the domain of the data.
For instance, suppose that you are performing estimation with SISO frequency-domain data and that
in your MATLAB workspace, you have a column vector W that contains frequency weights for the
prefilter. In the task, select Weighting prefilter > Frequency weights vector and the variable W.
Visualize Results
Plot a comparison of the model output and the original measured data, along with the fit percentage.
If you have separate validation data, a second plot compares the model response to the validation
input data with the measured output from the validation data set.
See Also
compare | frd | iddata | idfrd | idproc | procest | procestOptions
Introduced in R2019b
                                                                                                    1-273
1   Functions
          Description
          The Estimate State-Space Model task lets you interactively estimate and validate a state-space
          model using time or frequency data. You can define and vary the model structure and specify optional
          parameters, such as initial condition handling and search method. The task automatically generates
          MATLAB code for your live script. For more information about Live Editor tasks generally, see “Add
          Interactive Tasks to a Live Script” (MATLAB).
          State-space models are models that use state variables to describe a system by a set of first-order
          differential or difference equations, rather than by one or more nth-order differential or difference
          equations. State variables can be reconstructed from the measured input-output data, but are not
          themselves measured during the experiment.
          The state-space model structure is a good choice for quick estimation because it requires you to
          specify only one input, the model order. For more information about state-space estimation, see
          “What Are State-Space Models?”
          The Estimate State-Space Model task is independent of the more general System Identification
          app. Use the System Identification app when you want to compute and compare estimates for
          multiple model structures.
          To get started, load experiment data that contains input and output data into your MATLAB
          workspace and then import that data into the task. Then specify a model structure to estimate. The
          task gives you controls and plots that help you experiment with different model parameters and
          compare how well the output of each model fits the measurements.
Related Functions
The code that Estimate State-Space Model generates uses the following functions.
          • iddata
          • idfrd
                frd
          • ssest
          • ssestOptions
          • compare
The code that Estimate State-Space Model generates uses the following functions.
1-274
                                                                          Estimate State-Space Model
• iddata
• idfrd
   frd
• ssest
• ssestOptions
• compare
• On the Live Editor tab, select Task > Estimate State-Space Model.
• In a code block in your script, type a relevant keyword, such as state, space, or estimate.
  Select Estimate State Space Model from the suggested command completions.
Examples
Use the Estimate State-Space Model Live Editor Task to estimate a state-space model and compare
the model output to the measurement data.
Set Up Data
load iddata1 z1
z1
z1 =
In the Select data section, set Data Type to Data Object and set Estimation Object to z1.
                                                                                             1-275
1   Functions
          The data object contains the input and output variable names as well as the sample time, so you do
          not have to specify them.
          In the Specify model structure section, the plant order is set to its default value of 4 and the model
          is in the continuous-time domain. Equations below the parameters in this section display the specified
          structure.
          In the Specify optional parameters section, parameters display the default options for state-space
          estimation.
1-276
                                                                             Estimate State-Space Model
Execute the task from the Live Editor tab using Run. A plot displays the estimation data, the
estimated model output, and the fit percentage.
Experiment with the parameter settings and see how they influence the fit.
For instance, in Specify model structure, the Estimate disturbance box is selected, so the
disturbance matrix K is present in the equations. If you clear the box, the K term disappears. Run the
updated configuration, and see how the fit changes.
                                                                                                1-277
1   Functions
Change the Plant Order setting to Pick best value in range. The default setting is 1:10.
          When you run the model, a Model Order Selection plot displays the contribution of each state to
          the model dynamic behavior. With the initial task settings for the other parameters, the plot displays
          a recommendation of 2 for the model order.
1-278
                                                                            Estimate State-Space Model
Accept this recommendation by clicking Apply, and see how this change affects the fit.
                                                                                               1-279
1   Functions
Generate Code
          To display the code that the task generates, click   at the bottom of the parameter section. The
          code that you see reflects the current parameter configuration of the task.
1-280
                                                                                Estimate State-Space Model
Use separate estimation and validation data so that you can validate the estimated state-space model.
Set Up Data
Load measurement data iddata1 into your MATLAB workspace and examine its contents.
load iddata1 z1
z1
z1 =
u = z1.u;
y = z1.y;
Split the data into two sets, with one half for estimation and one half for validation. The original data
set has 300 samples, so each new data set has 150 samples.
u_est    =   u(1:150);
u_val    =   u(151:300);
y_est    =   y(1:150);
y_val    =   y(151:300);
In the Select data section, set Data Type to Time. Set Sample Time to 0.1 seconds, which is the
sample time in the original iddata object z1. Select the appropriate data sets for estimation and
validation.
                                                                                                   1-281
1   Functions
          The example “Estimate State-Space Model with Live Editor Task” on page 1-275 recommends a
          model order of 2. Use that value for Plant Order. Leave other parameters at their default values.
          Note that Input Channel refers not to the input data set, but to the channel index within the input
          data set, which for a single-input system is always u1.
          Execute the task from the Live Editor tab using Run. Executing the task creates two plots. The first
          plot shows the estimation results and the second plot shows the validation results.
1-282
Estimate State-Space Model
                   1-283
1   Functions
          The fit to the estimation data is somewhat worse than in “Estimate State-Space Model with Live
          Editor Task” on page 1-275. Estimation in the current example has only half the data with which to
          estimate the model. The fit to the validation data, which represents the goodness of the model more
          generally, is better than the fit to the estimation data.
          Parameters
          Select Data
          The task accepts numeric measurement values that are uniformly sampled in time. Input and output
          signals can contain multiple channels. Data can be packaged as numeric arrays (for Time or
          Frequency) or in a data object, such as an iddata or idfrd object.
The data type you choose determines whether you must specify additional parameters.
          • Time — Specify Sample Time and Start Time in the time units that you select.
          • Frequency — Specify Frequency by selecting the variable name of a frequency vector in your
            MATLAB workspace. Specify the units for this frequency vector. Specify Sample Time in seconds.
          • Data Object — Specify no additional parameters because the data object already contains
            information on time or frequency sampling.
          Estimation Input (u) and Estimation Output (y) — Variable names of input and
          output data for estimation
          valid variable names
          Select the input and output variable names from the MATLAB workspace choices. Use these
          parameters when Data Type is Time or Frequency.
          Estimation Object — Variable name of data object containing input and output data for
          estimation
          valid variable name
          Select the data object variable name from the MATLAB workspace choices. Use this parameter when
          Data Type is Data Object.
          Validation Input (u) and Validation Output (y) — Variable names of input and
          output data for validation
          valid variable names
          Select the input and output variable names from the workspace choices. Use these parameters when
          Data Type is Time or Frequency. Specifying validation data is optional but recommended.
          Validation Object — Variable name of data object containing input and output data for
          validation
          valid variable name
          Select the data object variable name from the MATLAB workspace choices. Use this parameter when
          Data Type is Data Object. Specifying validation data is optional but recommended.
1-284
                                                                               Estimate State-Space Model
The task allows you to specify a single value or a range of values for the order of the model to
estimate.
Select this option to estimate the disturbance model. When you select this option, the model
equations update to show the K matrix and e term.
For each input channel, assign values for Input Delay and Feedthrough.
• Input Channel — Select an input channel. The input channel is always of the form ui, where i is
  the ith channel of the input u.
• Input Delay — Enter the input delay in number of samples (discrete-time model) or number of
  time units (continuous-time model) for the channel. For instance, to specify a 0.2-second input
  delay for a continuous-time system for which the time unit is milliseconds, enter 200.
• Feedthrough — Select this option to estimate channel feedthrough from input to output. When
  you select this option, the model equations update to show the Du term.
Fit focus specifies what error to minimize in the loss function during estimation.
• Prediction — Minimize the one-step-ahead prediction error between measured and predicted
  outputs. This estimation approach focuses on producing a good predictor model for the estimation
  inputs and outputs. Prediction focus generally produces the best estimation results because it
  uses both input and output measurements, thus accounting for disturbances.
• Simulation — Minimize the error between measured and simulated outputs. This estimation
  approach focuses on producing a simulated model response that has a good fit with the estimation
  inputs and outputs. Simulation focus is generally best for validation, especially with data sets not
  used for the original estimation.
                                                                                                   1-285
1   Functions
          Set this option when you want to choose a specific method for initializing the model states. With the
          default setting of Auto, the software chooses the method based on the estimation data. Choices are:
          Input intersampling is a property of the input data. The task uses this property when estimating
          continuous models. Specify Input Intersampling when your data type is Time or Frequency. If you
          are using an iddata object, the object already contains the intersampling information. Choices for
          this property are:
          • Auto — For each iteration, the software cycles through the methods until it finds the first
            direction descent that leads to a reduction in estimation cost.
          • Gauss-Newton — Subspace Gauss-Newton least-squares search.
          • Levenberg-Marquardt — Levenberg-Marquardt least-squares search.
          • Adaptive Gauss-Newton —Adaptive subspace Gauss-Newton search.
          • Gradient Search — Steepest descent least-squares search.
          Set the maximum number of iterations during error minimization. The iterations stop when Max.
          Iterations is reached or another stopping criterion is satisfied, such as Tolerance.
When the percentage of expected improvement is less than Tolerance, the iterations stop.
          Set this option when you want to apply a weighting prefilter to the loss function that the task
          minimizes when you estimate the model. When you select an option, you must also select the
1-286
                                                                              Estimate State-Space Model
associated variable in your workspace that contains the filter information. The available options
depend on the domain of the data.
For instance, suppose that you are performing estimation with SISO frequency-domain data and that
in your MATLAB workspace, you have a column vector W that contains frequency weights for the
prefilter. In the task, select Weighting prefilter > Frequency weights vector and the variable W.
Visualize Results
Plot a comparison of the model output and the original measured data, along with the fit percentage.
If you have separate validation data, a second plot compares the model response to the validation
input data with the measured output from the validation data set.
See Also
compare | frd | iddata | idfrd | idss | ssest | ssestOptions
Topics
“What Are State-Space Models?”
Introduced in R2019b
                                                                                                    1-287
1   Functions
          etfe
          Estimate empirical transfer functions and periodograms
          Syntax
          g = etfe(data)
          g = etfe(data,M)
          g = etfe(data,M,N)
          Description
          g = etfe(data) estimates a transfer function of the form:
          • If data is time-domain input-output signals, g is the ratio of the output Fourier transform to the
            input Fourier transform for the data.
                For nonperiodic data, the transfer function is estimated at 128 equally-spaced frequencies
                [1:128]/128*pi/Ts.
                For periodic data that contains a whole number of periods (data.Period = integer ), the
                response is computed at the frequencies k*2*pi/period for k = 0 up to the Nyquist frequency.
          • If data is frequency-domain input-output signals, g is the ratio of output to input at all
            frequencies, where the input is nonzero.
          • If data is time-series data (no input channels), g is the periodogram, that is the normed absolute
            square of the Fourier transform, of the data. The corresponding spectral estimate is normalized,
            as described in “Spectrum Normalization” and differs from the spectrum normalization in the
            Signal Processing Toolbox™ product.
          g = etfe(data,M) applies a smoothing operation on the raw spectral estimates using a Hamming
          Window that yields a frequency resolution of about pi/M. The effect of M is similar to the effect of M in
          spa. M is ignored for periodic data. Use this syntax as an alternative to spa for narrowband spectra
          and systems that require large values of M.
          • For nonperiodic time-domain data, N specifies the frequency grid [1:N]/N*pi/Ts rad/TimeUnit.
            When not specified, N is 128.
          • For periodic time-domain data, N is ignored.
          • For frequency-domain data, the N is fmin:delta_f:fmax, where [fmin fmax] is the range of
            frequencies in data, and delta_f is (fmax-fmin)/(N-1) rad/TimeUnit. When not specified, the
            response is computed at the frequencies contained in data where input is nonzero.
Examples
1-288
                                                                                                  etfe
Generate a periodic input, simulate a system with it, and compare the frequency response of the
estimated model with the original system at the excited frequency points.
                                                                                              1-289
1   Functions
me = etfe([y u]);
bode(me,'b*',m,'r')
          Perform a smoothing operation on raw spectral estimates using a Hamming Window and compare the
          responses.
Load data.
load iddata1
Estimate empirical transfer functions with and without the smoothing operation.
          ge1 = etfe(z1);
          ge2 = etfe(z1,32);
ge2 is smoother than ge1 because of the effect of the smoothing operation.
1-290
                                                                                                etfe
bode(ge1,ge2)
Estimate empirical transfer functions with low- and high-frequency spacings and compare the
responses.
Load data.
load iddata9
Estimate empirical transfer functions with low and high frequency spacings.
ge1 = etfe(z9,[],32);
ge2 = etfe(z9,[],512);
spectrum(ge1,'b.-',ge2,'g')
                                                                                              1-291
1   Functions
          Input Arguments
          data — Estimation data
          iddata
          Estimation data, specified as an iddata object. The data can be time- or frequency-domain input/
          output signals or time-series data.
          M — Frequency resolution
          [] (default) | positive scalar
          N — Frequency spacing
          128 for nonperiodic time-domain data (default) | positive scalar
          Frequency spacing, specified as a positive scalar. For frequency-domain data, the default frequency
          spacing is the spacing inherent in the estimation data.
          Output Arguments
          g — Transfer function estimate
          idfrd
1-292
                                                                                                  etfe
Information about the estimation results and options used is stored in the model's Report property.
Report has the following fields:
                            Field     Description
                            Name      Name of the data set.
                            Type      Data type.
                            Length    Number of data samples.
                            Ts        Sample time.
                            InterSa Input intersample behavior, returned as one of the following
                            mple    values:
See Also
bode | freqresp | idfrd | impulseest | nyquist | spa | spafdr | spectrum
Topics
“Estimate Frequency-Response Models at the Command Line”
“What is a Frequency-Response Model?”
                                                                                               1-293
1   Functions
          evalfr
          Evaluate frequency response at given frequency
          Syntax
          frsp = evalfr(sys,f)
          Description
          frsp = evalfr(sys,f) evaluates the transfer function of the TF, SS, or ZPK model sys at the
          complex number f. For state-space models with data (A, B, C, D), the result is
          evalfr is a simplified version of freqresp meant for quick evaluation of the response at a single
          point. Use freqresp to compute the frequency response over a set of frequencies.
Examples
                          z−1
                 Hz =    2
                        z +z+1
          z = 1+j;
          evalfr(H,z)
                             1
                 Hs =
                        s2 + 2s + 1
1-294
                                                      evalfr
w = 0.1;
s = j*w;
evalfr(sys,s)
freqresp(sys,w)
Limitations
The response is not finite when f is a pole of sys.
See Also
bode | freqresp | sigma
Introduced in R2012a
                                                      1-295
1   Functions
          extendedKalmanFilter
          Create extended Kalman filter object for online state estimation
          Syntax
          obj = extendedKalmanFilter(StateTransitionFcn,MeasurementFcn,InitialState)
          obj = extendedKalmanFilter(StateTransitionFcn,MeasurementFcn,InitialState,
          Name,Value)
          obj = extendedKalmanFilter(StateTransitionFcn,MeasurementFcn)
          obj = extendedKalmanFilter(StateTransitionFcn,MeasurementFcn,Name,Value)
          obj = extendedKalmanFilter(Name,Value)
          Description
          obj = extendedKalmanFilter(StateTransitionFcn,MeasurementFcn,InitialState)
          creates an extended Kalman filter object for online state estimation of a discrete-time nonlinear
          system. StateTransitionFcn is a function that calculates the state of the system at time k, given
          the state vector at time k-1. MeasurementFcn is a function that calculates the output measurement
          of the system at time k, given the state at time k. InitialState specifies the initial value of the
          state estimates.
          After creating the object, use the correct and predict commands to update state estimates and
          state estimation error covariance values using a first-order discrete-time extended Kalman filter
          algorithm and real-time data.
          obj = extendedKalmanFilter(StateTransitionFcn,MeasurementFcn,InitialState,
          Name,Value) specifies additional attributes of the extended Kalman filter object using one or more
          Name,Value pair arguments.
          obj = extendedKalmanFilter(StateTransitionFcn,MeasurementFcn,Name,Value)
          specifies additional attributes of the extended Kalman filter object using one or more Name,Value
          pair arguments. Before using the predict and correct commands, specify the initial state values
          using Name,Value pair arguments or dot notation.
          Object Description
          extendedKalmanFilter creates an object for online state estimation of a discrete-time nonlinear
          system using the first-order discrete-time extended Kalman filter algorithm.
1-296
                                                                                    extendedKalmanFilter
Consider a plant with states x, input u, output y, process noise w, and measurement noise v. Assume
that you can represent the plant as a nonlinear system.
The algorithm computes the state estimates x of the nonlinear system using state transition and
measurement functions specified by you. The software lets you specify the noise in these functions as
additive or nonadditive:
• Additive Noise Terms — The state transition and measurements equations have the following
  form:
   Here f is a nonlinear state transition function that describes the evolution of states x from one
   time step to the next. The nonlinear measurement function h relates x to the measurements y at
   time step k. w and v are the zero-mean, uncorrelated process and measurement noises,
   respectively. These functions can also have additional input arguments that are denoted by us and
   um in the equations. For example, the additional arguments could be time step k or the inputs u to
   the nonlinear system. There can be multiple such arguments.
   Note that the noise terms in both equations are additive. That is, x(k) is linearly related to the
   process noise w(k-1), and y(k) is linearly related to the measurement noise v(k).
• Nonadditive Noise Terms — The software also supports more complex state transition and
  measurement functions where the state x[k] and measurement y[k] are nonlinear functions of the
  process noise and measurement noise, respectively. When the noise terms are nonadditive, the
  state transition and measurements equation have the following form:
When you perform online state estimation, you first create the nonlinear state transition function f
and measurement function h. You then construct the extendedKalmanFilter object using these
nonlinear functions, and specify whether the noise terms are additive or nonadditive. You can also
specify the Jacobians of the state transition and measurement functions. If you do not specify them,
the software numerically computes the Jacobians.
After you create the object, you use the predict command to predict state estimate at the next time
step, and correct to correct state estimates using the algorithm and real-time data. For information
about the algorithm, see “Extended and Unscented Kalman Filter Algorithms for Online State
Estimation”.
                                                                                                  1-297
1   Functions
           Command                                            Description
           correct                                            Correct the state and state estimation error
                                                              covariance at time step k using measured data at
                                                              time step k.
           predict                                            Predict the state and state estimation error
                                                              covariance at time the next time step.
           residual                                           Return the difference between the actual and
                                                              predicted measurements.
           clone                                              Create another object with the same object
                                                              property values.
Examples
          To define an extended Kalman filter object for estimating the states of your system, you first write
          and save the state transition function and measurement function for the system.
          In this example, use the previously written and saved state transition and measurement functions,
          vdpStateFcn.m and vdpMeasurementFcn.m. These functions describe a discrete-approximation to
          a van der Pol oscillator with nonlinearity parameter, mu, equal to 1. The oscillator has two states.
          Specify an initial guess for the two states. You specify the guess as an M-element row or column
          vector, where M is the number of states.
          initialStateGuess = [1;0];
          Create the extended Kalman filter object. Use function handles to provide the state transition and
          measurement functions to the object.
          obj = extendedKalmanFilter(@vdpStateFcn,@vdpMeasurementFcn,initialStateGuess);
The object has a default structure where the process and measurement noise are additive.
          To estimate the states and state estimation error covariance from the constructed object, use the
          correct and predict commands and real-time data.
Specify Process and Measurement Noise Covariances in Extended Kalman Filter Object
          Create an extended Kalman filter object for a van der Pol oscillator with two states and one output.
          Use the previously written and saved state transition and measurement functions, vdpStateFcn.m
1-298
                                                                                    extendedKalmanFilter
and vdpMeasurementFcn.m. These functions are written for additive process and measurement
noise terms. Specify the initial state values for the two states as [2;0].
Since the system has two states and the process noise is additive, the process noise is a 2-element
vector and the process noise covariance is a 2-by-2 matrix. Assume there is no cross-correlation
between process noise terms, and both the terms have the same variance 0.01. You can specify the
process noise covariance as a scalar. The software uses the scalar value to create a 2-by-2 diagonal
matrix with 0.01 on the diagonals.
Alternatively, you can specify noise covariances after object construction using dot notation. For
example, specify the measurement noise covariance as 0.2.
obj.MeasurementNoise = 0.2;
Since the system has only one output, the measurement noise is a 1-element vector and the
MeasurementNoise property denotes the variance of the measurement noise.
Create an extended Kalman filter object for a van der Pol oscillator with two states and one output.
Use the previously written and saved state transition and measurement functions, vdpStateFcn.m
and vdpMeasurementFcn.m. Specify the initial state values for the two states as [2;0].
obj = extendedKalmanFilter(@vdpStateFcn,@vdpMeasurementFcn,[2;0]);
The extended Kalman filter algorithm uses Jacobians of the state transition and measurement
functions for state estimation. You write and save the Jacobian functions and provide them as function
handles to the object. In this example, use the previously written and saved functions
vdpStateJacobianFcn.m and vdpMeasurementJacobianFcn.m.
obj.StateTransitionJacobianFcn = @vdpStateJacobianFcn;
obj.MeasurementJacobianFcn = @vdpMeasurementJacobianFcn;
Note that if you do not specify the Jacobians of the functions, the software numerically computes the
Jacobians. This numerical computation may result in increased processing time and numerical
inaccuracy of the state estimation.
Create an extended Kalman filter object for a van der Pol oscillator with two states and one output.
Assume that the process noise terms in the state transition function are additive. That is, there is a
linear relation between the state and process noise. Also assume that the measurement noise terms
are nonadditive. That is, there is a nonlinear relation between the measurement and measurement
noise.
                                                                                                  1-299
1   Functions
obj = extendedKalmanFilter('HasAdditiveMeasurementNoise',false);
          Specify the state transition function and measurement functions. Use the previously written and
          saved functions, vdpStateFcn.m and vdpMeasurementNonAdditiveNoiseFcn.m.
          The state transition function is written assuming the process noise is additive. The measurement
          function is written assuming the measurement noise is nonadditive.
          obj.StateTransitionFcn = @vdpStateFcn;
          obj.MeasurementFcn = @vdpMeasurementNonAdditiveNoiseFcn;
Specify the initial state values for the two states as [2;0].
obj.State = [2;0];
          You can now use the correct and predict commands to estimate the state and state estimation
          error covariance values from the constructed object.
          Consider a nonlinear system with input u whose state x and measurement y evolve according to the
          following state transition and measurement equations:
                                            2
                y[k] = x[k] + 2 * u[k] + v[k]
The process noise w of the system is additive while the measurement noise v is nonadditive.
          Create the state transition function and measurement function for the system. Specify the functions
          with an additional input u.
          f = @(x,u)(sqrt(x+u));
          h = @(x,v,u)(x+2*u+v^2);
          f and h are function handles to the anonymous functions that store the state transition and
          measurement functions, respectively. In the measurement function, because the measurement noise
          is nonadditive, v is also specified as an input. Note that v is specified as an input before the
          additional input u.
          Create an extended Kalman filter object for estimating the state of the nonlinear system using the
          specified functions. Specify the initial value of the state as 1 and the measurement noise as
          nonadditive.
obj = extendedKalmanFilter(f,h,1,'HasAdditiveMeasurementNoise',false);
obj.MeasurementNoise = 0.01;
          You can now estimate the state of the system using the predict and correct commands. You pass
          the values of u to predict and correct, which in turn pass them to the state transition and
          measurement functions, respectively.
1-300
                                                                                     extendedKalmanFilter
Correct the state estimate with measurement y[k]=0.8 and input u[k]=0.2 at time step k.
correct(obj,0.8,0.2)
predict(obj,0.2)
Retrieve the error, or residual, between the prediction and the measurement.
Input Arguments
StateTransitionFcn — State transition function
function handle
State transition function f, specified as a function handle. The function calculates the Ns-element
state vector of the system at time step k, given the state vector at time step k-1. Ns is the number of
states of the nonlinear system.
You write and save the state transition function for your nonlinear system, and use it to construct the
object. For example, if vdpStateFcn.m is the state transition function, specify
StateTransitionFcn as @vdpStateFcn. You can also specify StateTransitionFcn as a function
handle to an anonymous function.
The inputs to the function you write depend on whether you specify the process noise as additive or
nonadditive in the HasAdditiveProcessNoise property of the object:
• HasAdditiveProcessNoise is true — The process noise w is additive, and the state transition
  function specifies how the states evolve as a function of state values at the previous time step:
x(k) = f(x(k-1),Us1,...,Usn)
   Where x(k) is the estimated state at time k, and Us1,...,Usn are any additional input
   arguments required by your state transition function, such as system inputs or the sample time.
   During estimation, you pass these additional arguments to the predict command, which in turn
   passes them to the state transition function.
• HasAdditiveProcessNoise is false — The process noise is nonadditive, and the state transition
  function also specifies how the states evolve as a function of the process noise:
x(k) = f(x(k-1),w(k-1),Us1,...,Usn)
To see an example of a state transition function with additive process noise, type edit
vdpStateFcn at the command line.
Measurement function h, specified as a function handle. The function calculates the N-element output
measurement vector of the nonlinear system at time step k, given the state vector at time step k. N is
the number of measurements of the system. You write and save the measurement function, and use it
to construct the object. For example, if vdpMeasurementFcn.m is the measurement function, specify
                                                                                                  1-301
1   Functions
          The inputs to the function depend on whether you specify the measurement noise as additive or
          nonadditive in the HasAdditiveMeasurementNoise property of the object:
y(k) = h(x(k),Um1,...,Umn)
                Where y(k) and x(k) are the estimated output and estimated state at time k, and Um1,...,Umn
                are any optional input arguments required by your measurement function. For example, if you are
                using multiple sensors for tracking an object, an additional input could be the sensor position.
                During estimation, you pass these additional arguments to the correct command, which in turn
                passes them to the measurement function.
          • HasAdditiveMeasurementNoise is false — The measurement noise is nonadditive, and the
            measurement function also specifies how the output measurement evolves as a function of the
            measurement noise:
y(k) = h(x(k),v(k),Um1,...,Umn)
          To see an example of a measurement function with additive process noise, type edit
          vdpMeasurementFcn at the command line. To see an example of a measurement function with
          nonadditive process noise, type edit vdpMeasurementNonAdditiveNoiseFcn.
          Initial state estimate value, specified as an Ns-element vector, where Ns is the number of states in the
          system. Specify the initial state values based on your knowledge of the system.
          The specified value is stored in the State property of the object. If you specify InitialState as a
          column vector, then State is also a column vector, and the predict and correct commands return
          state estimates as a column vector. Otherwise, a row vector is returned.
          If you want a filter with single-precision floating-point variables, specify InitialState as a single-
          precision vector variable. For example, for a two-state system with state transition and measurement
          functions vdpStateFcn.m and vdpMeasurementFcn.m, create the extended Kalman filter object
          with initial state estimates [1;2] as follows:
          obj = extendedKalmanFilter(@vdpStateFcn,@vdpMeasurementFcn,single([1;2]))
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
1-302
                                                                                     extendedKalmanFilter
Properties
extendedKalmanFilter object properties are of three types:
• Tunable properties that you can specify multiple times, either during object construction using
  Name,Value arguments, or any time afterward during state estimation. After object creation, use
  dot notation to modify the tunable properties.
   obj = extendedKalmanFilter(StateTransitionFcn,MeasurementFcn,InitialState);
   obj.ProcessNoise = 0.01;
y(k) = h(x(k),Um1,...,Umn)
   Where y(k) and x(k) are the estimated output and estimated state at time k, and Um1,...,Umn
   are any optional input arguments required by your measurement function.
• false — Measurement noise is nonadditive. The measurement function specifies how the output
  measurement evolves as a function of the state and measurement noise:
y(k) = h(x(k),v(k),Um1,...,Umn)
HasAdditiveMeasurementNoise is a nontunable property, and you can specify it only during object
construction. You cannot change it using dot notation.
x(k) = f(x(k-1),Us1,...,Usn)
   Where x(k) is the estimated state at time k, and Us1,...,Usn are any additional input
   arguments required by your state transition function.
• false — Process noise is nonadditive. The state transition function specifies how the states
  evolve as a function of the state and process noise at the previous time step:
                                                                                                  1-303
1   Functions
x(k) = f(x(k-1),w(k-1),Us1,...,Usn)
          HasAdditiveProcessNoise is a nontunable property, and you can specify it only during object
          construction. You cannot change it using dot notation.
          Measurement function h, specified as a function handle. The function calculates the N-element output
          measurement vector of the nonlinear system at time step k, given the state vector at time step k. N is
          the number of measurements of the system. You write and save the measurement function and use it
          to construct the object. For example, if vdpMeasurementFcn.m is the measurement function, specify
          MeasurementFcn as @vdpMeasurementFcn. You can also specify MeasurementFcn as a function
          handle to an anonymous function.
          The inputs to the function depend on whether you specify the measurement noise as additive or
          nonadditive in the HasAdditiveMeasurementNoise property of the object:
y(k) = h(x(k),Um1,...,Umn)
                Where y(k) and x(k) are the estimated output and estimated state at time k, and Um1,...,Umn
                are any optional input arguments required by your measurement function. For example, if you are
                using multiple sensors for tracking an object, an additional input could be the sensor position.
                During estimation, you pass these additional arguments to the correct command which in turn
                passes them to the measurement function.
          • HasAdditiveMeasurementNoise is false — The measurement noise is nonadditive, and the
            measurement function also specifies how the output measurement evolves as a function of the
            measurement noise:
y(k) = h(x(k),v(k),Um1,...,Umn)
          To see an example of a measurement function with additive process noise, type edit
          vdpMeasurementFcn at the command line. To see an example of a measurement function with
          nonadditive process noise, type edit vdpMeasurementNonAdditiveNoiseFcn.
          MeasurementFcn is a nontunable property. You can specify it once before using the correct
          command either during object construction or using dot notation after object construction. You
          cannot change it after using the correct command.
          • [] — The Jacobian is numerically computed at every call to the correct command. This may
            increase processing time and numerical inaccuracy of the state estimation.
          • function handle — You write and save the Jacobian function and specify the handle to the function.
            For example, if vdpMeasurementJacobianFcn.m is the Jacobian function, specify
            MeasurementJacobianFcn as @vdpMeasurementJacobianFcn.
                The function calculates the partial derivatives of the measurement function with respect to the
                states and measurement noise. The number of inputs to the Jacobian function must equal the
1-304
                                                                                   extendedKalmanFilter
   number of inputs to the measurement function and must be specified in the same order in both
   functions. The number of outputs of the Jacobian function depends on the
   HasAdditiveMeasurementNoise property:
To see an example of a Jacobian function for additive measurement noise, type edit
vdpMeasurementJacobianFcn at the command line.
MeasurementJacobianFcn is a nontunable property. You can specify it once before using the
correct command either during object construction or using dot notation after object construction.
You cannot change it after using the correct command.
Measurement noise covariance, specified as a scalar or matrix depending on the value of the
HasAdditiveMeasurementNoise property:
Process noise covariance, specified as a scalar or matrix depending on the value of the
HasAdditiveProcessNoise property:
                                                                                                1-305
1   Functions
                process noise terms and all the terms have the same variance. The software extends the scalar to
                a W-by-W diagonal matrix.
          State of the nonlinear system, specified as a vector of size Ns, where Ns is the number of states of the
          system.
          When you use the predict command, State is updated with the predicted value at time step k using
          the state value at time step k–1. When you use the correct command, State is updated with the
          estimated value at time step k using measured data at time step k.
          The initial value of State is the value you specify in the InitialState input argument during
          object creation. If you specify InitialState as a column vector, then State is also a column vector,
          and the predict and correct commands return state estimates as a column vector. Otherwise, a
          row vector is returned. If you want a filter with single-precision floating-point variables, you must
          specify State as a single-precision variable during object construction using the InitialState
          input argument.
          State estimation error covariance, specified as a scalar or an Ns-by-Ns matrix, where Ns is the
          number of states of the system. If you specify a scalar, the software uses the scalar value to create an
          Ns-by-Ns diagonal matrix.
          Specify a high value for the covariance when you do not have confidence in the initial state values
          that you specify in the InitialState input argument.
          When you use the predict command, StateCovariance is updated with the predicted value at
          time step k using the state value at time step k–1. When you use the correct command,
          StateCovariance is updated with the estimated value at time step k using measured data at time
          step k.
          StateCovariance is a tunable property. You can change it using dot notation after using the
          correct or predict commands.
          State transition function f, specified as a function handle. The function calculates the Ns-element
          state vector of the system at time step k, given the state vector at time step k-1. Ns is the number of
          states of the nonlinear system.
          You write and save the state transition function for your nonlinear system and use it to construct the
          object. For example, if vdpStateFcn.m is the state transition function, specify
          StateTransitionFcn as @vdpStateFcn. You can also specify StateTransitionFcn as a function
          handle to an anonymous function.
1-306
                                                                                     extendedKalmanFilter
The inputs to the function you write depend on whether you specify the process noise as additive or
nonadditive in the HasAdditiveProcessNoise property of the object:
• HasAdditiveProcessNoise is true — The process noise w is additive, and the state transition
  function specifies how the states evolve as a function of state values at previous time step:
x(k) = f(x(k-1),Us1,...,Usn)
   Where x(k) is the estimated state at time k, and Us1,...,Usn are any additional input
   arguments required by your state transition function, such as system inputs or the sample time.
   During estimation, you pass these additional arguments to the predict command, which in turn
   passes them to the state transition function.
• HasAdditiveProcessNoise is false — The process noise is nonadditive, and the state transition
  function also specifies how the states evolve as a function of the process noise:
x(k) = f(x(k-1),w(k-1),Us1,...,Usn)
To see an example of a state transition function with additive process noise, type edit
vdpStateFcn at the command line.
StateTransitionFcn is a nontunable property. You can specify it once before using the predict
command either during object construction or using dot notation after object construction. You
cannot change it after using the predict command.
• [] — The Jacobian is numerically computed at every call to the predict command. This may
  increase processing time and numerical inaccuracy of the state estimation.
• function handle — You write and save the Jacobian function and specify the handle to the function.
  For example, if vdpStateJacobianFcn.m is the Jacobian function, specify
  StateTransitionJacobianFcn as @vdpStateJacobianFcn.
   The function calculates the partial derivatives of the state transition function with respect to the
   states and process noise. The number of inputs to the Jacobian function must equal the number of
   inputs of the state transition function and must be specified in the same order in both functions.
   The number of outputs of the function depends on the HasAdditiveProcessNoise property:
The extended Kalman filter algorithm uses the Jacobian to compute the state estimation error
covariance.
To see an example of a Jacobian function for additive process noise, type edit
vdpStateJacobianFcn at the command line.
                                                                                                  1-307
1   Functions
          StateTransitionJacobianFcn is a nontunable property. You can specify it once before using the
          predict command either during object construction or using dot notation after object construction.
          You cannot change it after using the predict command.
          Output Arguments
          obj — Extended Kalman filter object for online state estimation
          extendedKalmanFilter object
          Extended Kalman filter object for online state estimation, returned as an extendedKalmanFilter
          object. This object is created using the specified properties on page 1-303. Use the correct and
          predict commands to estimate the state and state estimation error covariance using the extended
          Kalman filter algorithm.
          When you use predict, obj.State and obj.StateCovariance are updated with the predicted
          value at time step k using the state value at time step k–1. When you use correct, obj.State and
          obj.StateCovariance are updated with the estimated values at time step k using measured data
          at time step k.
          Extended Capabilities
          C/C++ Code Generation
          Generate C and C++ code using MATLAB® Coder™.
For more information, see “Generate Code for Online State Estimation in MATLAB”.
          See Also
          Functions
          clone | correct | predict | residual | unscentedKalmanFilter
          Blocks
          Extended Kalman Filter | Kalman Filter | Unscented Kalman Filter
          Topics
          “Nonlinear State Estimation Using Unscented Kalman Filter and Particle Filter”
          “Generate Code for Online State Estimation in MATLAB”
          “What Is Online Estimation?”
          “Extended and Unscented Kalman Filter Algorithms for Online State Estimation”
          “Validate Online State Estimation at the Command Line”
          “Troubleshoot Online State Estimation”
Introduced in R2016b
1-308
                                                                                                  evaluate
evaluate
Value of nonlinearity estimator at given input
Syntax
value = evaluate(nl,x)
Arguments
nl
     Nonlinearity estimator object.
x
     Value at which to evaluate the nonlinearity.
Description
value = evaluate(nl,x) computes the value of a nonlinear estimator object of type customnet,
deadzone, linear, neuralnet, pwlinear, saturation, sigmoidnet, treepartition, or
wavenet.
Examples
The following syntax evaluates the nonlinearity of an estimated nonlinear ARX model m:
value = evaluate(m.Nonlinearity,x)
where m.Nonlinearity accesses the nonlinearity estimator of the nonlinear ARX model.
See Also
idnlarx | idnlhw
Introduced in R2007a
                                                                                                    1-309
1   Functions
          fcat
          Concatenate FRD models along frequency dimension
          Syntax
          sys = fcat(sys1,sys2,...)
          Description
          sys = fcat(sys1,sys2,...) takes two or more frd models and merges their frequency
          responses into a single frd model sys. The resulting frequency vector is sorted by increasing
          frequency. The frequency vectors of sys1, sys2,... should not intersect. If the frequency vectors
          do intersect, use fdel to remove intersecting data from one or more of the models.
          See Also
          fdel | frd | fselect | idfrd | interp
1-310
                                                                                                 fdel
fdel
Delete specified data from frequency response data (FRD) models
Syntax
sysout = fdel(sys, freq)
Description
sysout = fdel(sys, freq) removes from the frd model sys the data nearest to the frequency
values specified in the vector freq.
Input Arguments
sys
frd model.
freq
Output Arguments
sysout
frd model containing the data remaining in sys after removing the frequency points closest to the
entries of freq.
Examples
Create a frequency response data (FRD) model at specified frequencies from a transfer function
model.
w = logspace(0,1,10);
sys = frd(tf([1],[1 1]),w)
sys =
      Frequency(rad/s)            Response
      ----------------            --------
            1.0000            0.5000 - 0.5000i
            1.2915            0.3748 - 0.4841i
            1.6681            0.2644 - 0.4410i
            2.1544            0.1773 - 0.3819i
            2.7826            0.1144 - 0.3183i
            3.5938            0.0719 - 0.2583i
                                                                                             1-311
1   Functions
sys2 =
                Frequency(rad/s)          Response
                ----------------          --------
                      1.0000          0.5000 - 0.5000i
                      1.2915          0.3748 - 0.4841i
                      1.6681          0.2644 - 0.4410i
                      2.7826          0.1144 - 0.3183i
                      4.6416          0.0444 - 0.2059i
                      7.7426          0.0164 - 0.1270i
                     10.0000          0.0099 - 0.0990i
          Note that you do not have to specify the exact frequency of the data to remove. The fdel command
          removes the data corresponding to frequencies that are nearest to the specified frequencies.
          Tips
          • Use fdel to remove unwanted data (for example, outlier points) at specified frequencies.
          • Use fdel to remove data at intersecting frequencies from frd models before merging them with
            fcat. fcat produces an error when you attempt to merge frd models that have intersecting
            frequency data.
          • To remove data from an frd model within a range of frequencies, use fselect.
          See Also
          fcat | frd | fselect | idfrd
Introduced in R2012a
1-312
                                                                                                feedback
feedback
Identify possible feedback data
Syntax
[fbck,fbck0,nudir] = feedback(Data)
Description
Data is an iddata set with Ny outputs and Nu inputs.
fbck is an Ny-by-Nu matrix indicating the feedback. The ky,ku entry is a measure of feedback from
output ky to input ku. The value is a probability P in percent. Its interpretation is that if the
hypothesis that there is no feedback from output ky to input ku were tested at the level P, it would
have been rejected. An intuitive but technically incorrect way of thinking about this is to see P as “the
probability of feedback.” Often only values above 90% are taken as indications of feedback. When
fbck is calculated, direct dependence at lag zero between u(t) and y(t) is not regarded as a feedback
effect.
fbck0: Same as fbck, but direct dependence at lag 0 between u(t) and y(t) is viewed as feedback
effect.
nudir: A vector containing those input numbers that appear to have a direct effect on some outputs,
that is, no delay from input to output.
See Also
advice | iddata
                                                                                                  1-313
1   Functions
          fft
          Transform iddata object to frequency domain data
          Syntax
          Datf = fft(Data)
          Datf = fft(Data,N)
          Datf = fft(Data,N,'complex')
          Description
          Datf = fft(Data) transforms time-domain data to frequency domain data. If Data is a time-
          domain iddata object with real-valued signals and with constant sample time Ts, Datf is returned
          as a frequency-domain iddata object with the frequency values equally distributed from frequency 0
          to the Nyquist frequency. Whether the Nyquist frequency actually is included or not depends on the
          signal length (even or odd). Note that the FFTs are normalized by dividing each transform by the
          square root of the signal length. That is in order to preserve the signal power and noise level.
          Datf = fft(Data,N) specifies the transformation length. In the default case, the length of the
          transformation is determined by the signal length. A second argument N will force FFT
          transformations of length N, padding with zeros if the signals in Data are shorter and truncating
          otherwise. Thus the number of frequencies in the real signal case will be N/2 or (N+1)/2. If Data
          contains several experiments, N can be a row vector of corresponding length.
          Datf = fft(Data,N,'complex') specifies to include negative frequencies. For real signals, the
          default is that Datf only contains nonnegative frequencies. For complex-valued signals, negative
          frequencies are also included. To enforce negative frequencies in the real case, add a last argument,
          'Complex'.
          See Also
          iddata | ifft | spa
Introduced in R2007a
1-314
                                                                                            idnlarx/findop
idnlarx/findop
Compute operating point for Nonlinear ARX model
Syntax
[X,U] = findop(sys,'steady',InputLevel,OutputLevel)
[X,U] = findop(sys,spec)
[X,U] = findop(sys,'snapshot',T,Uin)
[X,U] = findop(sys,'snapshot',T,Uin,X0)
Description
[X,U] = findop(sys,'steady',InputLevel,OutputLevel) returns the operating-point state
values, X, and input values, U, for theidnlarx model, sys, using steady-state input and output
specifications.
[X,U] = findop(sys,spec) returns the steady-state operating point for sys using the operating-
point specification, spec.
[X,U] = findop( ___ ,Options) specifies optimization search options for all of the previous
syntaxes.
[X,U,Report] = findop( ___ ) returns a summary report on the optimization search results for
all of the previous syntaxes.
Examples
Find the steady-state operating point where the input level is fixed to 1 and the output is unknown.
[X,U] = findop(M,'steady',1,NaN);
                                                                                                  1-315
1   Functions
          load iddata7;
          M = nlarx(z7,[4 3*ones(1,2) 2*ones(1,2)]);
spec = operspec(M);
          spec.Input.Value(1) = -1;
          spec.Input.Value(2) = 1;
Set the maximum and minimum values for the output signal.
          spec.Output.Max = 10;
          spec.Output.Min = -10;
[X,U] = findop(M,spec);
          load iddata6;
          M = nlarx(z6,[4 3 2]);
opt = findopOptions(M);
          Modify the option set to specify a steepest descent gradient search method with a maximum of 50
          iterations.
          opt.SearchMethod = 'grad';
          opt.SearchOptions.MaxIterations = 50;
[X,U] = findop(M,'steady',1,1,opt);
          load iddata7;
          M = nlarx(z7,[4 3*ones(1,2) 2*ones(1,2)]);
1-316
                                                                                             idnlarx/findop
Find the steady-state operating point where input 1 is set to 1 and input 2 is unrestricted. The initial
guess for the output value is 2.
disp(R);
            SearchMethod:      'auto'
                 WhyStop:      'Near (local) minimum, (norm(g) < tol).'
              Iterations:      10
               FinalCost:      0
    FirstOrderOptimality:      0
            SignalLevels:      [1x1 struct]
load twotankdata;
z = iddata(y,u,1);
M = nlarx(z,[4 3 1]);
Find the simulation snapshot after 10 seconds, assuming initial states of zero.
[X,U] = findop(M,'snapshot',10,z);
load twotankdata;
z = iddata(y,u,1);
M = nlarx(z,[4 3 1]);
Create an initial state vector. The first four states correspond to delayed output values and the final
three states correspond to delayed inputs.
X0 = [2;2;2;2;5;5;5];
Find the simulation snapshot after 10 seconds using the specified initial states.
[X,U] = findop(M,'snapshot',10,z,X0);
Input Arguments
sys — Nonlinear ARX model
idnlarx object
                                                                                                   1-317
1   Functions
          Steady-state input level for computing the operating point, specified as a vector. The length of
          InputLevel must equal the number of inputs specified in sys.
          The optimization algorithm assumes that finite values in InputLevel are fixed input values. Use NaN
          to specify unknown input signals with initial guesses of 0. The minimum and maximum bounds for all
          inputs have default values of -Inf and +Inf respectively.
          Steady-state output level for computing the operating point, specified as a vector. The length of
          OutputLevel must equal the number of outputs specified in sys.
          The values in OutputLevel indicate initial guesses for the optimization algorithm. Use NaN to
          specify unknown output signals with initial guesses of 0. The minimum and maximum bounds for all
          outputs have default values of -Inf and +Inf respectively.
          Operating-point specifications, such as minimum and maximum input/output constraints and known
          inputs, specified as anoperspec object.
          Operating point snapshot time, specified as a positive scalar. The value of T must be in the range [T0,
          N*Ts], where N is the number of input samples, Ts is the sample time and T0 is the input start time
          (Uin.Tstart).
          • Time-domain iddata object with a sample time and input size that matches sys.
          • Matrix with as many columns as there are input channels. If the matrix has N rows, the input data
            is assumed to correspond to the time vector (1:N)*sys.Ts.
          X0 — Initial states
          column vector
          Initial states of the simulation, specified as a column vector with size equal to the number of states in
          sys. X0 provides the initial conditions at the time corresponding to the first input sample
          (Uin.Start, if Uin is an iddata object, or sys.Ts if Uin is a double matrix).
          For more information about the states of an idnlarx model, see “Definition of idnlarx States” on
          page 1-527.
1-318
                                                                                          idnlarx/findop
Output Arguments
X — Operating point state values
column vector
Operating point state values, returned as a column vector of length equal to the number of model
states.
Operating point input values, returned as a column vector of length equal to the number of inputs.
Search result summary report, returned as a structure with the following fields:
Field          Description
SearchMeth Search method used for iterative parameter estimation. See SearchMethod in
od         findopOptions for more information.
WhyStop        Search algorithm termination condition.
Iterations Number of estimation iterations performed.
FinalCost      Final value of the minimization objective function (sum of the squared errors).
FirstOrder ∞-norm of the search gradient vector when the search algorithm terminates.
Optimality
SignalLeve Structure containing the fields Input and Output, which are the operating point
ls         input and output signal levels respectively.
Algorithms
findop computes the operating point from steady-state operating point specifications or at a
simulation snapshot.
To compute the steady-state operating point, call findop using either of the following syntaxes:
[X,U] = findop(sys,'steady',InputLevel,OutputLevel)
[X,U] = findop(sys,spec)
To compute the states, X, and the input, U, of the steady-state operating point, findop minimizes the
norm of the error e(t) = y(t)-f(x(t), u(t)), where:
                                                                                                 1-319
1   Functions
You can specify the search algorithm and search options using the findopOptions option set.
          Because idnlarx model states are delayed samples of the input and output variables, the state
          values are the constant values of the corresponding steady-state inputs and outputs. For more
          information about the definition of nonlinear ARX model states, see “Definition of idnlarx States” on
          page 1-527.
          When you use the syntax [X,U] = findop(sys,'snapshot',T,Uin,X0), the algorithm simulates
          the model output until the snapshot time, T. At the snapshot time, the algorithm passes the input and
          output samples to the data2state command to map these values to the current state vector.
Note For snapshot-based computations, findop does not perform numerical optimization.
          Extended Capabilities
          Automatic Parallel Support
          Accelerate code by automatically running computation in parallel using Parallel Computing Toolbox™.
          Parallel computing support is available for estimation using the lsqnonlin search method (requires
          Optimization Toolbox). To enable parallel computing, use findopOptions, set SearchMethod to
          'lsqnonlin', and set SearchOptions.Advanced.UseParallel to true.
For example:
          opt = findopOptions(idnlarx);
          opt.SearchMethod = 'lsqnonlin';
          opt.SearchOptions.Advanced.UseParallel = true;
          See Also
          data2state | findopOptions | idnlarx | idnlarx/operspec | idnlhw/findop | sim
Introduced in R2008a
1-320
                                                                                            idnlhw/findop
idnlhw/findop
Compute operating point for Hammerstein-Wiener model
Syntax
[X,U] = findop(sys,'steady',InputLevel,OutputLevel)
[X,U] = findop(sys,spec)
[X,U] = findop(sys,'snapshot',T,Uin)
[X,U] = findop(sys,'snapshot',T,Uin,X0)
Description
[X,U] = findop(sys,'steady',InputLevel,OutputLevel) returns the operating-point state
values, X, and input values, U, for the idnlhw model, sys, using steady-state input and output
specifications.
[X,U] = findop(sys,spec) returns the steady-state operating point for sys using the operating
point specification in spec.
[X,U] = findop( ___ ,Options) specifies optimization search options for all of the previous
syntaxes.
[X,U,Report] = findop( ___ ) returns a summary report on the optimization search results for
all of the previous syntaxes.
Examples
load twotankdata;
z = iddata(y,u,1);
M = nlhw(z,[5 1 3]);
Find the steady-state operating point where the input level is set to 1 and the output is unknown.
[X,U] = findop(M,'steady',1,NaN);
                                                                                                  1-321
1   Functions
          load iddata7;
          orders = [4*ones(1,2) 2*ones(1,2) 3*ones(1,2)];
          M = nlhw(z7,orders,'unitgain','pwlinear');
spec = operspec(M);
          spec.Input.Value(1) = -1;
          spec.Input.Value(2) = 1;
Set the maximum and minimum values for the output signal.
          spec.Output.Max = 10;
          spec.Output.Min = -10;
[X,U] = findop(M,spec);
          load twotankdata;
          z = iddata(y,u,1);
          M = nlhw(z,[5 1 3]);
opt = findopOptions(M);
          Modify the option set to specify a steepest descent gradient search method with a maximum of 50
          iterations.
          opt.SearchMethod = 'grad';
          opt.SearchOptions.MaxIterations = 50;
[X,U] = findop(M,'steady',1,NaN,opt);
1-322
                                                                                             idnlhw/findop
load iddata7;
orders = [4*ones(1,2) 2*ones(1,2) 3*ones(1,2)];
M = nlhw(z7,orders,'unitgain','pwlinear');
Find the steady-state operating point where input 1 is set to 1 and input 2 is unrestricted. The initial
guess for the output value is 2.
[X,U,R] = findop(M,'steady',[1 NaN],2);
             SearchMethod:        'auto'
                  WhyStop:        'Near (local) minimum, (norm(g) < tol).'
               Iterations:        20
                FinalCost:        1.2326e-30
     FirstOrderOptimality:        4.1203e-16
             SignalLevels:        [1x1 struct]
Find the simulation snapshot after 10 seconds, assuming initial states of zero.
[X,U] = findop(M,'snapshot',10,z);
Find the simulation snapshot after 10 seconds using the specified initial states.
[X,U] = findop(M,'snapshot',10,z,X0);
Input Arguments
sys — Hammerstein-Wiener model
idnlhw object
                                                                                                   1-323
1   Functions
          Steady-state input level for computing the operating point, specified as a vector. The length of
          InputLevel must equal the number of inputs specified in sys.
          The optimization algorithm assumes that finite values in InputLevel are fixed input values. Use NaN
          to specify unknown input signals with initial guesses of 0. The minimum and maximum bounds for all
          inputs have default values of -Inf and +Inf respectively.
          Steady-state output level for computing the operating point, specified as a vector. The length of
          OutputLevel must equal the number of outputs specified in sys.
          The values in OutputLevel indicate initial guesses for the optimization algorithm. Use NaN to
          specify unknown output signals with initial guesses of 0. The minimum and maximum bounds for all
          outputs have default values of -Inf and +Inf respectively.
          Operating-point specifications, such as minimum and maximum input/output constraints and known
          inputs, specified as an operspec object.
          Operating point snapshot time, specified as a positive scalar. The value of T must be in the range [T0,
          N*Ts], where N is the number of input samples, Ts is the sample time and T0 is the input start time
          (Uin.Tstart).
          • Time-domain iddata object with a sample time and input size that matches sys.
          • Matrix with as many columns as there are input channels. If the matrix has N rows, the input data
            is assumed to correspond to the time vector (1:N)*sys.Ts.
          X0 — Initial states
          column vector
          Initial states of the simulation, specified as a column vector with length equal to the number of states
          in sys. X0 provides the initial conditions at the time corresponding to the first input sample
          (Uin.Start, if Uin is an iddata object, or sys.Ts if Uin is a double matrix).
          For more information about the states of an idnlhw model, see “Definition of idnlhw States” on page
          1-557.
1-324
                                                                                           idnlhw/findop
Output Arguments
X — Operating point state values
column vector
Operating point state values, returned as a column vector of length equal to the number of model
states.
Operating point input values, returned as a column vector of length equal to the number of inputs.
Search result summary report, returned as a structure with the following fields:
Field          Description
SearchMeth Search method used for iterative parameter estimation. See SearchMethod in
od         findopOptions for more information.
WhyStop        Search algorithm termination condition.
Iterations Number of estimation iterations performed.
FinalCost      Final value of the minimization objective function (sum of the squared errors).
FirstOrder ∞-norm of the search gradient vector when the search algorithm terminates.
Optimality
SignalLeve Structure containing the fields Input and Output, which are the operating point
ls         input and output signal levels respectively.
Algorithms
findop computes the operating point from steady-state operating point specifications or at a
simulation snapshot.
To compute the steady-state operating point, call findop using either of the following syntaxes:
[X,U] = findop(sys,'steady',InputLevel,OutputLevel)
[X,U] = findop(sys,spec)
findop uses a different approach to compute the steady-state operating point depending on how
much information you provide for this computation:
• When you specify values for all input levels (no NaN values). For a given input level, U, the
  equilibrium state values are X = inv(I-A)*B*f(U), where [A,B,C,D] =
  ssdata(model.LinearModel), and f() is the input nonlinearity.
                                                                                                  1-325
1   Functions
          • When you specify known and unknown input levels. findop uses numerical optimization to
            minimize the norm of the error and compute the operating point. The total error is the union of
            contributions from e1 and e2 , e(t) = (e1(t)e2(t)), such that:
                • e1 applies for known outputs and the algorithm minimizes e1 = y- g(L(x,f(u))), where f is the
                  input nonlinearity, L(x,u) is the linear model with states x, and g is the output nonlinearity.
                • e2 applies for unknown outputs and the error is a measure of whether these outputs are within
                  the specified minimum and maximum bounds. If a variable is within its specified bounds, the
                  corresponding error is zero. Otherwise, the error is equal to the distance from the nearest
                  bound. For example, if a free output variable has a value z and its minimum and maximum
                  bounds are L and U, respectively, then the error is e2= max[z-U, L-z, 0].
                The independent variables for the minimization problem are the unknown inputs. In the error
                definition e, both the input u and the states x are free variables. To get an error expression that
                contains only unknown inputs as free variables, the algorithm findop specifies the states as a
                function of inputs by imposing steady-state conditions: x = inv(I-A)*B*f(U), where A and B are
                state-space parameters corresponding to the linear model L(x,u). Thus, substituting x = inv(I-
                A)*B*f(U) into the error function results in an error expression that contains only unknown inputs
                as free variables computed by the optimization algorithm.
          When you use the syntax [X,U] = findop(sys,'snapshot',T,UIN,X0), the algorithm simulates
          the model output until the snapshot time, T. At the snapshot time, the algorithm computes the inputs
          for the linear model block of the Hammerstein-Wiener model (LinearModel property of theidnlhw
          object) by transforming the given inputs using the input nonlinearity: w = f(u). findop uses the
          resulting w to compute x until the snapshot time using the following equation: x(t+1) = Ax(t) + Bw(t),
          where [A,B,C,D] = ssdata(model.LinearModel).
Note For snapshot-based computations, findop does not perform numerical optimization.
          Extended Capabilities
          Automatic Parallel Support
          Accelerate code by automatically running computation in parallel using Parallel Computing Toolbox™.
          Parallel computing support is available for estimation using the lsqnonlin search method (requires
          Optimization Toolbox). To enable parallel computing, use findopOptions, set SearchMethod to
          'lsqnonlin', and set SearchOptions.Advanced.UseParallel to true.
For example:
          opt = findopOptions(idnlhw);
          opt.SearchMethod = 'lsqnonlin';
          opt.SearchOptions.Advanced.UseParallel = true;
          See Also
          findopOptions | idnlarx/findop | idnlhw | idnlhw/operspec | sim
Introduced in R2008a
1-326
                                                                                       findopOptions
findopOptions
Option set for findop
Syntax
opt = findopOptions(model)
opt = findopOptions(model,Name,Value)
Description
opt = findopOptions(model) creates a default option set for computing the operating point of a
specified nonlinear ARX or Hammerstein-Wiener model. Use dot notation to modify this option set for
your specific application. Options that you do not modify retain their default values.
Examples
opt = findopOptions(idnlarx);
opt = findopOptions(idnlhw);
Use dot notation to specify a subspace Gauss-Newton least squares search with a maximum of 25
iterations.
opt.SearchMethod = 'gn';
opt.SearchOptions.MaxIterations = 25;
Create an option set for findop using an idnlarx model. Specify a steepest descent least squares
search with default search options.
opt = findopOptions(idnlarx,'SearchMethod','grad');
                                                                                             1-327
1   Functions
          Input Arguments
          model — Estimated nonlinear model
          idnlarx model | idnlhw model
          • idnlarx model
          • idnlhw model
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
          Example: 'SearchMethod','grad' specifies a steepest descent least squares search method
          Numerical search method used for iterative parameter estimation, specified as the comma-separated
          pair consisting of 'SearchMethod' and one of the following:
          • 'auto' — A combination of the line search algorithms, 'gn', 'lm', 'gna', and 'grad' methods
            is tried in sequence at each iteration. The first descent direction leading to a reduction in
            estimation cost is used.
          • 'gn' — Subspace Gauss-Newton least squares search. Singular values of the Jacobian matrix less
            than GnPinvConstant*eps*max(size(J))*norm(J) are discarded when computing the
            search direction. J is the Jacobian matrix. The Hessian matrix is approximated as JTJ. If there is no
            improvement in this direction, the function tries the gradient direction.
          • 'gna' — Adaptive subspace Gauss-Newton search. Eigenvalues less than gamma*max(sv) of the
            Hessian are ignored, where sv contains the singular values of the Hessian. The Gauss-Newton
            direction is computed in the remaining subspace. gamma has the initial value
            InitialGnaTolerance (see Advanced in 'SearchOptions' for more information). This value
            is increased by the factor LMStep each time the search fails to find a lower value of the criterion
            in fewer than five bisections. This value is decreased by the factor 2*LMStep each time a search is
            successful without any bisections.
          • 'lm' — Levenberg-Marquardt least squares search, where the next parameter value is -pinv(H
            +d*I)*grad from the previous one. H is the Hessian, I is the identity matrix, and grad is the
            gradient. d is a number that is increased until a lower value of the criterion is found.
          • 'grad' — Steepest descent least squares search.
          • 'lsqnonlin' — Trust-region-reflective algorithm of lsqnonlin. Requires Optimization Toolbox
            software.
          • 'fmincon' — Constrained nonlinear solvers. You can use the sequential quadratic programming
            (SQP) and trust-region-reflective algorithms of the fmincon solver. If you have Optimization
            Toolbox software, you can also use the interior-point and active-set algorithms of the fmincon
            solver. Specify the algorithm in the SearchOptions.Algorithm option. The fmincon algorithms
            may result in improved estimation results in the following scenarios:
• Constrained minimization problems when there are bounds imposed on the model parameters.
1-328
                                                                                        findopOptions
   • Model structures where the loss function is a nonlinear or non smooth function of the
     parameters.
   • Multi-output model estimation. A determinant loss function is minimized by default for multi-
     output model estimation. fmincon algorithms are able to minimize such loss functions directly.
     The other search methods such as 'lm' and 'gn' minimize the determinant loss function by
     alternately estimating the noise variance and reducing the loss value for a given noise variance
     value. Hence, the fmincon algorithms can offer better efficiency and accuracy for multi-output
     model estimations.
Option set for the search algorithm, specified as the comma-separated pair consisting of
'SearchOptions' and a search option set with fields that depend on the value of SearchMethod.
                                                                                               1-329
1   Functions
1-330
                                                                                          findopOptions
                                                                                                1-331
1   Functions
1-332
                                                                         findopOptions
                            • 'sqp' — Sequential
                              quadratic programming
                              algorithm. The algorithm
                              satisfies bounds at all
                              iterations, and it can recover
                              from NaN or Inf results. It is
                              not a large-scale algorithm.
                              For more information, see
                              “Large-Scale vs. Medium-
                              Scale Algorithms”
                              (Optimization Toolbox).
                            • 'trust-region-
                              reflective' — Subspace
                              trust-region method based
                              on the interior-reflective
                              Newton method. It is a large-
                              scale algorithm.
                            • 'interior-point' —
                              Large-scale algorithm that
                              requires Optimization
                              Toolbox software. The
                              algorithm satisfies bounds at
                              all iterations, and it can
                              recover from NaN or Inf
                              results.
                            • 'active-set' — Requires
                              Optimization Toolbox
                              software. The algorithm can
                              take large steps, which adds
                              speed. It is not a large-scale
                              algorithm.
                                                                               1-333
1   Functions
          To specify field values in SearchOptions, create a default findopOptions set and modify the fields
          using dot notation. Any fields that you do not modify retain their default values.
          opt = findopOptions;
          opt.SearchOptions.MaxIterations = 15;
          opt.SearchOptions.Advanced.RelImprovement = 0.5;
          Output Arguments
          opt — Option set for findop command
          findopOptions object
          Compatibility Considerations
          Renaming of Estimation and Analysis Options
          The names of some estimation and analysis options were changed in R2018a. Prior names still work.
          For details, see the R2018a release note “Renaming of Estimation and Analysis Options”.
          See Also
          idnlarx/findop | idnlhw/findop
Introduced in R2015a
1-334
                                                                                            findstates
findstates
Estimate initial states of model
Syntax
x0 = findstates(sys,Data)
x0 = findstates(sys,Data,Horizon)
x0 = findstates(sys,Data,Horizon,Options)
Description
x0 = findstates(sys,Data) estimates the initial states, x0, of an identified model sys, to
maximize the fit between the model response and the output signal in the estimation data.
[x0,Report]= findstates( ___ ) delivers a report on the initial state estimation. Report is
returned with any of the previous syntaxes.
Examples
Create a nonlinear grey-box model. The model is a linear DC motor with one input (voltage), and two
outputs (angular position and angular velocity). The structure of the model is specified by
dcmotor_m.m file.
FileName = 'dcmotor_m';
Order = [2 1 2];
Parameters = [0.24365;0.24964];
nlgr = idnlgrey(FileName,Order,Parameters);
nlgr = setinit(nlgr, 'Fixed', false(2,1)); % set initial states free
load(fullfile(matlabroot,'toolbox','ident',...
     'iddemos','data','dcmotordata'));
z = iddata(y,u,0.1);
Estimate the initial states such that the model's response using the estimated states X0 and measured
input u is as close as possible to the measured output y.
X0 = findstates(nlgr,z,Inf);
                                                                                              1-335
1   Functions
          Estimate an idss model and simulate it such that the response of the estimated model matches the
          estimation data's output signal as closely as possible.
model = ssest(z1,2);
Estimate the value of the initial states to best fit the measured output z1.y.
x0est = findstates(model,z1,Inf);
          opt = simOptions('InitialCondition',x0est);
          sim(model,z1(:,[],:),opt);
1-336
                                                                                                 findstates
Estimate the initial states of a model selectively by fixing the first state and allowing the second state
of the model to be estimated.
The model is a linear DC motor with one input (voltage), and two outputs (angular position and
angular velocity). The structure of the model is specified by dcmotor_m.m file.
Hold the first state fixed at zero, and estimate the value of the second.
x0spec = idpar('x0',[0;0]);
x0spec.Free(1) = false;
opt = findstatesOptions;
opt.InitialState = x0spec;
[X0,Report] = findstates(nlgr,z,Inf,opt)
X0 = 2×1
         0
    0.0061
Report =
         Status:     'Estimated by simulation error minimization'
         Method:     'lsqnonlin'
     Covariance:     [2x2 double]
       DataUsed:     [1x1 struct]
    Termination:     [1x1 struct]
The model is a linear DC motor with one input (voltage), and two outputs (angular position and
angular velocity). The structure of the model is specified by dcmotor_m.m file.
                                                                                                    1-337
1   Functions
          load(fullfile(matlabroot,'toolbox','ident',...
               'iddemos','data','dcmotordata'));
          z = iddata(y,u,0.1);
x0spec = idpar('x0',[10;10]);
          opt = findstatesOptions;
          opt.InitialState = x0spec;
          x0 = findstates(nlgr,z,Inf,opt)
x0 = 2×1
                 0.0362
                -0.1322
          FileName = 'dcmotor_m';
          Order = [2 1 2];
          Parameters = [0.24365;0.24964];
          nlgr = idnlgrey(FileName,Order,Parameters);
          set(nlgr, 'InputName','Voltage','OutputName', ...
                  {'Angular position','Angular velocity'});
          The model is a linear DC motor with one input (voltage), and two outputs (angular position and
          angular velocity). The structure of the model is specified by dcmotor_m.m file.
          load(fullfile(matlabroot,'toolbox','ident',...
               'iddemos','data','dcmotordata'));
          z = iddata(y,u,0.1,'Name','DC-motor',...
               'InputName','Voltage','OutputName',...
               {'Angular position','Angular velocity'});
z3 = merge(z,z,z);
1-338
                                                                                              findstates
x0spec = idpar('x0',zeros(2,3));
x0spec.Free(1,2) = false;
x0spec.Free(2,[2 3]) = false;
opt = findstatesOptions;
opt.InitialState = x0spec;
[X0,EstInfo] = findstates(nlgr,z3,Inf,opt);
Input Arguments
sys — Identified model
idss object | idgrey object | idnlarx object | idnlhw object | idnlgrey object
Identified model whose initial states are estimated, represented as a linear state-space (idss or
idgrey) or nonlinear model (idnlarx, idnlhw, or idnlgrey).
Estimation data, specified as an iddata object with input/output dimensions that match sys.
If sys is a linear model, Data can be a frequency-domain iddata object. For easier interpretation of
initial conditions, make the frequency vector of Data be symmetric about the origin. For converting
time-domain data into frequency-domain data, use fft with 'compl' input argument, and ensure
that there is sufficient zero padding. Scale your data appropriately when you compare x0 between
the time-domain and frequency-domain. Since for an N-point fft, the input/output signals are scaled
by 1/sqrt(N), the estimated x0 vector is also scaled by this factor.
Prediction horizon for computing the response of sys, specified as a positive integer between 1 and
Inf. The most common values used are:
• Horizon = 1 — Minimizes the 1-step prediction error. The 1–step ahead prediction response of
  sys is compared to the output signals in Data to determine x0. See predict for more
  information.
• Horizon = Inf — Minimizes the simulation error. The difference between measured output,
  Data.y, and simulated response of sys to the measured input data, Data.u is minimized. See
  sim for more information.
Specify Horizon as any positive integer between 1 and Inf, with the following restrictions:
Scenario                                                                  Horizon
Continuous-time model with time-domain data                               1 or Inf
Continuous-time frequency-domain data (data.Ts = 0)                       Inf
                                                                                                1-339
1   Functions
           Scenario                                                                 Horizon
           Output Error models (trivial noise component):                           Irrelevant
Estimation options for findstates, specified as an option set created using findstatesOptions
          Output Arguments
          x0 — Estimated initial states
          vector | matrix
          Estimated initial states of model sys, returned as a vector or matrix. For multi-experiment data, x0 is
          a matrix with one column for each experiment.
          Initial state estimation information, returned as a structure. Report contains information about the
          data used, state covariance, and results of any numerical optimization performed to search for the
          initial states. Report has the following fields:
           Report      Description
           Field
           Status      Summary of how the initial state were estimated.
           Method      Search method used.
           Covarianc Covariance of state estimates, returned as a Ns-by-Ns matrix, where Ns is the number
           e         of states.
1-340
                                                                                              findstates
Report       Description
Field
DataUsed     Attributes of the data used for estimation, returned as a structure with the following
             fields:
             Field         Description
             Name          Name of the data set.
             Type          Data type.
             Length        Number of data samples.
             Ts            Sample time.
             InterSam Input intersample behavior, returned as one of the following values:
             ple
                      • 'zoh' — Zero-order hold maintains a piecewise-constant input signal
                         between samples.
                           • 'foh' — First-order hold maintains a piecewise-linear input signal
                             between samples.
                           • 'bl' — Band-limited behavior specifies that the continuous-time input
                             signal has zero power above the Nyquist frequency.
             InputOff Offset removed from time-domain input data during estimation. For
             set      nonlinear models, it is [].
             OutputOf Offset removed from time-domain output data during estimation. For
             fset     nonlinear models, it is [].
Terminati Termination conditions for the iterative search used for initial state estimation of
on        nonlinear models. Structure with the following fields:
             Field         Description
             WhyStop       Reason for terminating the numerical search.
             Iteratio Number of search iterations performed by the estimation algorithm.
             ns
             FirstOrd ∞-norm of the gradient search vector when the search algorithm
             erOptima terminates.
             lity
             FcnCount Number of times the objective function was called.
             UpdateNo Norm of the gradient search vector in the last iteration. Omitted when the
             rm       search method is 'lsqnonlin' or 'fmincon'.
             LastImpr Criterion improvement in the last iteration, expressed as a percentage.
             ovement Omitted when the search method is 'lsqnonlin' or 'fmincon'.
             Algorith Algorithm used by 'lsqnonlin' or 'fmincon' search method. Omitted
             m        when other search methods are used.
                                                                                                 1-341
1   Functions
          Extended Capabilities
          Automatic Parallel Support
          Accelerate code by automatically running computation in parallel using Parallel Computing Toolbox™.
          Parallel computing support is available for estimation using the lsqnonlin search method (requires
          Optimization Toolbox). To enable parallel computing, use findstatesOptions, set SearchMethod
          to 'lsqnonlin', and set SearchOptions.Advanced.UseParallel to true.
For example:
          opt = findstatesOptions;
          opt.SearchMethod = 'lsqnonlin';
          opt.SearchOptions.Advanced.UseParallel = true;
          See Also
          findstatesOptions | predict | sim
Introduced in R2015a
1-342
                                                                                        findstatesOptions
findstatesOptions
Option set for findstates
Syntax
opt = findstatesOptions
opt = findstatesOptions(Name,Value)
Description
opt = findstatesOptions creates the default option set for findstates. Use dot notation to
customize the option set, if needed.
Examples
Create an option set for findstates by configuring a specification object for the initial states.
z8 is an iddata object containing time-domain system response data. sys is a fourth-order idss
model that is identified from the data.
x0obj specifies estimation constraints on the initial conditions. The value of the first state is
specified as 1 when x0obj is created. x0obj.Free(1) = false specifies the first initial state as a
fixed estimation parameter. The second state is unknown. But, x0obj.Minimum(2) = 0 and
x0obj.Maximum(2) = 1 specify the lower and upper bounds of the second state as 0 and 1,
respectively.
Create an option set for findstates to identify the initial states of the model.
opt = findstatesOptions;
opt.InitialState = x0obj;
                                                                                                    1-343
1   Functions
          • Initial states are estimated such that the norm of prediction error is minimized. The initial values
            of the states corresponding to nonzero delays are also estimated.
          • Adaptive subspace Gauss-Newton search is used for estimation.
opt = findstatesOptions('InitialState','d','SearchMethod','gna');
          Input Arguments
          Name-Value Pair Arguments
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
          Example: findstatesOptions('InitialState','d')
• 'e' — The initial states are estimated such that the norm of prediction error is minimized.
                For nonlinear grey-box models, only those initial states i that are designated as free in the model
                (sys.InitialStates(i).Fixed = false) are estimated. To estimate all the states of the
                model, first specify all the Nx states of the idnlgrey model sys as free.
                for i = 1:Nx
                sys.InitialStates(i).Fixed = false;
                end
                Similarly, to fix all the initial states to values specified in sys.InitialStates, first specify all
                the states as fixed in the sys.InitialStates property of the nonlinear grey-box model.
          • 'd' — Similar to 'e', but absorbs nonzero delays into the model coefficients. The delays are first
            converted to explicit model states, and the initial values of those states are also estimated and
            returned.
1-344
                                                                                     findstatesOptions
   Use x0obj only for nonlinear grey-box models and linear state-space models (idss or idgrey).
   This option is applicable only for prediction horizon equal to 1 or Inf. See findstates for more
   details about the prediction horizon.
Removal of offset from time-domain input data during estimation, specified as the comma-separated
pair consisting of 'InputOffset' and one of the following:
• A column vector of positive integers of length Nu, where Nu is the number of inputs.
• [] — Indicates no offset.
• Nu-by-Ne matrix — For multi-experiment data, specify InputOffset as an Nu-by-Ne matrix. Nu
  is the number of inputs, and Ne is the number of experiments.
Each entry specified by InputOffset is subtracted from the corresponding input data.
Removal of offset from time-domain output data during estimation, specified as the comma-separated
pair consisting of 'OutputOffset' and one of the following:
Each entry specified by OutputOffset is subtracted from the corresponding output data.
Weighting of prediction errors when using multi-output data, specified as the comma-separated pair
consisting of 'OutputWeight' and one of the following:
Numerical search method used for iterative parameter estimation, specified as the comma-separated
pair consisting of 'SearchMethod' and one of the following:
• 'auto' — A combination of the line search algorithms, 'gn', 'lm', 'gna', and 'grad' methods
  is tried in sequence at each iteration. The first descent direction leading to a reduction in
  estimation cost is used.
                                                                                               1-345
1   Functions
          • 'gn' — Subspace Gauss-Newton least squares search. Singular values of the Jacobian matrix less
            than GnPinvConstant*eps*max(size(J))*norm(J) are discarded when computing the
            search direction. J is the Jacobian matrix. The Hessian matrix is approximated as JTJ. If there is no
            improvement in this direction, the function tries the gradient direction.
          • 'gna' — Adaptive subspace Gauss-Newton search. Eigenvalues less than gamma*max(sv) of the
            Hessian are ignored, where sv contains the singular values of the Hessian. The Gauss-Newton
            direction is computed in the remaining subspace. gamma has the initial value
            InitialGnaTolerance (see Advanced in 'SearchOptions' for more information). This value
            is increased by the factor LMStep each time the search fails to find a lower value of the criterion
            in fewer than five bisections. This value is decreased by the factor 2*LMStep each time a search is
            successful without any bisections.
          • 'lm' — Levenberg-Marquardt least squares search, where the next parameter value is -pinv(H
            +d*I)*grad from the previous one. H is the Hessian, I is the identity matrix, and grad is the
            gradient. d is a number that is increased until a lower value of the criterion is found.
          • 'grad' — Steepest descent least squares search.
          • 'lsqnonlin' — Trust-region-reflective algorithm of lsqnonlin. Requires Optimization Toolbox
            software.
          • 'fmincon' — Constrained nonlinear solvers. You can use the sequential quadratic programming
            (SQP) and trust-region-reflective algorithms of the fmincon solver. If you have Optimization
            Toolbox software, you can also use the interior-point and active-set algorithms of the fmincon
            solver. Specify the algorithm in the SearchOptions.Algorithm option. The fmincon algorithms
            may result in improved estimation results in the following scenarios:
                • Constrained minimization problems when there are bounds imposed on the model parameters.
                • Model structures where the loss function is a nonlinear or non smooth function of the
                  parameters.
                • Multi-output model estimation. A determinant loss function is minimized by default for multi-
                  output model estimation. fmincon algorithms are able to minimize such loss functions directly.
                  The other search methods such as 'lm' and 'gn' minimize the determinant loss function by
                  alternately estimating the noise variance and reducing the loss value for a given noise variance
                  value. Hence, the fmincon algorithms can offer better efficiency and accuracy for multi-output
                  model estimations.
          Option set for the search algorithm, specified as the comma-separated pair consisting of
          'SearchOptions ' and a search option set with fields that depend on the value of SearchMethod.
1-346
                                                                                    findstatesOptions
                                                                                              1-347
1   Functions
1-348
                                                                                     findstatesOptions
                                                                                               1-349
1   Functions
                                      • 'sqp' — Sequential
                                        quadratic programming
                                        algorithm. The algorithm
                                        satisfies bounds at all
                                        iterations, and it can recover
                                        from NaN or Inf results. It is
                                        not a large-scale algorithm.
                                        For more information, see
                                        “Large-Scale vs. Medium-
                                        Scale Algorithms”
                                        (Optimization Toolbox).
                                      • 'trust-region-
                                        reflective' — Subspace
                                        trust-region method based
                                        on the interior-reflective
                                        Newton method. It is a large-
                                        scale algorithm.
                                      • 'interior-point' —
                                        Large-scale algorithm that
                                        requires Optimization
                                        Toolbox software. The
                                        algorithm satisfies bounds at
                                        all iterations, and it can
                                        recover from NaN or Inf
                                        results.
                                      • 'active-set' — Requires
                                        Optimization Toolbox
                                        software. The algorithm can
                                        take large steps, which adds
                                        speed. It is not a large-scale
                                        algorithm.
1-350
                                                                                   findstatesOptions
To specify field values in SearchOptions , create a default findstatesOptions set and modify
the fields using dot notation. Any fields that you do not modify retain their default values.
opt = findstatesOptions;
opt.SearchOptions.Tolerance = 0.02;
opt.SearchOptions.Advanced.MaxBisections = 30;
Output Arguments
opt — Option set for findstates
findstatesOptions option set
Compatibility Considerations
Renaming of Estimation and Analysis Options
The names of some estimation and analysis options were changed in R2018a. Prior names still work.
For details, see the R2018a release note “Renaming of Estimation and Analysis Options”.
See Also
findstates | idpar
Introduced in R2012a
                                                                                             1-351
1   Functions
          fnorm
          Pointwise peak gain of FRD model
          Syntax
          fnrm = fnorm(sys)
          fnrm = fnorm(sys,ntype)
          Description
          fnrm = fnorm(sys) computes the pointwise 2-norm of the frequency response contained in the
          FRD model sys, that is, the peak gain at each frequency point. The output fnrm is an FRD object
          containing the peak gain across frequencies.
          fnrm = fnorm(sys,ntype) computes the frequency response gains using the matrix norm
          specified by ntype. See norm for valid matrix norms and corresponding NTYPE values.
          See Also
          abs | norm
Introduced in R2006a
1-352
                                                                                                forecast
forecast
Forecast identified model output
Syntax
yf = forecast(sys,PastData,K)
yf = forecast(sys,PastData,K,FutureInputs)
forecast(sys,PastData,K, ___ )
forecast(sys,Linespec,PastData,K, ___ )
forecast(sys1,...,sysN,PastData,K, ___ )
forecast(sys1,Linespec1,...,sysN,LinespecN,PastData,K, ___ )
Description
yf = forecast(sys,PastData,K) forecasts the output of an identified time series model sys, K
steps into the future using past measured data, PastData.
forecast performs prediction into the future, in a time range beyond the last instant of measured
data. In contrast, the predict command predicts the response of an identified model over the time
span of measured data. Use predict to determine if the predicted result matches the observed
response of an estimated model. If sys is a good prediction model, consider using it with forecast.
yf = forecast( ___ ,opts) uses the option set, opts, to specify additional forecast options. Use
opts with any of the previous input argument combinations.
[yf,x0,sysf] = forecast( ___ ) also returns the estimated values for initial states, x0, and a
forecasting model, sysf, and can include any of the previous input argument combinations.
forecast(sys,PastData,K, ___ ) plots the forecasted output. Use with any of the previous input
argument combinations.
To change display options, right-click the plot to access the context menu. For example, to view the
estimated standard deviation of the forecasted output, select Confidence Region from the context
menu. For more details about the menu, see “Tips” on page 1-365.
                                                                                                 1-353
1   Functions
Examples
          data = iddata(sin(0.1*[1:100])',[]);
          plot(data)
sys = ar(data,2);
Forecast the values into the future for a given time horizon.
          K = 100;
          p = forecast(sys,data,K);
1-354
                                                                                               forecast
K specifies the forecasting time horizon as 100 samples. p is the forecasted model response.
plot(data,'b',p,'r'), legend('measured','forecasted')
load iddata9 z9
past_data = z9.OutputData(1:50);
model = ar(z9,4);
opt = forecastOptions('InitialCondition','e');
                                                                                               1-355
1   Functions
          K = 100;
          forecast(model,past_data,K,opt);
          legend('Measured','Forecasted')
          load iddata9 z9
          past_data = z9.OutputData(1:50);
          model = ar(z9,4);
Plot the forecasted system response for a given time horizon as a red dashed line.
          K = 100;
          forecast(model,'r--',past_data,K);
1-356
                                                                                              forecast
The plot also displays the past data by default. To change display options, right-click the plot to
access the context menu. For example, to view the estimated standard deviation of the forecasted
output, select ConfidenceRegion from the context menu. To specify number of standard deviations
to plot, double-click the plot and open the Property Editor dialog box. In the dialog box, in the
Options tab, specify the number of standard deviations in Confidence Region for Identified
Models. The default value is 1 standard deviation.
load iddata1 z1
z1 = iddata(cumsum(z1.y),cumsum(z1.u),z1.Ts,'InterSample','foh');
past_data = z1(1:100);
future_inputs = z1.u(101:end);
sys = polyest(z1,[2 2 2 0 0 1],'IntegrateNoise',true);
z1 is an iddata object that contains integrated data. sys is an idpoly model. past_data contains
the first 100 data points of z1.
Forecast the system response into the future for a given time horizon and future inputs.
                                                                                              1-357
1   Functions
          K = 200;
          [yf,x0,sysf,yf_sd,x,x_sd] = forecast(sys,past_data,K,future_inputs);
          yf is the forecasted model response, and yf_sd is the standard deviation of the output. x0 is the
          estimated value for initial states, and sysf is the forecasting state-space model. Also returned are the
          state trajectory, x, and standard deviation of the trajectory, x_sd.
          subplot(3,1,2)
          plot(t, x(:,2),t,x(:,2)+3*x_sd(:,2),'k--',t, x(:,2)-3*x_sd(:,2),'k--')
          title('X_2')
          subplot(3,1,3)
          plot(t,x(:,3),t,x(:,3)+3*x_sd(:,3),'k--',t, x(:,3)-3*x_sd(:,3),'k--')
          title('X_3')
1-358
                                                                                               forecast
The response uncertainty does not grow over the forecasting time span because of the specification
of future inputs.
Load data.
load(fullfile(matlabroot,'toolbox','ident','iddemos','data','predprey2data'));
z = iddata(y,[],0.1);
set(z,'Tstart',0,'OutputUnit',{'Population (in thousands)',...
    'Population (in thousands)'},'TimeUnit','Years');
z is a two output time-series data set (no inputs) from a 1-predator 1-prey population. The population
exhibits a decline in predator population due to crowding. The data set contains 201 data samples
covering 20 years of evolution.
The changes in the predator (y1) and prey (y2) population can be represented as:
                                                                       2
    y2(t) = p3 * y2(t − 1) − p4 * y1(t − 1) * y2(t − 1) − p5 * y2(t − 1)
The nonlinearity in the predator and prey populations can be fit using a nonlinear ARX model with
custom regressors.
                                                                                                1-359
1   Functions
past_data = z(1:100);
          na = [1 0; 0 1];
          nb = [];
          nk = [];
C = {{'y1(t-1)*y2(t-1)'};{'y1(t-1)*y2(t-1)','y2(t-1)^2'}};
Compare the simulated output of sys with measured data to ensure it is a good fit.
compare(past_data,sys);
          forecast(sys,past_data,101);
          legend('Measured','Forecasted');
1-360
                                                                                                 forecast
load iddata3 z3
past_data = z3(1:100);
future_inputs = z3.u(101:end);
sys = polyest(z3,[2 2 2 0 0 1]);
Forecast the system response into the future for a given time horizon and future inputs.
K = size(future_inputs,1);
[yf,x0,sysf] = forecast(sys,past_data,K,future_inputs);
yf is the forecasted model response, x0 is the estimated value for initial states, and sysf is the
forecasting state-space model.
Simulate the forecasting state-space model with inputs, future_inputs, and initial conditions, x0.
opt = simOptions;
opt.InitialCondition = x0;
ys = sim(sysf,future_inputs(1:K),opt);
                                                                                                     1-361
1   Functions
          t = yf.SamplingInstants;
          plot(t,yf.OutputData,'b',t,ys,'.r');
          legend('Forecasted Output','Simulated Output')
          Simulation of forecasting model, sysf, with inputs, future_inputs, and initial conditions, x0,
          yields the forecasted output, yf.
          Input Arguments
          sys — Identified model
          linear model | nonlinear model
          If a model is unavailable, estimate sys from PastData using commands such as ar, arx, armax,
          nlarx, and ssest.
1-362
                                                                                                  forecast
• iddata object — Use observed input and output signals to create an iddata object. For time-
  series data (no inputs), specify as an iddata object with no inputs iddata(output,[]).
• Matrix of doubles — For discrete-time models only. Specify as an N-by-Ny matrix for time-series
  data. Here, N is the number of observations and Ny is the number of outputs.
Time horizon of forecasting, specified as a positive integer. The output, yf, is calculated K steps into
the future, such that the prediction time horizon is Ts*K.
• [] — Future input values are assumed to be zero, or equal to input offset levels (if they are
  specified in opts). For time series models, specify as [].
• iddata object — Specify as an iddata object with no outputs.
• K-by-Nu matrix of doubles — K is the forecast horizon, and Nu is the number of inputs.
   If you have data from multiple experiments, you can specify a cell array of matrices, one for each
   experiment in PastData.
Line style, marker, and color, specified as a character vector. For example, 'b' or 'b+:'.
For more information about configuring Linespec, see the Linespec argument of plot.
Output Arguments
yf — Forecasted response
iddata object
Forecasted response, returned as an iddata object. yf is the forecasted response at times after the
last sample time in PastData. yf contains data for the time interval T0+(N+1:N+K)*T1, where T0
= PastData.Tstart and T1 = PastData.Ts. N is the number of samples in PastData.
Estimated initial states at the start of forecasting, returned as a column vector of size equal to the
number of states. Use x0 with the forecasting model sysf to reproduce the result of forecasting by
pure simulation.
                                                                                                   1-363
1   Functions
          When sys is not a state-space model (idss, idgrey, or idnlgrey), the definition of states depends
          on if sys is linear or nonlinear:
          • Linear model (idpoly, idproc, idtf) – sys is converted to a discrete-time state-space model,
            and x0 is returned as the states of the converted model at a time-point beyond the last data in
            PastData.
                If conversion of sys to idss is not possible, x0 is returned empty. For example, if sys is a MIMO
                continuous-time model with irreducible internal delays.
          • Nonlinear model (idnlhw or idnlarx) — For a definition of the states of idnlarx and idnlhw
            models, see “Definition of idnlarx States” on page 1-527, and “Definition of idnlhw States” on page
            1-557.
          • Discrete-time idss — If sys is a discrete-time idss model, sysf is the same as sys. If sys is a
            linear model that is not a state-space model (idpoly, idproc, idtf), or is a continuous-time
            state-space model (idss, idgrey), sys is converted to a discrete-time idss model. The
            converted model is returned in sysf.
          • idnlarx, idnlhw, or idnlgrey— If sys is a nonlinear model, sysf is the same as sys.
          • Cell array of models — If PastData is multiexperiment, sysf is an array of Ne models, where Ne
            is the number of experiments.
          Simulation of sysf using sim, with inputs, FutureInputs, and initial conditions, x0, yields yf as
          the output. For time-series models, FutureInputs is empty.
          Estimated standard deviations of forecasted response, returned as a K-by-Ny matrix, where K is the
          forecast horizon, and Ny is the number of outputs. The software computes the standard deviation by
          taking into account the model parameter covariance, initial state covariance, and additive noise
          covariance. The additive noise covariance is stored in the NoiseVariance property of the model.
          If PastData is multiexperiment, yf_sd is a cell array of size Ne, where Ne is the number of
          experiments.
          yf_sd is empty if sys is a nonlinear ARX (idnlarx) or Hammerstein-Wiener model (idnlhw). yf_sd
          is also empty if sys does not contain parameter covariance information, that is if getcov(sys) is
          empty. For more information, see getcov.
          Forecasted state trajectory, returned as a K-by-Nx matrix, where K, the forecast horizon and Nx is the
          number of states. x are the states of the forecasting model.
If PastData is multiexperiment, x is a cell array of size Ne, where Ne is the number of experiments.
1-364
                                                                                               forecast
If sys is linear model other than a state-space model (not idss or idgrey), then it is converted to a
discrete-time state-space model, and the states of the converted model are calculated. If conversion
of sys to idss is not possible, x is returned empty. For example, if sys is a MIMO continuous-time
model with irreducible internal delays.
Estimated standard deviations of forecasted states x, returned as a K-by-Ns matrix, where K, the
forecast horizon and Ns is the number of states. The software computes the standard deviation by
taking into account the model parameter covariance, initial state covariance, and additive noise
covariance. The additive noise covariance is stored in the NoiseVariance property of the model.
If PastData is multiexperiment, x_sd is a cell array of size Ne, where Ne is the number of
experiments.
If sys is linear model other than a state-space model (not idss or idgrey), then it is converted to a
discrete-time state-space model, and the states and standard deviations of the converted model are
calculated. If conversion of sys to idss is not possible, x_sd is returned empty. For example, if sys
is a MIMO continuous-time model with irreducible internal delays.
Tips
• Right-clicking the plot opens the context menu, where you can access the following options:
   • Systems — Select systems to view forecasted output. By default, the forecasted output of all
     systems is plotted.
   • Data Experiment — For multi-experiment data only. Toggle between data from different
     experiments.
   • Characteristics — View the following data characteristics:
          The confidence region is not generated for nonlinear ARX and Hammerstein-Wiener models
          and models that do not contain parameter covariance information.
   • Show Past Data — Plot the past output data used for forecasting. By default, the past output
     data is plotted.
   • I/O Grouping — For datasets containing more than one input or output channel. Select
     grouping of input and output channels on the plot.
                                                                                                1-365
1   Functions
                • I/O Selector — For datasets containing more than one input or output channel. Select a subset
                  of the input and output channels to plot. By default, all output channels are plotted.
                • Grid — Add grids to the plot.
                • Normalize — Normalize the y-scale of all data in the plot.
                • Full View — Return to full view. By default, the plot is scaled to full view.
                • Properties — Open the Property Editor dialog box to customize plot attributes.
          See Also
          ar | arx | compare | forecastOptions | iddata | predict | sim | ssest
          Topics
          “Forecast the Output of a Dynamic System”
          “Forecast Multivariate Time Series”
          “Time Series Prediction and Forecasting for Prognosis”
          “Introduction to Forecasting of Dynamic System Response”
Introduced in R2012a
1-366
                                                                                      forecastOptions
forecastOptions
Option set for forecast
Syntax
opt = forecastOptions
opt = forecastOptions(Name,Value)
Description
opt = forecastOptions creates the default option set for forecast. Use dot notation to modify
this option set. Any options that you do not modify retain their default values.
opt = forecastOptions(Name,Value) creates an option set with the options specified by one or
more Name,Value pair arguments.
Examples
You can now use this option set for forecasting. Before forecasting model response, the forecast
command subtracts this offset value from the past input data signal.
z1 and z2 are iddata objects that store SISO input-output data. Create a two-experiment data set
from z1 and z2.
                                                                                              1-367
1   Functions
z = merge(z1,z2);
Estimate a transfer function model with 2 poles using the multi-experiment data.
sys = tfest(z,2);
Specify the offset as -1 and 1 for the output signals of the two experiments.
          Using the option set opt, forecast the response of the model 10 time steps into the future. The
          software subtracts the offset value OutputOffset(i,j) from the output signal i of experiment j
          before using the data in the forecasting algorithm. The removed offsets are added back to generate
          the final result.
y = forecast(sys,z,10,opt)
          y =
          Time domain data set containing 2 experiments.
          y is an iddata object that returns the forecasted response corresponding to each set of past
          experimental data.
          Input Arguments
          Name-Value Pair Arguments
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
          Example: forecastOptions('InitialCondition','e') specifies that the software estimates
          the initial conditions of the measured input-output data such that the 1-step prediction error for
          observed output is minimized.
1-368
                                                                                            forecastOptions
   For nonlinear grey-box models, only those initial states i that are designated as free in the model
   (sys.InitialStates(i).Fixed = false) are estimated. To estimate all the states of the
   model, first specify all the Nx states of the idnlgrey model sys as free.
   for i = 1:Nx
   sys.InitialStates(i).Fixed = false;
   end
   Similarly, to fix all the initial states to values specified in sys.InitialStates, first specify all
   the states as fixed in the sys.InitialStates property of the nonlinear grey-box model.
• x0obj — Specification object created using idpar. Use this object for discrete-time state-space
  models only (idss, idgrey, and idnlgrey). Use x0obj to impose constraints on the initial states
  by fixing their value or specifying minimum or maximum bounds.
Input signal offset for time-domain data, specified as the comma-separated pair consisting of
'InputOffset' and one of the following values:
• [] — No input offsets.
• A column vector of length Nu, where Nu is the number of inputs. When you use the forecast
  command, the software subtracts the offset value InputOffset(i) from the ith input signals in
  the past and future input values. You specify these values in the PastData and FutureInputs
  arguments of forecast. The software then uses the offset subtracted inputs to forecast the model
  response.
• Nu-by-Ne matrix — For multi-experiment data, specify InputOffset as an Nu-by-Ne matrix,
  where Ne is the number of experiments. The software subtracts the offset value
  InputOffset(i,j) from the ith input signal of the jth experiment in the PastData and
  FutureInputs arguments of forecast before forecasting.
Output signal offset for time-domain data, specified as the comma-separated pair consisting of
'OutputOffset' and one of the following values:
• [] — No output offsets.
• A column vector of length Ny, where Ny is the number of outputs. When you use the forecast
  command, the software subtracts the offset value OutputOffset(i) from the ith past output
  signal that you specify in the PastData argument of forecast. The software then uses the offset
  subtracted output to compute the detrended forecasts. The removed offsets are added back to the
  detrended forecasts to generate the final result.
• Ny-by-Ne matrix — For multi-experiment data, specify OutputOffset as an Ny-by-Ne matrix,
  where Ne is the number of experiments. Before forecasting, the software subtracts the offset
  value OutputOffset(i,j) from the ith output signal of the jth experiment in the PastData
  argument of forecast. For an example, see “Specify Output Offset for Forecasting Multi-
  Experiment Data” on page 1-367.
                                                                                                    1-369
1   Functions
          Output Arguments
          opt — Option set for forecast
          forecastOptions option set
          See Also
          forecast | idpar
          Topics
          “Introduction to Forecasting of Dynamic System Response”
Introduced in R2012a
1-370
                                                                                                    fpe
fpe
Akaike’s Final Prediction Error for estimated model
Syntax
value = fpe(model)
value = fpe(model1,...,modeln)
Description
value = fpe(model) returns the Final Prediction Error (FPE) value for the estimated model.
value = fpe(model1,...,modeln) returns the FPE value for multiple estimated models.
Examples
value = fpe(sys)
value = 1.7252
Alternatively, use the Report property of the model to access the value.
sys.Report.Fit.FPE
ans = 1.7252
Pick Model with Optimal Tradeoff Between Accuracy and Complexity Using FPE Criterion
Estimate multiple Output-Error (OE) models and use Akaike's Final Prediction Error (FPE) value to
pick the one with optimal tradeoff between accuracy and complexity.
load iddata2
                                                                                             1-371
1   Functions
          nf = 1:4;
          nb = 1:4;
          nk = 0:4;
          NN = struc(nf,nb,nk);
          models = cell(size(NN,1),1);
          for ct = 1:size(NN,1)
              models{ct} = oe(z2, NN(ct,:));
          end
Compute the small sample-size corrected AIC values for the models, and return the smallest value.
          V = fpe(models{:});
          [Vmin, I] = min(V);
Return the optimal model that has the smallest AICc value.
models{I}
          ans =
          Discrete-time OE model: y(t) = [B(z)/F(z)]u(t) + e(t)
            B(z) = 1.067 z^-2
          Parameterization:
             Polynomial orders:   nb=1   nf=3   nk=2
             Number of free coefficients: 4
             Use "polydata", "getpvec", "getcov" for parameters and their uncertainties.
          Status:
          Estimated using OE on time domain data "z2".
          Fit to estimation data: 86.53%
          FPE: 0.9809, MSE: 0.9615
          Input Arguments
          model — Identified model
          idtf | idgrey | idpoly | idproc | idss | idnlarx, | idnlhw | idnlgrey
          • idtf
          • idgrey
          • idpoly
          • idproc
          • idss
          • idnlarx, except nonlinear ARX model that includes a binary-tree or neural network nonlinearity
            estimator
1-372
                                                                                                       fpe
• idnlhw
• idnlgrey
Output Arguments
value — Final Prediction Error (FPE) value
scalar | vector
Final Prediction Error (FPE) value, returned as a scalar or vector. For multiple models, value is a
row vector where value(k) corresponds to the kth estimated model modelk.
More About
Akaike's Final Prediction Error (FPE)
Akaike's Final Prediction Error (FPE) criterion provides a measure of model quality by simulating the
situation where the model is tested on a different data set. After computing several different models,
you can compare them using this criterion. According to Akaike's theory, the most accurate model has
the smallest FPE.
If you use the same data set for both model estimation and validation, the fit always improves as you
increase the model order and, therefore, the flexibility of the model structure.
where:
If number of parameters exceeds the number of samples, FPE is not computed when model
estimation is performed (model.Report.FPE is empty). The fpe command returns NaN.
Tips
• The software computes and stores the FPE value during model estimation. If you want to access
  this value, see the Report.Fit.FPE property of the model.
References
[1] Ljung, L. System Identification: Theory for the User, Upper Saddle River, NJ, Prentice-Hall PTR,
        1999. See sections 7.4 and 16.4.
See Also
aic | goodnessOfFit
                                                                                                1-373
1   Functions
          Topics
          “Loss Function and Model Quality Metrics”
1-374
                                                                                                  frdata
frdata
Access data for frequency response data (FRD) object
Syntax
[response,freq] = frdata(sys)
[response,freq,covresp] = frdata(sys)
[response,freq,Ts,covresp] = frdata(sys,'v')
[response,freq,Ts] = frdata(sys)
Description
[response,freq] = frdata(sys) returns the response data and frequency samples of the FRD
model sys. For an FRD model with Ny outputs and Nu inputs at Nf frequencies:
• response is an Ny-by-Nu-by-Nf multidimensional array where the (i,j) entry specifies the
  response from input j to output i.
• freq is a column vector of length Nf that contains the frequency samples of the FRD model.
See the frd reference page for more information on the data format for FRD response data.
[response,freq] = frdata(sys,'v')
forces frdata to return the response data as a column vector rather than a 3-dimensional array (see
example below). Similarly
Other properties of sys can be accessed with get or by direct structure-like referencing (e.g.,
sys.Frequency).
Arguments
The input argument sys to frdata must be an FRD model.
Examples
                                                                                                  1-375
1   Functions
          Create a frequency response data model by computing the response of a transfer function on a grid of
          frequencies.
          H = tf([-1.2,-2.4,-1.5],[1,20,9.1]);
          w = logspace(-2,3,101);
          sys = frd(H,w);
          sys is a SISO frequency response data (frd) model containing the frequency response at 101
          frequencies.
[response,freq] = frdata(sys);
          See Also
          frd | freqresp | get | idfrd | set | spectrum
1-376
                                                                                                 freqresp
freqresp
Frequency response over grid
Syntax
[H,wout] = freqresp(sys)
H = freqresp(sys,w)
H = freqresp(sys,w,units)
[H,wout,covH] = freqresp(idsys,...)
Description
[H,wout] = freqresp(sys) returns the frequency response on page 1-380 of the dynamic system
model sys at frequencies wout. The freqresp command automatically determines the frequencies
based on the dynamics of sys.
H = freqresp(sys,w) returns the frequency response on page 1-380 on the real frequency grid
specified by the vector w.
Input Arguments
sys
Vector of real frequencies at which to evaluate the frequency response. Specify frequencies in units of
rad/TimeUnit, where TimeUnit is the time units specified in the TimeUnit property of sys.
units
Units of the frequencies in the input frequency vector w, specified as one of the following values:
• 'rad/TimeUnit' — radians per the time unit specified in the TimeUnit property of sys
• 'cycles/TimeUnit' — cycles per the time unit specified in the TimeUnit property of sys
• 'rad/s'
• 'Hz'
• 'kHz'
• 'MHz'
• 'GHz'
• 'rpm'
                                                                                                  1-377
1   Functions
Default: 'rad/TimeUnit'
idsys
          Output Arguments
          H
          If sys is an individual dynamic system model having Ny outputs and Nu inputs, H is a 3D array with
          dimensions Ny-by-Nu-by-Nw, where Nw is the number of frequency points. Thus, H(:,:,k) is the
          response at the frequency w(k) or wout(k).
          If sys is a model array of size [Ny Nu S1 ... Sn], H is an array with dimensions Ny-by-Nu-by-Nw-by-
          S1-by-...-by-Sn] array.
          If sys is a frequency response data model (such as frd, genfrd, or idfrd), freqresp(sys,w)
          evaluates to NaN for values of w falling outside the frequency interval defined by sys.frequency.
          The freqresp command can interpolate between frequencies in sys.frequency. However,
          freqresp cannot extrapolate beyond the frequency interval defined by sys.frequency.
wout
          Vector of frequencies corresponding to the frequency response values in H. If you omit w from the
          inputs to freqresp, the command automatically determines the frequencies of wout based on the
          system dynamics. If you specify w, then wout = w
covH
          Covariance of the response H. The covariance is a 5D array where covH(i,j,k,:,:) contains the 2-
          by-2 covariance matrix of the response from the ith input to the jth output at frequency w(k). The
          (1,1) element of this 2-by-2 matrix is the variance of the real part of the response. The (2,2) element
          is the variance of the imaginary part. The (1,2) and (2,1) elements are the covariance between the
          real and imaginary parts of the response.
Examples
                               1
                         0
                              s+1
                sys =
                        s−1
                               1
                        s+2
          sys11 = 0;
          sys22 = 1;
          sys12 = tf(1,[1 1]);
1-378
                                                                                              freqresp
[H,wout] = freqresp(sys);
H is a 2-by-2-by-45 array. Each entry H(:,:,k) in H is a 2-by-2 matrix giving the complex frequency
response of all input-output pairs of sys at the corresponding frequency wout(k). The 45
frequencies in wout are automatically selected based on the dynamics of sys.
                   1
             0
                  s+1
    sys =
            s−1
                   1
            s+2
sys11   = 0;
sys22   = 1;
sys12   = tf(1,[1 1]);
sys21   = tf([1 -1],[1 2]);
sys =   [sys11,sys12;sys21,sys22];
Create a logarithmically-spaced grid of 200 frequency points between 10 and 100 radians per second.
w = logspace(1,2,200);
Compute the frequency response of the system on the specified frequency grid.
H = freqresp(sys,w);
H is a 2-by-2-by-200 array. Each entry H(:,:,k) in H is a 2-by-2 matrix giving the complex frequency
response of all input-output pairs of sys at the corresponding frequency w(k).
Compute the frequency response and associated covariance for an identified process model at its
peak response frequency.
load iddata1 z1
model = procest(z1,'P2UZ');
Compute the frequency at which the model achieves the peak frequency response gain. To get a more
accurate result, specify a tolerance value of 1e-6.
                                                                                               1-379
1   Functions
[gpeak,fpeak] = getPeakGain(model,1e-6);
          Compute the frequency response and associated covariance for model at its peak response
          frequency.
[H,wout,covH] = freqresp(model,fpeak);
H is the response value at fpeak frequency, and wout is the same as fpeak.
          covH is a 5-dimensional array that contains the covariance matrix of the response from the input to
          the output at frequency fpeak. Here covH(1,1,1,1,1) is the variance of the real part of the
          response, and covH(1,1,1,2,2) is the variance of the imaginary part. The covH(1,1,1,1,2) and
          covH(1,1,1,2,1) elements are the covariance between the real and imaginary parts of the
          response.
          More About
          Frequency Response
          In continuous time, the frequency response at a frequency ω is the transfer function value at s = jω.
          For state-space models, this value is given by
                                         −1
                H( jω) = D + C( jωI − A)      B
          In discrete time, the frequency response is the transfer function evaluated at points on the unit circle
          that correspond to the real frequencies. freqresp maps the real frequencies w(1),..., w(N) to points
                                                           jωT
          on the unit circle using the transformation z = e s. Ts is the sample time. The function returns the
          values of the transfer function at the resulting z values. For models with unspecified sample time,
          freqresp uses Ts = 1.
          Algorithms
          For transfer functions or zero-pole-gain models, freqresp evaluates the numerator(s) and
          denominator(s) at the specified frequency points. For continuous-time state-space models (A, B, C, D),
          the frequency response is
                              −1
                D + C( jω − A)     B, ω =ω1, …, ωN
          For efficiency, A is reduced to upper Hessenberg form and the linear equation (jω − A)X = B is solved
          at each frequency point, taking advantage of the Hessenberg structure. The reduction to Hessenberg
          form provides a good compromise between efficiency and reliability. See [1] for more details on this
          technique.
          Alternatives
          Use evalfr to evaluate the frequency response at individual frequencies or small numbers of
          frequencies. freqresp is optimized for medium-to-large vectors of frequencies.
1-380
                                                                                            freqresp
References
[1] Laub, A.J., "Efficient Multivariable Frequency Response Computations," IEEE Transactions on
        Automatic Control, AC-26 (1981), pp. 407-408.
See Also
bode | evalfr | interp | nichols | nyquist | sigma | spectrum
                                                                                             1-381
1   Functions
          fselect
          Select frequency points or range in FRD model
          Syntax
          subsys = fselect(sys,fmin,fmax)
          subsys = fselect(sys,index)
          Description
          subsys = fselect(sys,fmin,fmax) takes an FRD model sys and selects the portion of the
          frequency response between the frequencies fmin and fmax. The selected range [fmin,fmax]
          should be expressed in the FRD model units. For an IDFRD model, the SpectrumData,
          CovarianceData and NoiseCovariance values, if non-empty, are also selected in the chosen
          range.
          subsys = fselect(sys,index) selects the frequency points specified by the vector of indices
          index. The resulting frequency grid is
sys.Frequency(index)
          See Also
          fcat | fdel | frd | idfrd | interp
1-382
                                                                                                get
get
Access model property values
Syntax
Value = get(sys,'PropertyName')
Struct = get(sys)
Description
Value = get(sys,'PropertyName') returns the current value of the property PropertyName of
the model object sys. 'PropertyName' can be the full property name (for example, 'UserData')
or any unambiguous case-insensitive abbreviation (for example, 'user'). See reference pages for the
individual model object types for a list of properties available for that model.
Struct = get(sys) converts the TF, SS, or ZPK object sys into a standard MATLAB structure
with the property names as field names and the property values as field values.
get(sys)
Examples
                1
      H(z) =
               z+2
Specify the sample time as 0.1 seconds and input channel name as Voltage.
h = tf(1,[1 2],0.1,'InputName','Voltage')
h =
get(h)
                                                                                             1-383
1   Functions
          The numerator data is stored as a cell array, thus the Numerator property is a cell array containing
          the row vector [0 1].
          num{1}
ans = 1×2
0 1
ans = 0.1000
ans = 0.1000
          Tips
          An alternative to the syntax
          Value = get(sys,'PropertyName')
1-384
                                                                                                   get
For example,
sys.Ts
sys.A
sys.user
return the values of the sample time, A matrix, and UserData property of the (state-space) model
sys.
See Also
frdata | getcov | getpvec | idssdata | polydata | set | ssdata | tfdata
                                                                                             1-385
1   Functions
          getcov
          Parameter covariance of identified model
          Syntax
          cov_data = getcov(sys)
          cov_data = getcov(sys,cov_type)
          cov_data = getcov(sys,cov_type,'free')
          Description
          cov_data = getcov(sys) returns the raw covariance of the parameters of an identified model.
          • If sys is a single model, then cov_data is an np-by-np matrix. np is the number of parameters of
            sys.
          • If sys is a model array, then cov_data is a cell array of size equal to the array size of sys.
          cov_data = getcov(sys,cov_type,'free') returns the covariance data of only the free model
          parameters.
Examples
          load iddata1 z1
          sys = tfest(z1,2);
cov_data = getcov(sys)
cov_data = 5×5
1-386
                                                                                           getcov
sys.Denominator(1) is fixed to 1 and not treated as a parameter. The covariance matrix entries
corresponding to the delay parameter (fifth row and column) are zero because the delay was not
estimated.
Get the raw parameter covariance for the models in the array.
cov_data = getcov(sysarr)
cov_data is a 2-by-1 cell array. cov_data{1} and cov_data{2} are the raw parameter covariance
matrices for sys1 and sys2.
load iddata1 z1
z1.y = cumsum(z1.y);
sys is an idtf model with six parameters, four of which are estimated.
cov_type = 'value';
cov_data = getcov(sys,cov_type,'free')
cov_data = 4×4
105 ×
                                                                                           1-387
1   Functions
cov_data is a 4x4 covariance matrix, with entries corresponding to the four estimated parameters.
          Get the factored parameter covariance for the models in the array.
          cov_type = 'factors';
          cov_data = getcov(sysarr,cov_type)
          cov_data is a 2-by-1 structure array. cov_data(1) and cov_data(2) are the factored covariance
          structures for sys1 and sys2.
1-388
                                                                                                  getcov
sys, an idtf model, has six parameters, four of which are estimated.
cov_type = 'factors';
cov_data = getcov(sys,cov_type,'free');
Input Arguments
sys — Identified model
idtf, idss, idgrey, idpoly, idproc, idnlarx, idnlhw, or idnlgrey object | model array
Identified model, specified as an idtf, idss, idgrey, idpoly, idproc, idnlarx, idnlhw, or
idnlgrey model or an array of such models.
The getcov command returns cov_data as [] for idnlarx and idnlhw models because these
models do not store parameter covariance data.
   Use this option for fetching the covariance data if the covariance matrix contains nonfinite values,
   is not positive definite, or is ill conditioned. You can calculate the response uncertainty using the
   covariance factors instead of the numerically disadvantageous covariance matrix.
This option does not offer a numerical advantage in the following cases:
Output Arguments
cov_data — Parameter covariance of sys
matrix or cell array of matrices | structure or cell array of structures
                                                                                                  1-389
1   Functions
          Parameter covariance of sys, returned as a matrix, cell array of matrices, structure, or cell array of
          structures. cov_data is [] for idnlarx and idnlhw models.
          • If sys is a single model and cov_type is 'value', then cov_data is an np-by-np matrix. np is
            the number of parameters of sys.
                Free = cov_factored.Free;
                T = cov_factored.T;
                R = cov_factored.R;
                np = nparams(sys);
                cov_matrix = zeros(np);
                cov_matrix(Free, Free) = T*inv(R'*R)*T';
          See Also
          getpvec | nparams | rsample | setcov | sim | simsd
          Topics
          “What Is Model Covariance?”
          “Types of Model Uncertainty Information”
Introduced in R2012a
1-390
                                                                                            getDelayInfo
getDelayInfo
Get input/output delay information for idnlarx model structure
Syntax
DELAYS = getDelayInfo(MODEL)
DELAYS = getDelayInfo(MODEL,TYPE)
Description
DELAYS = getDelayInfo(MODEL) obtains the maximum delay in each input and output variable of
an idnlarx model.
Delay information is useful for determining the number of states in the model. For nonlinear ARX
models, the states are related to the set of delayed input and output variables that define the model
structure (regressors). For example, if an input or output variable p has a maximum delay of D
samples, then it contributes D elements to the state vector:
The number of states of a nonlinear ARX model equals the sum of the maximum delays of each input
and output variable. For more information about the definition of states for idnlarx models, see
“Definition of idnlarx States” on page 1-527
Input Arguments
getDelayInfo accepts the following arguments:
   • 'all': Default value. DELAYS contains the maximum delays across each output (vector of ny
     +nu entries, where [ny, nu] = size(MODEL)).
   • 'channelwise': DELAYS contains delay values separated for each output (ny-by-(ny+nu)
     matrix).
Output Arguments
• DELAYS: Contains delay information in a vector of length ny+nu arranged with output channels
  preceding the input channels, i.e., [y1, y2,.., u1, u2,..].
                                                                                                 1-391
1   Functions
Examples
Get Input and Output Delay Information for Nonlinear ARX Model
M = idnlarx([2 0 2 2 1 1 0 0; 1 0 1 5 0 1 1 0],'linear');
Del = getDelayInfo(M,'channelwise')
Del = 2×5
                 2       0       2       1        0
                 1       0       1       5        0
          The matrix Del contains the maximum delays for the first and second output of model M. You can
          interpret the contents of matrix Del as follows:
          • In the dynamics for output 1 ( y1), the maximum delays in channels y1, y2, u1, u2, u3 are 2, 0, 2, 1,
            and 0 respectively.
          • Similarly, in the dynamics for output 2 (y2) of the model, the maximum delays in channels y1, y2,
            u1, u2, u3 are 1, 0, 1, 5, and 0 respectively.
Find maximum delays for all the input and output variables in the order y1, y2, u1, u2, u3.
Del = getDelayInfo(M,'all')
Del = 1×5
2 0 2 5 0
          Note, The maximum delay across all output equations can be obtained by executing MaxDel =
          max(Del,[],1). Since input u2 has 5 delays (the fourth entry in Del), there are 5 terms
          corresponding to u2 in the state vector. Applying this definition to all I/O channels, the complete state
          vector for model M becomes:
X(t) = [y1(t − 1), y1(t − 2), u1(t − 1), u1(t − 2), u2(t − 1), u2(t − 2), u2(t − 3), u2(t − 4), u2(t − 5)]
          See Also
          data2state | getreg | idnlarx
Introduced in R2008b
1-392
                                                                                           getexp
getexp
Specific experiments from multiple-experiment data set
Syntax
d1 = getexp(data,ExperimentNumber)
d1 = getexp(data,ExperimentName)
Description
d1 = getexp(data,ExperimentNumber) retrieves specific experiments from multiple-experiment
data set. data is an iddata object that contains several experiments. d1 is another iddata object
containing the indicated experiment(s). ExperimentNumber is the experiment number as in d1 =
getexp(data,3) or d1 = getexp(data,[4 2]).
See merge (iddata) and iddata for how to create multiple-experiment data objects.
                                                                                           1-393
1   Functions
          getinit
          Values of idnlgrey model initial states
          Syntax
          getinit(model)
          getinit(model,prop)
          Arguments
          model
                Name of the idnlgrey model object.
          Property
                Name of the InitialStates model property field, such as 'Name', 'Unit', 'Value',
                'Minimum', 'Maximum', and 'Fixed'.
Default: 'Value'.
          Description
          getinit(model) gets the initial-state values in the 'Value' field of the InitialStates model
          property.
          getinit(model,prop) gets the initial-state values of the prop field of the InitialStates model
          property. prop can be 'Name', 'Unit', 'Value', 'Minimum', 'Maximum', and 'Fixed'.
The returned values are an Nx-by-1 cell array of values, where Nx is the number of states.
          See Also
          getpar | idnlgrey | setinit | setpar
Introduced in R2007a
1-394
                                                                                               getoptions
getoptions
Return @PlotOptions handle or plot options property
Syntax
p = getoptions(h)
p = getoptions(h,propertyname)
Description
p = getoptions(h) returns the plot options handle associated with plot handle h. p contains all
the settable options for a given response plot.
p = getoptions(h,'Grid')
For a list of the properties and values available for each plot type, see “Properties and Values
Reference” (Control System Toolbox).
See Also
setoptions
Introduced in R2012a
                                                                                                   1-395
1   Functions
          idParametric/getpar
          Obtain attributes such as values and bounds of linear model parameters
          Syntax
          value = getpar(sys,'value')
          free = getpar(sys,'free')
          bounds = getpar(sys,'bounds')
          label = getpar(sys,'label')
          getpar(sys)
          Description
          value = getpar(sys,'value') returns the parameter values of the model sys. If sys is a model
          array, the returned value is a cell array of size equal to the model array.
bounds = getpar(sys,'bounds') returns the minimum and maximum bounds on the parameters.
          getpar(sys) prints a table of parameter values, labels, free status and minimum and maximum
          bounds.
Examples
val = 5×1
                -0.7519
                -0.4341
                 0.4442
                 0.0119
1-396
                                                                                   idParametric/getpar
0.3431
Get the free parameters and their bounds for a process model.
Construct a process model, and set its parameter values and free status.
m = idproc('P2DUZI');
m.Kp = 1;
m.Tw = 100;
m.Zeta = .3;
m.Tz = 10;
m.Td = 0.4;
m.Structure.Td.Free = 0;
Val = getpar(m,'Value')
Val = 5×1
    1.0000
  100.0000
    0.3000
    0.4000
   10.0000
Free = getpar(m,'Free')
   1
   1
   1
   0
   1
The output indicates that Td is a fixed parameter and the remaining parameters are free.
MinMax = getpar(m,'bounds')
MinMax = 5×2
-Inf Inf
                                                                                               1-397
1   Functions
                   0   Inf
                   0   Inf
                   0   Inf
                -Inf   Inf
FreeValues = Val(Free)
FreeValues = 4×1
                  1.0000
                100.0000
                  0.3000
                 10.0000
FreeValBounds = MinMax(Free,:)
FreeValBounds = 4×2
                -Inf   Inf
                   0   Inf
                   0   Inf
                -Inf   Inf
          load iddata8;
          init_data = z8(1:100);
          na = 1;
          nb = [1 1 1];
          nc = 1;
          nk = [0 0 0];
          sys = armax(init_data,[na nb nc nk]);
sys.Structure.A.Info(2).Label = 'a2';
label = getpar(sys,'label')
1-398
                                                                                 idParametric/getpar
    {0x0 char}
    {0x0 char}
load iddata8;
init_data = z8(1:100);
na = 4;
nb = [3 2 3];
nc = 2;
nk = [0 0 0];
sys = armax(init_data,[na nb nc nk]);
getpar(sys)
------------------------------------------------------
  # Label      Value   Free       Min.         Max.
------------------------------------------------------
  1.         -1.4328    1       -Inf          Inf
  2.           0.497    1       -Inf          Inf
  3.         0.22904    1       -Inf          Inf
  4.        -0.09849    1       -Inf          Inf
  5.        -0.10246    1       -Inf          Inf
  6.          1.1671    1       -Inf          Inf
  7.         0.39579    1       -Inf          Inf
  8.         0.97219    1       -Inf          Inf
  9.        0.026995    1       -Inf          Inf
 10.        -0.17113    1       -Inf          Inf
 11.         0.16155    1       -Inf          Inf
 12.         0.48468    1       -Inf          Inf
 13.         -1.8871    1       -Inf          Inf
 14.         0.97391    1       -Inf          Inf
Input Arguments
sys — Identified linear model
idss | idproc | idgrey | idtf | idpoly | array of model objects
Identified linear model, specified as an idss, idpoly, idgrey, idtf, or idfrd model object or an
array of model objects.
Output Arguments
value — Parameter values
vector of doubles
                                                                                             1-399
1   Functions
          Minimum and maximum bounds on parameters, returned as a double matrix of size nparams(sys)-
          by-2. The first column contains the minimum bound, and the second column the maximum bound.
          Parameter labels, returned as a cell array of character vectors of length nparams(sys). For
          example, {'a2','a3'}, if nparams(sys) is two.
          See Also
          getcov | getpvec | idssdata | polydata | setpar | tfdata
Introduced in R2013b
1-400
                                                                                                 getpar
getpar
Parameter values and properties of idnlgrey model parameters
Syntax
getpar(model)
getpar(model,prop)
Arguments
model
   Name of the idnlgrey model object.
Property
   Name of the Parameters model property field, such as 'Name', 'Unit', 'Value', 'Minimum',
   'Maximum', or 'Fixed'.
Default: 'Value'.
Description
getpar(model) gets the model parameter values in the 'Value' field of the Parameters model
property.
getpar(model,prop) gets the model parameter values in the prop field of the Parameters model
property. prop can be 'Name', 'Unit', 'Value', 'Minimum', and 'Maximum'.
The returned values are an Np-by-1 cell array of values, where Np is the number of parameters.
See Also
getinit | getpvec | idnlgrey | setinit | setpar
Introduced in R2007a
                                                                                                 1-401
1   Functions
          getpvec
          Model parameters and associated uncertainty data
          Syntax
          pvec = getpvec(sys)
          [pvec,pvec_sd] = getpvec(sys)
          [ ___ ] = getpvec(sys,'free')
          Description
          pvec = getpvec(sys) returns a vector, pvec, containing the values of all the parameters of the
          identified model sys.
          [pvec,pvec_sd] = getpvec(sys) also returns the 1 standard deviation value of the uncertainty
          associated with the parameters of sys. If the model covariance information for sys is not available,
          pvec_sd is [].
          [ ___ ] = getpvec(sys,'free') returns data for only the free parameters of sys, using any of
          the output arguments in previous syntaxes. For idnlarx and idnlhw models, all parameters are
          treated as free.
          Input Arguments
          sys
Identified model.
          Identified model, specified as an idtf, idss, idgrey, idpoly, idproc, idnlarx, idnlhw, or
          idnlgrey model or an array of such models.
          Output Arguments
          pvec
          If sys is an array of models, then pvec is a cell array with parameter value vectors corresponding to
          each model in sys. pvec is [] for idnlarx and idnlhw models that have not been estimated.
pvec_sd
          If the model covariance information for sys is not available, pvec_sd is []. Thus, pvec_sd is always
          [] for idnlarx and idnlhw models because these models do not store parameter covariance
          information.
          If sys is an array of models, then pvec_sd is a cell array with standard deviation vectors
          corresponding to each model in sys.
1-402
                                                                                             getpvec
Examples
sys = tfest(z1,3);
pvec = getpvec(sys);
sys = ssest(z2,3);
Retrieve the model parameters, pvec, and associated standard deviations, pvec_sd, from the
estimated model.
[pvec,pvec_sd] = getpvec(sys);
sys = ssest(z2,3);
Retrieve the values of the free parameters from the estimated model.
pvec = getpvec(sys,'free');
See Also
getcov | idssdata | setpvec | tfdata | zpkdata
Introduced in R2012a
                                                                                             1-403
1   Functions
          getreg
          Regressor expressions and numerical values in nonlinear ARX model
          Syntax
          Rs    =   getreg(model)
          Rs    =   getreg(model,subset)
          Rm    =   getreg(model,subset,data)
          Rm    =   getreg(model,subset,data,init)
          Description
          Rs = getreg(model) returns expressions for computing regressors in the nonlinear ARX model.
          model is an idnlarx object.
          Input Arguments
          data
                iddata object containing measured data.
          init
                Initial conditions of your data:
          model
                iddata object representing nonlinear ARX model.
          subset
                Subset of all regressors, specified as one of the following values:
1-404
                                                                                                   getreg
Output Arguments
Rm
     Matrix of regressor values for all or a specified subset of regressors. Each matrix in Rm contains
     as many rows as there are data samples. For a model with ny outputs, Rm is an ny-by-1 cell array
     of matrices. When data contains multiple experiments, Rm is a cell array where each element
     corresponds to a matrix of regressor values for an experiment.
Rs
     Regressor expressions represented as a cell array of character vectors. For a model with ny
     outputs, Rs is an ny-by-1 cell array of cell array of character vectors. For example, the expression
     'u1(t-2)' computes the regressor by delaying the input signal u1 by two time samples.
     Similarly, the expression 'y2(t-1)' computes the regressor by delaying the output signal y2 by
     one time sample.
     The order of regressors in Rs corresponds to regressor indices in the idnlarx object property
     model.NonlinearRegressors.
Examples
Get Regressor Expressions and Values, and Evaluate Predicted Model Output
Create data object and use first 1000 samples for estimation.
  z = iddata(y,u,Ts);
  ze = z(1:1000);
                                                                                                   1-405
1   Functions
Rm = getreg(model,'all',ze);
Y = evaluate(model.Nonlinearity,Rm);
Y_p = predict(model,ze,1,'z');
          See Also
          addreg | customreg | evaluate | polyreg
          Topics
          “Identifying Nonlinear ARX Models”
Introduced in R2007a
1-406
                                                                                         getStateEstimate
getStateEstimate
Extract best state estimate and covariance from particles
Syntax
State = getStateEstimate(pf)
[State,StateCovariance] = getStateEstimate(pf)
Description
State = getStateEstimate(pf) returns the best state estimate based on the current set of
particles. The estimate is extracted based on the StateEstimationMethod property from the
particleFilter object, pf.
The State and StateCovariance information can directly be accessed as properties of the particle
filter object pf, as pf.State and pf.StateCovariance. However, when both these quantities are
needed, using the getStateEstimation method with two output arguments is more
computationally efficient.
Examples
Create a particle filter, and set the state transition and measurement likelihood functions.
myPF = particleFilter(@vdpParticleFilterStateFcn,@vdpMeasurementLikelihoodFcn);
Initialize the particle filter at state [2; 0] with unit covariance, and use 1000 particles.
myPF.StateEstimationMethod = 'mean';
myPF.ResamplingMethod = 'systematic';
myPF
myPF =
  particleFilter with properties:
           NumStateVariables:       2
                NumParticles:       1000
          StateTransitionFcn:       @vdpParticleFilterStateFcn
    MeasurementLikelihoodFcn:       @vdpMeasurementLikelihoodFcn
     IsStateVariableCircular:       [0 0]
                                                                                                  1-407
1   Functions
          Get the best state estimate and covariance based on the StateEstimationMethod property.
          [State, StateCovariance] = getStateEstimate(myPF)
State = 2×1
                 2.1018
                -0.1413
StateCovariance = 2×2
                 0.0175   -0.0096
                -0.0096    0.5394
          Input Arguments
          pf — Particle filter
          particleFilter object
          Output Arguments
          State — Best state estimate
          [ ] (default) | vector
Best state estimate, defined as a vector based on the condition of the StateOrientation property:
1-408
                                                                                 getStateEstimate
See Also
correct | initialize | particleFilter | predict
Topics
“Nonlinear State Estimation Using Unscented Kalman Filter and Particle Filter”
“What Is Online Estimation?”
Introduced in R2017b
                                                                                          1-409
1   Functions
          getTrend
          Data offset and trend information
          Syntax
          T = getTrend(data)
          T = getTrend(data,0)
          T = getTrend(data,1)
          Description
          T = getTrend(data) constructs a TrendInfo object to store offset, mean, or linear trend
          information for detrending or retrending data. You can assign specific offset and slope values to T.
          T = getTrend(data,0) computes the means of input and output signals and stores them as
          InputOffset and OutputOffset properties of T, respectively.
          T = getTrend(data,1) computes a best-fit straight line for both input and output signals and
          stores them as properties of T.
Examples
load dryer2
Create a data object with sample time of 0.08 seconds and plot it.
          data = iddata(y2,u2,0.08);
          plot(data)
1-410
                                                                     getTrend
T = getTrend(data);
T.InputOffset = 5;
T.OutputOffset = 5;
data_d = detrend(data,T);
hold on
plot(data_d)
                                                                      1-411
1   Functions
get(T)
Compute input-output signal means, store them, and detrend the data.
load dryer2
data = iddata(y2,u2,0.08);
1-412
                                                         getTrend
T = getTrend(data,0);
data_d = detrend(data,T);
plot(data,data_d)
See Also
TrendInfo | detrend | retrend
Topics
“Handling Offsets and Trends in Data”
Introduced in R2009a
                                                          1-413
1   Functions
          goodnessOfFit
          Goodness of fit between test and reference data for analysis and validation of identified models
          Syntax
          fit = goodnessOfFit(x,xref,cost_func)
          Description
          goodnessOfFit returns fit values that represent the error norm between test and reference data
          sets. If you want to compare and visualize simulated model output with measurement data, see also
          compare.
          fit = goodnessOfFit(x,xref,cost_func) returns the goodness of fit between the test data x
          and the reference data xref using the cost function cost_func. fit is a quantitative representation
          of the closeness of x to xref. To perform multiple test-to-reference fit comparisons, you can specify x
          and xref as cell arrays of equal size that contain multiple test and reference data sets. With cell
          array inputs, fit returns an array of fit values.
Examples
          Find the goodness of fit between measured output data and the simulated output of an estimated
          model.
          load iddata1 z1
          yref = z1.y;
z1 is an iddata object containing measured input-output data. z1.y is the measured output.
Estimate a second-order transfer function model and simulate the model output y_est.
          sys = tfest(z1,2);
          y_est = sim(sys,z1(:,[],:));
          Calculate the goodness of fit, or error norm, between the measured and estimated outputs. Specify
          the normalized root mean squared error (NRMSE) as the cost function.
          cost_func = 'NRMSE';
          y = y_est.y;
          fit = goodnessOfFit(y,yref,cost_func)
fit = 0.2943
          Alternatively, you can use compare to calculate the fit. compare uses the NRMSE cost function, and
          expresses the fit percentage using the one's complement of the error norm. The fit relationship
1-414
                                                                                        goodnessOfFit
between compare and goodnessOfFit is therefore fitcompare = 1 − fitgof * 100. A compare result of
100% is equivalent to a goodnessOfFit result of 0.
Specify an initial condition of zero to match the initial condition that goodnessOfFit assumes.
opt = compareOptions('InitialCondition','z');
compare(z1,sys,opt);
Find the goodness of fit between measured and estimated outputs for two models.
Obtain the input-output measurements z2 from iddata2. Copy the measured output into reference
output yref.
load iddata2 z2
yref = z2.y;
sys2 = tfest(z2,2);
sys4 = tfest(z2,4);
                                                                                                  1-415
1   Functions
          Create cell arrays from the reference and estimated outputs. The reference data set is the same for
          both model comparisons, so create identical reference cells.
          yrefc = {yref yref};
          yc = {y2 y4};
fit_nrmse = 1×2
0.1429 0.1439
fit_nmse = goodnessOfFit(yc,yrefc,'NMSE')
fit_nmse = 1×2
0.0204 0.0207
fit_mse = goodnessOfFit(yc,yrefc,'MSE')
fit_mse = 1×2
1.0811 1.0967
          A fit value of 0 indicates a perfect fit between reference and estimated outputs. The fit value rises as
          fit goodness decreases. For all three cost functions, the fourth-order model produces a better fit than
          the second-order model.
          Input Arguments
          x — Data to test
          matrix (default) | cell array
          • For a single test data set, specify an Ns-by-N matrix, where Ns is the number of samples and N is
            the number of channels. You must specify cost_fun as 'NRMSE' or 'NMSE' to use multiple-
            channel data.
          • For multiple test data sets, specify a cell array of length Nd, where Nd is the number of test-to-
            reference pairs and each cell contains one data matrix.
1-416
                                                                                                       goodnessOfFit
• For a single reference data set, specify an Ns-by-N matrix, where Ns is the number of samples and
  N is the number of channels. xref must be the same size as x. You must specify cost_fun as
  'NRMSE' or 'NMSE' to use multiple-channel data.
• For multiple reference data sets, specify a cell array of length Nd, where Nd is the number of test-
  to-reference pairs and each cell contains one reference data matrix. As with the individual data
  matrices, the cell array sizes for x and xref must match. Each ith element of fit corresponds to
  the pairs of the ith cells of x and xref.
Cost function to determine goodness of fit, specified as one of the following values. In the equations,
the value fit applies to a single pairing of test and reference data sets.
Output Arguments
fit — Goodness of fit
scalar | row vector | cell array
Goodness of fit between test and reference data pairs, returned as a scalar, a row vector, or a cell
array.
                                                                                                             1-417
1   Functions
• For a single test and reference data set pair, fit is returned as a scalar or row vector.
                Each element of fit contains the goodness of fit values for the corresponding test data and
                reference pair.
Possible values for individual fit elements depend on the selection of cost_func.
          • If cost_func is 'MSE', each fit value is a positive scalar that grows with the error between test
            and reference data. A fit value of 0 indicates a perfect match between test and reference data.
          • If cost_func is 'NRMSE' or 'NMSE', fit values vary between -Inf and 1.
          Compatibility Considerations
          goodnessOfFit: Fit result represents the error norm for all three cost functions, with a
          value of zero indicating a perfect fit
          Behavior changed in R2020a
          goodnessOfFit now returns the error norm E as the fit value for all three cost functions (MSE,
          NRMSE, and NMSE). Previously, goodnessOfFit returned the one's complement of the error norm,
          1-E, for fit values that used the NRMSE or NMSE cost functions. This change allows consistent fit-
          value interpretation across the three cost functions, with the ideal fit value of zero representing a
          perfect fit.
          Previously computed NRMSE and NMSE fit values are the one's complements of the fit values
          computed with the current software. Similarly, the NRMSE fit value is now the one's complement of
          the fit used in the percentage value that compare computes. For example, if the previous
          goodnessOfFit fit value was 0.8, the current fit value is 0.2. A goodnessOfFit fit value of 0.2 is
          equivalent to a compare fit percentage of 80%.
          See Also
          aic | compare | fpe | resid
Introduced in R2012a
1-418
                                                                                             greyest
greyest
Linear grey-box model estimation
Syntax
sys = greyest(data,init_sys)
sys = greyest(data,init_sys,opt)
Description
sys = greyest(data,init_sys) estimates a linear grey-box model, sys, using time or frequency
domain data, data. The dimensions of the inputs and outputs of data and init_sys, an idgrey
model, must match. sys is an identified idgrey model that has the same structure as init_sys.
sys = greyest(data,init_sys,opt) estimates a linear grey-box model using the option set,
opt, to configure the estimation options.
Input Arguments
data
Estimation data.
The dimensions of the inputs and outputs of data and init_sys must match.
For time-domain estimation, data is an iddata object containing the input and output signal values.
init_sys
Identified linear grey-box model that configures the initial parameterization of sys.
init_sys, an idgrey model, must have the same input and output dimensions as data.
opt
Estimation options.
opt is an option set, created using greyestOptions, which specifies options including:
• Estimation objective
• Initialization choice
• Disturbance model handling
• Numerical search method to be used in estimation
                                                                                             1-419
1   Functions
          Output Arguments
          sys
          Estimated grey-box model, returned as an idgrey model. This model is created using the specified
          initial system, and estimation options.
          Information about the estimation results and options used is stored in the Report property of the
          model. Report has the following fields:
           Report      Description
           Field
           Status      Summary of the model status, which indicates whether the model was created by
                       construction or obtained by estimation.
           Method      Estimation command used.
           InitialSt Handling of initial states during estimation, returned as one of the following:
           ate
                     • 'model' — The initial state is parameterized by the ODE file used by the idgrey
                       model.
                       • 'zero' — The initial state is set to zero.
                       • 'estimate' — The initial state is treated as an independent estimation parameter.
                       • 'backcast' — The initial state is estimated using the best least squares fit.
                       • Vector of doubles of length Nx, where Nx is the number of states. For
                         multiexperiment data, a matrix with Ne columns, where Ne is the number of
                         experiments.
                       This field is especially useful to view how the initial states were handled when the
                       InitialState option in the estimation option set is 'auto'.
           Disturban Handling of the disturbance component (K) during estimation, returned as one of the
           ceModel   following values:
                       • 'model' — K values are parameterized by the ODE file used by the idgrey model.
                       • 'fixed' — The value of the K property of the idgrey model is fixed to its original
                         value.
                       • 'none' — K is fixed to zero.
                       • 'estimate' — K is treated as an independent estimation parameter.
                       This field is especially useful to view the how the disturbance component was handled
                       when the DisturbanceModel option in the estimation option set is 'auto'.
1-420
                                                                                              greyest
Report       Description
Field
Fit          Quantitative assessment of the estimation, returned as a structure. See “Loss Function
             and Model Quality Metrics” for more information on these quality metrics. The
             structure has the following fields:
             Field         Description
             FitPerce Normalized root mean squared error (NRMSE) measure of how well the
             nt       response of the model fits the estimation data, expressed as the
                      percentage fit = 100(1-NRMSE).
             LossFcn       Value of the loss function when the estimation completes.
             MSE           Mean squared error (MSE) measure of how well the response of the
                           model fits the estimation data.
             FPE           Final prediction error for the model.
             AIC           Raw Akaike Information Criteria (AIC) measure of model quality.
             AICc          Small sample-size corrected AIC.
             nAIC          Normalized AIC.
             BIC           Bayesian Information Criteria (BIC).
Parameter Estimated values of model parameters.
s
OptionsUs Option set used for estimation. If no custom options were configured, this is a set of
ed        default options. See greyestOptions for more information.
RandState State of the random number stream at the start of estimation. Empty, [], if
          randomization was not used during estimation. For more information, see rng in the
          MATLAB documentation.
                                                                                              1-421
1   Functions
           Report      Description
           Field
           DataUsed    Attributes of the data used for estimation, returned as a structure with the following
                       fields:
                        Field        Description
                        Name         Name of the data set.
                        Type         Data type.
                        Length       Number of data samples.
                        Ts           Sample time.
                        InterSam Input intersample behavior, returned as one of the following values:
                        ple
                                 • 'zoh' — Zero-order hold maintains a piecewise-constant input signal
                                    between samples.
                                     • 'foh' — First-order hold maintains a piecewise-linear input signal
                                       between samples.
                                     • 'bl' — Band-limited behavior specifies that the continuous-time input
                                       signal has zero power above the Nyquist frequency.
                        InputOff Offset removed from time-domain input data during estimation. For
                        set      nonlinear models, it is [].
                        OutputOf Offset removed from time-domain output data during estimation. For
                        fset     nonlinear models, it is [].
           Terminati Termination conditions for the iterative search used for prediction error minimization.
           on        Structure with the following fields:
                        Field        Description
                        WhyStop      Reason for terminating the numerical search.
                        Iteratio Number of search iterations performed by the estimation algorithm.
                        ns
                        FirstOrd ∞-norm of the gradient search vector when the search algorithm
                        erOptima terminates.
                        lity
                        FcnCount Number of times the objective function was called.
                        UpdateNo Norm of the gradient search vector in the last iteration. Omitted when the
                        rm       search method is 'lsqnonlin' or 'fmincon'.
                        LastImpr Criterion improvement in the last iteration, expressed as a percentage.
                        ovement Omitted when the search method is 'lsqnonlin' or 'fmincon'.
                        Algorith Algorithm used by 'lsqnonlin' or 'fmincon' search method. Omitted
                        m        when other search methods are used.
                       For estimation methods that do not require numerical search optimization, the
                       Termination field is omitted.
1-422
                                                                                                  greyest
Examples
data is an iddata object containing the measured data for the outputs, the angular position, the
angular velocity. It also contains the input, the driving voltage.
For the DC motor, choose the angular position (rad) and the angular velocity (rad/s) as the outputs
and the driving voltage (V) as the input. Set up a linear state-space structure of the following form:
            0 1          0
    ẋ(t) =     1 x(t) + G u(t)
            0 −
                τ        τ
              1 0
    y(t) =        x(t) .
              0 1
τ is the time constant of the motor in seconds, and G is the static gain from the input to the angular
velocity in rad/(V*s) .
G = 0.25;
tau = 1;
init_sys = idgrey('motorDynamics',tau,'cd',G,0);
The governing equations in state-space form are represented in the MATLAB® file
motorDynamics.m. To view the contents of this file, enter edit motorDynamics.m at the MATLAB
command prompt.
Estimate τ.
sys = greyest(data,init_sys);
                                                                                                  1-423
1   Functions
To obtain the estimated parameter values associated with sys, use getpvec(sys).
          opt = compareOptions('InitialCondition','zero');
          compare(data,sys,Inf,opt)
sys provides a 98.35% fit for the angular position and an 84.42% fit for the angular velocity.
          Estimate the parameters of a DC motor by incorporating prior information about the parameters
          when using regularization constants.
          The model is parameterized by static gain G and time constant τ. From prior knowledge, it is known
          that G is about 4 and τ is about 1. Also, you have more confidence in the value of τ than G and would
          like to guide the estimation to remain close to the initial guess.
The data contains measurements of motor's angular position and velocity at given input voltages.
1-424
                                                                                          greyest
Create an idgrey model for DC motor dynamics. Use the function DCMotorODE that represents the
structure of the grey-box model.
type DCMotorODE.m
A = [0 1;0 -1/Tau];
B = [0; G/Tau];
C = eye(2);
D = [0;0];
if Ts>0 % Sample the model with sample time Ts
   s = expm([[A B]*Ts; zeros(1,3)]);
   A = s(1:2,1:2);
   B = s(1:2,3);
end
opt = greyestOptions;
opt.Regularization.Lambda = 100;
You specify more weighting on the second parameter because you have more confidence in the value
of τ than G.
opt.Regularization.Nominal = 'model';
                                                                                           1-425
1   Functions
          Extended Capabilities
          Automatic Parallel Support
          Accelerate code by automatically running computation in parallel using Parallel Computing Toolbox™.
          Parallel computing support is available for estimation using the lsqnonlin search method (requires
          Optimization Toolbox). To enable parallel computing, use greyestOptions, set SearchMethod to
          'lsqnonlin', and set SearchOptions.Advanced.UseParallel to true.
For example:
          opt = greyestOptions;
          opt.SearchMethod = 'lsqnonlin';
          opt.SearchOptions.Advanced.UseParallel = true;
          See Also
          greyestOptions | iddata | idfrd | idgrey | idnlgrey | pem | ssest
          Topics
          “Estimate Model Using Zero/Pole/Gain Parameters”
          “Regularized Estimates of Model Parameters”
Introduced in R2012a
1-426
                                                                                          greyestOptions
greyestOptions
Option set for greyest
Syntax
opt = greyestOptions
opt = greyestOptions(Name,Value)
Description
opt = greyestOptions creates the default options set for greyest.
opt = greyestOptions(Name,Value) creates an option set with the options specified by one or
more Name,Value pair arguments.
Input Arguments
Name-Value Pair Arguments
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Handling of initial states during estimation, specified as one of the following values:
• 'model' — The initial state is parameterized by the ODE file used by the idgrey model. The ODE
  file must return 6 or more output arguments.
• 'zero' — The initial state is set to zero. Any values returned by the ODE file are ignored.
• 'estimate' — The initial state is treated as an independent estimation parameter.
• 'backcast' — The initial state is estimated using the best least squares fit.
• 'auto' — The software chooses the method to handle initial states based on the estimation data.
• Vector of doubles — Specify a column vector of length Nx, where Nx is the number of states. For
  multiexperiment data, specify a matrix with Ne columns, where Ne is the number of experiments.
  The specified values are treated as fixed values during the estimation process.
Handling of the disturbance component (K) during estimation, specified as one of the following
values:
• 'model' — K values are parameterized by the ODE file used by the idgrey model. The ODE file
  must return 5 or more output arguments.
• 'fixed' — The value of the K property of the idgrey model is fixed to its original value.
                                                                                                 1-427
1   Functions
          • 'none' — K is fixed to zero. Any values returned by the ODE file are ignored.
          • 'estimate' — K is treated as an independent estimation parameter.
          • 'auto' — The software chooses the method to handle how the disturbance component is handled
            during estimation. The software uses the 'model' method if the ODE file returns 5 or more
            output arguments with a finite value for K. Else, the software uses the 'fixed' method.
          Error to be minimized in the loss function during estimation, specified as the comma-separated pair
          consisting of 'Focus' and one of the following values:
          • 'prediction' — The one-step ahead prediction error between measured and predicted outputs
            is minimized during estimation. As a result, the estimation focuses on producing a good predictor
            model.
          • 'simulation' — The simulation error between measured and simulated outputs is minimized
            during estimation. As a result, the estimation focuses on making a good fit for simulation of model
            response with the current inputs.
          The Focus option can be interpreted as a weighting filter in the loss function. For more information,
          see “Loss Function and Model Quality Metrics”.
          Weighting prefilter applied to the loss function to be minimized during estimation. To understand the
          effect of WeightingFilter on the loss function, see “Loss Function and Model Quality Metrics”.
                Passbands are expressed in rad/TimeUnit for time-domain data and in FrequencyUnit for
                frequency-domain data, where TimeUnit and FrequencyUnit are the time and frequency units
                of the estimation data.
          • SISO filter — Specify a single-input-single-output (SISO) linear filter in one of the following ways:
1-428
                                                                                         greyestOptions
      This option calculates the weighting function as a product of the filter and the input spectrum
      to estimate the transfer function.
• Weighting vector — Applicable for frequency-domain data only. Specify a column vector of
  weights. This vector must have the same length as the frequency vector of the data set,
  Data.Frequency. Each input and output response in the data is multiplied by the corresponding
  weight at that frequency.
Control whether to enforce stability of estimated model, specified as the comma-separated pair
consisting of 'EnforceStability' and either true or false.
Data Types: logical
If EstimateCovariance is true, then use getcov to fetch the covariance matrix from the
estimated model.
Specify whether to display the estimation progress, specified as one of the following values:
• 'on' — Information on model structure and estimation results are displayed in a progress-viewer
  window.
• 'off' — No progress or results information is displayed.
Removal of offset from time-domain input data during estimation, specified as the comma-separated
pair consisting of 'InputOffset' and one of the following:
• A column vector of positive integers of length Nu, where Nu is the number of inputs.
• [] — Indicates no offset.
• Nu-by-Ne matrix — For multi-experiment data, specify InputOffset as an Nu-by-Ne matrix. Nu
  is the number of inputs, and Ne is the number of experiments.
Each entry specified by InputOffset is subtracted from the corresponding input data.
Removal of offset from time-domain output data during estimation, specified as the comma-separated
pair consisting of 'OutputOffset' and one of the following:
                                                                                                 1-429
1   Functions
Each entry specified by OutputOffset is subtracted from the corresponding output data.
Weighting of prediction errors in multi-output estimations, specified as one of the following values:
          • 'noise' — Minimize det(E′ * E/N), where E represents the prediction error and N is the number
            of data samples. This choice is optimal in a statistical sense and leads to maximum likelihood
            estimates if nothing is known about the variance of the noise. It uses the inverse of the estimated
            noise variance as the weighting function.
                • E is the matrix of prediction errors, with one column for each output, and W is the positive
                  semidefinite symmetric matrix of size equal to the number of outputs. Use W to specify the
                  relative importance of outputs in multiple-output models, or the reliability of corresponding
                  data.
                • N is the number of data samples.
          • [] — The software chooses between the 'noise' or using the identity matrix for W.
          Options for regularized estimation of model parameters. For more information on regularization, see
          “Regularized Estimates of Model Parameters”.
Specify a positive scalar to add the regularization term to the estimation cost.
                Default: 0
          • R — Weighting matrix.
                Specify a vector of nonnegative numbers or a square positive semi-definite matrix. The length
                must be equal to the number of free parameters of the model.
                For black-box models, using the default value is recommended. For structured and grey-box
                models, you can also specify a vector of np positive numbers such that each entry denotes the
                confidence in the value of the associated parameter.
                The default value of 1 implies a value of eye(npfree), where npfree is the number of free
                parameters.
1-430
                                                                                          greyestOptions
   Default: 1
• Nominal — The nominal value towards which the free parameters are pulled during estimation.
   The default value of zero implies that the parameter values are pulled towards zero. If you are
   refining a model, you can set the value to 'model' to pull the parameters towards the parameter
   values of the initial model. The initial parameter values must be finite for this setting to work.
Default: 0
Numerical search method used for iterative parameter estimation, specified as the comma-separated
pair consisting of 'SearchMethod' and one of the following:
• 'auto' — A combination of the line search algorithms, 'gn', 'lm', 'gna', and 'grad' methods
  is tried in sequence at each iteration. The first descent direction leading to a reduction in
  estimation cost is used.
• 'gn' — Subspace Gauss-Newton least squares search. Singular values of the Jacobian matrix less
  than GnPinvConstant*eps*max(size(J))*norm(J) are discarded when computing the
  search direction. J is the Jacobian matrix. The Hessian matrix is approximated as JTJ. If there is no
  improvement in this direction, the function tries the gradient direction.
• 'gna' — Adaptive subspace Gauss-Newton search. Eigenvalues less than gamma*max(sv) of the
  Hessian are ignored, where sv contains the singular values of the Hessian. The Gauss-Newton
  direction is computed in the remaining subspace. gamma has the initial value
  InitialGnaTolerance (see Advanced in 'SearchOptions' for more information). This value
  is increased by the factor LMStep each time the search fails to find a lower value of the criterion
  in fewer than five bisections. This value is decreased by the factor 2*LMStep each time a search is
  successful without any bisections.
• 'lm' — Levenberg-Marquardt least squares search, where the next parameter value is -pinv(H
  +d*I)*grad from the previous one. H is the Hessian, I is the identity matrix, and grad is the
  gradient. d is a number that is increased until a lower value of the criterion is found.
• 'grad' — Steepest descent least squares search.
• 'lsqnonlin' — Trust-region-reflective algorithm of lsqnonlin. Requires Optimization Toolbox
  software.
• 'fmincon' — Constrained nonlinear solvers. You can use the sequential quadratic programming
  (SQP) and trust-region-reflective algorithms of the fmincon solver. If you have Optimization
  Toolbox software, you can also use the interior-point and active-set algorithms of the fmincon
  solver. Specify the algorithm in the SearchOptions.Algorithm option. The fmincon algorithms
  may result in improved estimation results in the following scenarios:
   • Constrained minimization problems when there are bounds imposed on the model parameters.
   • Model structures where the loss function is a nonlinear or non smooth function of the
     parameters.
   • Multi-output model estimation. A determinant loss function is minimized by default for multi-
     output model estimation. fmincon algorithms are able to minimize such loss functions directly.
     The other search methods such as 'lm' and 'gn' minimize the determinant loss function by
     alternately estimating the noise variance and reducing the loss value for a given noise variance
     value. Hence, the fmincon algorithms can offer better efficiency and accuracy for multi-output
     model estimations.
                                                                                                 1-431
1   Functions
          Option set for the search algorithm, specified as the comma-separated pair consisting of
          'SearchOptions' and a search option set with fields that depend on the value of SearchMethod.
1-432
                                                                                    greyestOptions
                                                                                            1-433
1   Functions
1-434
                                                                                        greyestOptions
                                                                                               1-435
1   Functions
                                      • 'sqp' — Sequential
                                        quadratic programming
                                        algorithm. The algorithm
                                        satisfies bounds at all
                                        iterations, and it can recover
                                        from NaN or Inf results. It is
                                        not a large-scale algorithm.
                                        For more information, see
                                        “Large-Scale vs. Medium-
                                        Scale Algorithms”
                                        (Optimization Toolbox).
                                      • 'trust-region-
                                        reflective' — Subspace
                                        trust-region method based
                                        on the interior-reflective
                                        Newton method. It is a large-
                                        scale algorithm.
                                      • 'interior-point' —
                                        Large-scale algorithm that
                                        requires Optimization
                                        Toolbox software. The
                                        algorithm satisfies bounds at
                                        all iterations, and it can
                                        recover from NaN or Inf
                                        results.
                                      • 'active-set' — Requires
                                        Optimization Toolbox
                                        software. The algorithm can
                                        take large steps, which adds
                                        speed. It is not a large-scale
                                        algorithm.
1-436
                                                                                         greyestOptions
• ErrorThreshold — Specifies when to adjust the weight of large errors from quadratic to linear.
   Errors larger than ErrorThreshold times the estimated standard deviation have a linear weight
   in the loss function. The standard deviation is estimated robustly as the median of the absolute
   deviations from the median of the prediction errors, divided by 0.7. For more information on
   robust norm choices, see section 15.2 of [2].
   Default: 0
• MaxSize — Specifies the maximum number of elements in a segment when input-output data is
  split into segments.
   Default: 250000
• StabilityThreshold — Specifies thresholds for stability tests.
   • s — Specifies the location of the right-most pole to test the stability of continuous-time models.
     A model is considered stable when its right-most pole is to the left of s.
      Default: 0
   • z — Specifies the maximum distance of all poles from the origin to test stability of discrete-
     time models. A model is considered stable if all poles are within the distance z from the origin.
                                                                                                 1-437
1   Functions
                   Default: 1+sqrt(eps)
          • AutoInitThreshold — Specifies when to automatically estimate the initial state.
                  yp, z − ymeas
                                > AutoInitThreshold
                  yp, e − ymeas
Default: 1.05
          Output Arguments
          opt — Options set for greyest
          greyestOptions option set
Examples
          Create an options set for greyest using the 'backcast' algorithm to initialize the state. Specify
          Display as 'on'.
          opt = greyestOptions('InitialState','backcast','Display','on');
          Compatibility Considerations
          Renaming of Estimation and Analysis Options
          The names of some estimation and analysis options were changed in R2018a. Prior names still work.
          For details, see the R2018a release note “Renaming of Estimation and Analysis Options”.
1-438
                                                                                         greyestOptions
References
[1] Wills, Adrian, B. Ninness, and S. Gibson. “On Gradient-Based Search for Multivariable System
         Estimates”. Proceedings of the 16th IFAC World Congress, Prague, Czech Republic, July 3–8,
         2005. Oxford, UK: Elsevier Ltd., 2005.
[2] Ljung, L. System Identification: Theory for the User. Upper Saddle River, NJ: Prentice-Hall PTR,
        1999.
See Also
greyest | idgrey | idnlgrey | pem | ssest
Topics
“Loss Function and Model Quality Metrics”
Introduced in R2012a
                                                                                                1-439
1   Functions
          hasdelay
          True for linear model with time delays
          Syntax
          B = hasdelay(sys)
          B = hasdelay(sys,'elem')
          Description
          B = hasdelay(sys) returns 1 (true) if the model sys has input delays, output delays, I/O delays, or
          internal delays, and 0 (false) otherwise. If sys is a model array, then B is true if least one model in
          sys has delays.
          B = hasdelay(sys,'elem') returns a logical array of the same size as the model array sys. The
          logical array indicates which models in sys have delays.
          See Also
          absorbDelay | totaldelay
Introduced in R2012a
1-440
                                                                                                 iddata
iddata
Input-output data and its properties for system identification in the time or frequency domain
Description
Use the iddata object to encapsulate input and output measurement data for the system you want to
identify. System identification functions use these measurements to estimate a model. Model
validation functions use the input measurements to provide the input for simulations, and the output
measurements to compare how well the estimated model response fits the original data.
iddata objects can contain a single set of measurements or multiple sets. Each set of data
corresponds to an experiment. The objects have the following characteristics, which are encoded in
the object properties on page 1-443:
• Data can be in the frequency domain or the time domain. You can convert objects from one
  domain to the other.
• In the time domain, the data can be uniformly or nonuniformly sampled. To use the iddata object
  for estimation, however, the data must be uniformly sampled, and the input and output data for
  each experiment must be recorded at the same time instants.
• You can specify data properties, such as the sample time, start time, time points, frequency
  sample points, and intersample behavior.
• You can provide labels and comments to differentiate and annotate data components, experiments,
  and the object as a whole.
Creation
Syntax
data   =   iddata(y,u,Ts)
data   =   iddata(y,[],Ts)
data   =   iddata(y,u,Ts,'Frequency',W)
data   =   iddata( ___ ,Name,Value)
Description
data = iddata(y,u,Ts) creates an iddata object containing a time-domain output signal y and
input signal u. Ts specifies the sample time of the experimental data.
You can use iddata to create a multiexperiment iddata object by specifying y and u as cell arrays.
Alternatively, you can create single-experiment iddata objects and use merge (iddata) to
combine the objects into one multiexperiment iddata object. For more information on
multiexperiment iddata objects, see “Create Multiexperiment Data at the Command Line”.
                                                                                                 1-441
1   Functions
          data = iddata(y,[],Ts) creates an iddata object for time-series data. The object contains a
          time-domain output signal y and an empty input signal []. Ts specifies the sample time of the
          experimental data.
          data = iddata( ___ ,Name,Value) sets additional properties using name-value pair arguments.
          Specify Name,Value after any of the input argument combinations in the previous syntaxes.
Input Arguments
          • An N-by-1 vector for a single output system, where N is the number of observations
          • An N-by-Ny matrix for a multiple-output system, where Ny is the number of output channels
          • An Ne element cell array for a multiexperiment data set, where Ne is the number of experiments
            and each cell contains the output signals for one experiment
          • [] for a system that has no output signal, such as when only the input signal is recorded
          y must be in the same domain as the input data u. If the data is in the time domain, y and u must be
          recorded at the same time instants.
          If you use the iddata object for estimation, y and u must be uniformly sampled. If the nonuniformity
          is small, you may be able to able to convert your data into a uniformly sampled set with enough
          integrity that the converted data supports estimation. For more information on techniques you can
          try, see interp1 and “Missing Data in MATLAB” (MATLAB).
          • An N-by-1 vector for a single input system, where N is the number of observations
          • An N-by-Nu matrix for a multiple-input system, where Nu is the number of input channels
          • An Ne element cell array for a multiexperiment data set, where Ne is the number of experiments
            and each cell contains the input signals for one experiment
          • [] for a system that has no input signal, such as a time series
          u must be in the same domain as output data y. If the data is in the time domain, y and u must be
          recorded at the same time instants.
          If you use the iddata object for estimation, y and u must be uniformly sampled. If the nonuniformity
          is small, you may be able to able to convert your data into a uniformly sampled set with enough
          integrity that the converted data supports estimation. For more information on techniques you can
          try, see interp1 and “Missing Data in MATLAB” (MATLAB).
1-442
                                                                                                  iddata
Ts — Sample time
1 (default) | scalar | 0 | []
Sample time in the units specified by the property TimeUnit, specified as one of the following:
Properties
Domain — Data time or frequency domain
'Time' (default) | 'Frequency'
Name of each data set contained in the iddata object, specified as an Ne-by-1 cell array of character
vectors, where Ne is the number of experiments. Each cell contains the name of the corresponding
experiment. For instance, {'MyMeas1';'MyMeas2';'MyMeas3'} contains experiment names for a
three-experiment iddata object.
    A 1-by-Ne cell array, where Ne is the number of experiments. Because all Frequency vectors
    must have the same units, all values of FrequencyUnit must be the same.
Changing this property does not scale or convert the data. Modifying the property changes only the
interpretation of the existing data.
                                                                                                  1-443
1   Functions
          • For a single experiment, an N-by-Nu matrix, where N is the number of data samples and Nu is the
            number of input channels
          • For multiple experiments, a cell array containing Ne single-experiment matrices, where Ne is the
            number of experiments
          When accessing InputData from the command line, you can use the shorthand form u. For example,
          u1 = data.InputData is equivalent to u1 = data.u.
Input channel names, specified as an Nu-by-1 cell array, where Nu is the number of input channels.
          Input channel units, specified as an Nu-by-1 cell array, where Nu is the number of input channels.
          Each cell contains the units of the corresponding input channel.
          Example: {'rad';'rad/s'}
          Intersample behavior for transformations between discrete time and continuous time, specified as a
          character vector or as a cell array of character vectors. For each experiment, the possible values for
          each input channel are:
          For a single experiment with a single input channel, InterSample contains one of the values in the
          previous list. For multiple experiments, InterSample is an Nu-by-Ne cell array, where Nu is the
          number of input channels and Ne is the number of experiments. Each cell contains the behavior value
          associated with the experiment and input channel that the cell represents.
          Comments about the data set, specified as a character vector or, for multiexperiment data sets, an Ne-
          by-1 cell array of character vectors, where Ne is the number of experiments.
1-444
                                                                                                iddata
Output signal values from the system, specified as one of the following:
• For a single experiment, an N-by-Ny matrix, where N is the number of data samples and Ny is the
  number of output channels
• For multiple experiments, a cell array containing Ne single-experiment matrices, where Ne is the
  number of experiments
When accessing OutputData from the command line, you can use the shorthand form y. For
example, y1 = data.InputData is equivalent to y1 = data.y.
Output channel names, specified as an Ny-by-1 cell array, where Ny is the number of output channels.
Output channel units, specified as an Ny-by-1 cell array, where Nu is the number of output channels.
Each cell contains the units of the corresponding input channel.
Example: {'rad';'rad/s'}
Period of the input signal, specified as a double for each experiment. The value is either Inf for
nonperiodic input signals or the period in the units specified by the property TimeUnit for periodic
input signals.
• For a single experiment with a single input channel, Period contains a single value.
• For a multiple-input system, Period is an Nu-by-1 vector, where Nu is the number of input
  channels and the kth entry contains the period of the kth input.
• For multiple-experiment data, Period is a 1-by-Ne cell array, where Ne is the number of
  experiments and each cell contains a scalar or vector of periods for the corresponding experiment.
Time values for time-domain data in units specified by TimeUnit, specified as:
The values in SamplingInstants can be uniform or nonuniform. If you specify the Ts property, the
software computes uniform time values in SamplingInstants from Ts and Tstart. If you have
nonuniform sample points, specify the time values in SamplingInstants. The software then sets the
Ts property to empty. Estimation functions do not support nonuniform sampling.
                                                                                                1-445
1   Functions
          Units for the time variable and the sample time, specified as a scalar. This property applies to all
          experiments in the data set.
          Changing this property does not resample or convert the data. Modifying the property changes only
          the interpretation of the existing data.
          Ts — Sample time
          1 (default) | positive scalar | 0 | [] | cell array
          Sample time in units specified by TimeUnit, specified as a scalar or a cell array. For each
          experiment, the value is one of the following:
          For a single experiment, Ts is a scalar. For multiexperiment data, Ts is a 1-by-Ne cell array, where Ne
          is the number of experiments and each cell contains the sample time for the corresponding
          experiment.
Additional comments on the data set, specified as any MATLAB data type.
          Object Functions
          In general, any function applicable to system identification data is applicable to an iddata object.
          These functions are of three general types.
          1     Functions that both operate on and return iddata objects enable you to manipulate and process
                iddata objects.
1-446
                                                                                                  iddata
    • Use fft and ifft to transform existing iddata objects to and from the time and frequency
      domains. For example:
       datafd = fft(Data);
       datatd = ifft(Dataf);
    • Use merge (iddata) to merge iddata objects into a single iddata object containing
      multiple experiments. To extract an experiment from a multiexperiment iddata object, use
      getexp. For example:
       data123 = merge(data1,data2,data3);
       data2 = getexp(data123,2);
       For a more detailed example, see “Extract and Model Specific Data Segments”.
    • Use preprocessing functions such as detrend or idfilt to filter data in iddata objects and
      to remove bad data. For example:
       data_d = detrend(data);
       data_f = idfilt(data,filter);
2   Functions that perform analytical processing on iddata objects and create plots or return
    specific parameters or values let you analyze data and determine inputs to use for estimation.
    • Use analysis functions such as delayest and spa to compute variables such as time delay
      and frequency spectrum.
3   Functions that use the data in iddata objects to estimate, simulate, and validate models let you
    create dynamic models and evaluate how closely the model response matches validation data.
    • Use estimation functions such as ssest and tfest to estimate models with specific
      structures.
    • Use validation functions such as compare and sim to simulate estimated models and compare
      the simulated outputs with validation data and with other models.
    The following lists contain a representative subset of the functions you can use with iddata
    objects.
Data Visualization
iddata/plot    Plot input-output data
Data Selection
getexp             Specific experiments from multiple-experiment data set
merge (iddata)     Merge data sets into iddata object
Data Preprocessing
detrend       Subtract offset or trend from time-domain signals contained in iddata objects
retrend       Add offsets or trends to data signals
idfilt        Filter data using user-defined passbands, general filters, or Butterworth filters
diff          Difference signals in iddata objects
misdata       Reconstruct missing input and output data
idresamp      Resample time-domain data by decimation or interpolation
                                                                                                  1-447
1   Functions
          Data Transformation
          fft    Transform iddata object to frequency domain data
          ifft   Transform iddata objects from frequency to time domain
          Data Analysis
          realdata             Determine whether iddata is based on real-valued signals
          delayest             Estimate time delay (dead time) from data
          isreal               Determine whether model parameters or data values are real
          impulseest           Nonparametric impulse response estimation
          pexcit               Level of excitation of input signals
          feedback             Identify possible feedback data
          etfe                 Estimate empirical transfer functions and periodograms
          spafdr               Estimate frequency response and spectrum using spectral analysis with
                               frequency-dependent resolution
          spa                  Estimate frequency response with fixed frequency resolution using spectral
                               analysis
          iddataPlotOptions    Option set for iddata/plot
Examples
Time-Domain Data
          Create an iddata object using single-input/single-output (SISO) time-domain data. The input and
          output each contain 1000 samples with a sample time of 0.08 seconds.
          load dryer2_data output input;
          data = iddata(output,input,0.08)
data =
1-448
                                                                                               iddata
The software assigns the default channel name 'y1' to the first and only output channel. When the
output signal contains several channels, the software assigns the default names
'y1','y2',...,'yn'. Similarly, the software assigns the default channel name 'u1' to the first
and only input channel. For more information about naming channels, see “Naming, Adding, and
Removing Data Channels”.
plot(data)
Time-Series Data
Create an iddata object from time-series data. Time-series data has no input channel.
Load the output channel of a data set, and create an iddata object that has a sample time of 0.08
seconds.
data =
                                                                                              1-449
1   Functions
Frequency-Domain Data
          Create and examine an iddata object from complex-valued frequency-domain input-output data.
          Convert the object into the time domain.
          Input and output data is sometimes expressed in the form of the Fourier transforms of time-domain
          input-output signals. You can encapsulate this data in a frequency-domain iddata object.
          Load the data, which consists of the complex-valued input-output frequency-domain data U and Y,
          frequency vector W, and sample time Ts.
          load demofr1 U Y W Ts
1-450
                                                                                                iddata
data_fr = iddata(Y,U,Ts,'Frequency',W)
data_fr =
get(data_fr)
F = data_fr.Frequency;
Get the frequency units of the data. The property TimeUnit sets the units of the sample time.
frequ = data_fr.FrequencyUnit
frequ =
'rad/TimeUnit'
timeu = data_fr.TimeUnit
                                                                                                1-451
1   Functions
          timeu =
          'seconds'
          Convert data_fr back into the time domain by using the inverse Fourier transform function ifft.
          data_t = ifft(data_fr)
data_t =
get(data_t)
View properties of an iddata object. Modify the properties both during and after object creation.
data =
1-452
                                                                                              iddata
get(data)
You can specify properties when you create an iddata object using name-value pair arguments.
Create an iddata object from the same data inputs, but change the experiment name from its default
setting to Dryer2.
data = iddata(output,input,0.08,'ExperimentName','Dryer2')
data =
To change property values for an existing iddata object, use dot notation. Change the sample time
property Ts to 0.05 seconds.
data.Ts = 0.05
                                                                                             1-453
1   Functions
data =
          Property names are not case sensitive. Also, if the first few letters uniquely identify the property, you
          do not need to type the entire property name.
data =
          Experiment Dryer2 January 2015.Time domain data set with 1000 samples.
          Sample time: 0.05 seconds
          You can use data.y as a shorthand for data.OutputData to access the output values, or use
          data.u as a shorthand for data.InputData to access the input values.
          y_data = data.y;
          u_data = data.u;
          See Also
          idfrd | idinput
          Topics
          “Representing Data in MATLAB Workspace”
          “Create Multiexperiment Data at the Command Line”
          “Representing Time- and Frequency-Domain Data Using iddata Objects”
          “Managing iddata Objects”
1-454
                                                                                     iddataPlotOptions
iddataPlotOptions
Option set for iddata/plot
Syntax
opt = iddataPlotOptions('time')
opt = iddataPlotOptions('frequency')
opt = iddataPlotOptions( ___ ,'identpref')
Description
opt = iddataPlotOptions('time') creates the default option set for plotting time-domain data.
Use dot notation to customize the option set, if needed.
opt = iddataPlotOptions( ___ ,'identpref') initializes the plot options with the System
Identification Toolbox preferences. This syntax can include any of the input argument combinations in
the previous syntaxes. Use this syntax to change a few plot options but otherwise use your toolbox
preferences.
Examples
opt = iddataPlotOptions('time');
Specify plot properties, such as time units and grid. View the plot in minutes
 opt.TimeUnits = 'minutes';
 % Turn grid on
 opt.Grid = 'on';
load iddata1 z1
h = plot(z1, opt);
                                                                                               1-455
1   Functions
z = iddata(randn(100,1),rand(100,2));
opt = iddataPlotOptions('time');
h = plot(z,opt);
1-456
                                                                                        iddataPlotOptions
Change the orientation of the plots such that all inputs are plotted in one column, and all outputs are
in a second column.
opt.Orientation = 'two-column';
h = plot(z,opt);
                                                                                                  1-457
1   Functions
setoptions(h,'Orientation','two-column')
          You can also change the orientation by right-clicking the plot and choosing Orientation in the
          context menu.
opt = iddataPlotOptions('frequency');
          opt.PhaseVisible = 'off';
          opt.FreqUnits = 'Hz';
          load iddata7 z7
          zf = fft(z7);
          h = plot(zf,opt);
1-458
                                                                                     iddataPlotOptions
opt = iddataPlotOptions('time','identpref');
Output Arguments
opt — Option set for iddata/plot
iddataPlotOptions option set
Option set containing the specified options for iddata/plot. The structure has the following fields:
                                                                                               1-459
1   Functions
           Field                   Description
           Title, XLabel, YLabel   Text and style for axes labels and plot title,
                                   specified as a structure array with the following
                                   fields:
1-460
                                                          iddataPlotOptions
Field                Description
                       Default: 'tex'
TickLabel            Tick label style, specified as a structure array with
                     the following fields:
                     Default: 'off'
GridColor            Color of the grid lines, specified as one of the
                     following values: vector of RGB values in the range
                     [0,1] | character vector of color name | 'none'.
                     For example, for yellow color, specify as one of the
                     following: [1 1 0], 'yellow', or 'y'.
                     Default: [0.15,0.15,0.15]
XlimMode, YlimMode   Axes limit modes, specified as one of the following
                     values:
                     Default: 'auto'
Xlim, Ylim           Axes limits, specified as maximum and minimum
                     values.
Default: [0 1]
                                                                      1-461
1   Functions
           Field        Description
           IOGrouping   Grouping of input-output pairs, specified as one of
                        the following values: 'none' | 'inputs' |
                        'outputs'|'all'
Default: 'none'
1-462
                                                                   iddataPlotOptions
Field                         Description
InputLabels, OutputLabels     Input and output label styles on individual plot
                              axes, specified as a structure array with the
                              following fields:
Default: 'on'
                                                                             1-463
1   Functions
           Field                              Description
           Orientation                        Orientation of the input and output data plots,
                                              specified as one of the following values:
                                              Default: 'two-row'.
           For time-domain data plots only:
           Field                               Description
           TimeUnits                           Time units, specified as one of the following
                                               values:
                                               • 'nanoseconds'
                                               • 'microseconds'
                                               • 'milliseconds'
                                               • 'seconds'
                                               • 'minutes'
                                               • 'hours'
                                               • 'days'
                                               • 'weeks'
                                               • 'months'
                                               • 'years'
Default: 'off'
1-464
                                                                            iddataPlotOptions
Field                                   Description
For frequency-domain data plots only:
Field                                   Description
FreqUnits                               Frequency units, specified as one of the following
                                        values:
                                        • 'Hz'
                                        • 'rad/second'
                                        • 'rpm'
                                        • 'kHz'
                                        • 'MHz'
                                        • 'GHz'
                                        • 'rad/nanosecond'
                                        • 'rad/microsecond'
                                        • 'rad/millisecond'
                                        • 'rad/minute'
                                        • 'rad/hour'
                                        • 'rad/day'
                                        • 'rad/week'
                                        • 'rad/month'
                                        • 'rad/year'
                                        • 'cycles/nanosecond'
                                        • 'cycles/microsecond'
                                        • 'cycles/millisecond'
                                        • 'cycles/hour'
                                        • 'cycles/day'
                                        • 'cycles/week'
                                        • 'cycles/month'
                                        • 'cycles/year'
Default: 'rad/s'
Default: 'log'
                                                                                      1-465
1   Functions
           Field                 Description
           Field                 Description
           MagUnits              Magnitude units, specified as one of the
                                 following values: 'dB' | 'abs'
                                 Default: 'dB'
           MagScale              Magnitude scale, specified as one of the
                                 following values: 'linear' | 'log'
                                 Default: 'linear'
           MagVisible            Magnitude plot visibility, specified as one of the
                                 following values: 'on' | 'off'
                                 Default: 'on'
           MagLowerLimMode       Enables a lower magnitude limit, specified as one
                                 of the following values: 'auto' | 'manual'
                                 Default: 'auto'
           MagLowerLim           Lower magnitude limit, , specified as data type
                                 double. It is typically decided by the range of
                                 the amplitudes the plotted data takes.
           PhaseUnits            Phase units, specified as one of the following
                                 values: 'deg' | 'rad'
                                 Default: 'deg'
           PhaseVisible          Phase plot visibility, specified as one of the
                                 following values: 'on' | 'off'
                                 Default: 'on'
           PhaseWrapping         Enable phase wrapping, specified as one of the
                                 following values: 'on' | 'off'
                                 Default: 'off'
           PhaseWrappingBranch   Phase value at which the plot wraps accumulated
                                 phase when PhaseWrapping is set to 'on'.
                                 Default: 'off'
           PhaseMatchingFreq     Frequency for matching phase, specified as data
                                 type double.
           PhaseMatchingValue    The value to which phase responses are matched
                                 closely, specified as a real number representing
                                 the desired phase value PhaseMatchingFreq.
1-466
                          iddataPlotOptions
See Also
iddata/plot | identpref
Introduced in R2014a
                                    1-467
1   Functions
          identpref
          Set System Identification Toolbox preferences
          Syntax
          identpref
          Description
          identpref opens a Graphical User Interface (GUI) which allows you to change the System
          Identification Toolbox preferences. Preferences set in this GUI affect future plots only (existing plots
          are not altered).
          Your preferences are stored to disk (in a system-dependent location) and will be automatically
          reloaded in future MATLAB sessions using the System Identification Toolbox software.
          See Also
          Topics
          “Toolbox Preferences Editor”
Introduced in R2012a
1-468
                                                                                                     idfilt
idfilt
Filter data using user-defined passbands, general filters, or Butterworth filters
Syntax
Zf = idfilt(Z,filter)
Zf = idfilt(Z,filter,causality)
Zf = idfilt(Z,filter,'FilterOrder',NF)
Description
Zf = idfilt(Z,filter) filters data using user-defined passbands, general filters, or Butterworth
filters. Z is the data, defined as an iddata object. Zf contains the filtered data as an iddata object.
The filter can be defined in three ways:
   idm can be any SISO identified linear model or LTI model object. Alternatively the filter can be
   defined as a cell array {A,B,C,D} of SISO state-space matrices or as a cell array {num,den} of
   numerator/denominator filter coefficients.
• As a vector or matrix that defines one or several passbands.
   filter=[[wp1l,wp1h];[ wp2l,wp2h]; ....;[wpnl,wpnh]]
   The matrix is n-by-2, where each row defines a passband. A filter is constructed that gives the
   union of these passbands. For time-domain data, it is computed as cascaded Butterworth filters or
   order NF. The default value of NF is 5.
   • For time-domain data — The passbands are in units of rad/TimeUnit, where TimeUnit is the
     time units of the estimation data.
   • For frequency-domain data — The passbands are in the frequency units (FrequencyUnit
     property) of the estimation data.
   Here Wf is a vector of possibly complex values that define the filter's frequency response, so that
   the inputs and outputs at frequency Z.Frequency(kf) are multiplied by Wf(kf). Wf is a column
   vector of length = number of frequencies in Z. If the data object has several experiments, Wf is a
   cell array of length = # of experiments in Z.
                                                                                                  1-469
1   Functions
          For frequency-domain data, the signals are multiplied by the frequency response of the filter. With the
          filters defined as passband, this gives ideal, zero-phase filtering (“brickwall filters”). Frequencies that
          have been assigned zero weight by the filter (outside the passband, or via the frequency response)
          are removed from the iddata object Zf.
          It is common practice in identification to select a frequency band where the fit between model and
          data is concentrated. Often this corresponds to bandpass filtering with a passband over the
          interesting breakpoints in a Bode diagram. For identification where a disturbance model is also
          estimated, it is better to achieve the desired estimation result by using the 'WeightingFilter'
          option of the estimation command than just to prefilter the data. The values for 'WeightingFilter'
          are the same as the argument filter in idfilt.
          Algorithms
          The Butterworth filter is the same as butter in the Signal Processing Toolbox product. Also, the
          zero-phase filter is equivalent to filtfilt in that toolbox.
          References
          Ljung (1999), Chapter 14.
          See Also
          iddata | resample
1-470
                                                                                                     idfrd
idfrd
Frequency-response data or model
Syntax
h = idfrd(Response,Freq,Ts)
h =
idfrd(Response,Freq,Ts,'CovarianceData',Covariance,'SpectrumData',Spec,'Noise
Covariance',Speccov)
h = idfrd(Response,Freq,Ts,...
     'P1',V1,'PN',VN)
h = idfrd(mod)
h = idfrd(mod,Freqs)
Description
h = idfrd(Response,Freq,Ts) constructs an idfrd object that stores the frequency response,
Response, of a linear system at frequency values, Freq. Ts is the sample time. For a continuous-time
system, set Ts=0.
h =
idfrd(Response,Freq,Ts,'CovarianceData',Covariance,'SpectrumData',Spec,'Noise
Covariance',Speccov) also stores the uncertainty of the response, Covariance, the spectrum of
the additive disturbance (noise), Spec, and the covariance of the noise, Speccov.
h = idfrd(Response,Freq,Ts,...
      'P1',V1,'PN',VN) constructs an idfrd object that stores a frequency-response model with
properties specified by the idfrd model property-value pairs.
h = idfrd(mod) converts a System Identification Toolbox or Control System Toolbox linear model
to frequency-response data at default frequencies, including the output noise spectra and their
covariance.
For a model
idfrd object stores the transfer function estimate G eiω , as well as the spectrum of the additive
noise (Φv) at the output.
                           2
    Φv(ω) = λT H(eiωT )
                                                                                                1-471
1   Functions
          Response is a 3-D array of dimension ny-by-nu-by-Nf, with ny being the number of outputs, nu the
          number of inputs, and Nf the number of frequencies (that is, the length of Freqs).
          Response(ky,ku,kf) is thus the complex-valued frequency response from input ku to output ky at
          frequency ω=Freqs(kf). When defining the response of a SISO system, Response can be given as a
          vector.
          Intersample behavior: For discrete-time frequency response data (Ts>0), you can also specify the
          intersample behavior of the input signal that was in effect when the samples were collected originally
          from an experiment. To specify the intersample behavior, use:
mf = idfrd(Response,Freq,Ts,'InterSample','zoh');
          For multi-input systems, specify the intersample behavior using an Nu-by-1 cell array, where Nu is the
          number of inputs. The InterSample property is irrelevant for continuous-time data.
          Covariance is a 5-D array containing the covariance of the frequency response. It has dimension ny-
          by-nu-by-Nf-by-2-by-2. The structure is such that Covariance(ky,ku,kf,:,:) is the 2-by-2
          covariance matrix of the response Response(ky,ku,kf). The 1-1 element is the variance of the real
          part, the 2-2 element is the variance of the imaginary part, and the 1-2 and 2-1 elements are the
          covariance between the real and imaginary parts. squeeze(Covariance(ky,ku,kf,:,:)) thus
          gives the covariance matrix of the corresponding response.
          spec is a 3-D array of dimension ny-by-ny-by-Nf, such that spec(ky1,ky2,kf) is the cross
          spectrum between the noise at output ky1 and the noise at output ky2, at frequency Freqs(kf).
          When ky1 = ky2 the (power) spectrum of the noise at output ky1 is thus obtained. For a single-
          output model, spec can be given as a vector.
Converting to idfrd
An idfrd object can also be computed from a given linear identified model, mod.
          If the frequencies Freqs are not specified, a default choice is made based on the dynamics of the
          model mod.
Estimated covariance:
          • If you obtain mod by identification, the software computes the estimated covariance for the idfrd
            object from the uncertainty information in mod. The software uses the Gauss approximation
            formula for this calculation for all model types, except grey-box models. For grey-box models
            (idgrey), the software applies numerical differentiation. The step sizes for the numerical
            derivatives are determined by nuderst.
1-472
                                                                                                   idfrd
• If you create mod by using commands such as idss, idtf, idproc, idgrey, or idpoly, then the
  software sets CovarianceData to [].
Delay treatment: If mod contains delays, then the software assigns the delays of the idfrd object, h,
as follows:
• h.InputDelay = mod.InputDelay
• h.IODelay = mod.IODelay+repmat(mod.OutputDelay,[1,nu])
The idfrd models can be graphed with bode, spectrum, and nyquist, which accept mixtures of
parametric models, such as idtf and idfrd models as arguments. Note that spa, spafdr, and etfe
return their estimation results as idfrd objects.
Constructor
The idfrd object represents complex frequency-response data. Before you can create an idfrd
object, you must import your data as described in “Frequency-Response Data Representation”.
Note The idfrd object can only encapsulate one frequency-response data set. It does not support
the iddata equivalent of multiexperiment data.
fr_data = idfrd(response,f,Ts)
Suppose that ny is the number of output channels, nu is the number of input channels, and nf is a
vector of frequency values. response is an ny-by-nu-by-nf 3-D array. f is the frequency vector that
contains the frequencies of the response.Ts is the sample time, which is used when measuring or
computing the frequency response. If you are working with a continuous-time system, set Ts to 0.
response(ky,ku,kf), where ky, ku, and kf reference the kth output, input, and frequency value,
respectively, is interpreted as the complex-valued frequency response from input ku to output ky at
frequency f(kf).
You can specify object properties when you create the idfrd object using the constructor syntax:
fr_data = idfrd(response,f,Ts,
               'Property1',Value1,...,'PropertyN',ValueN)
Properties
idfrd object properties include:
ResponseData
                                                                                                1-473
1   Functions
          The 'ResponseData' property stores the frequency response data as a 3-D array of complex
          numbers. For SISO systems, 'ResponseData' is a vector of frequency response values at the
          frequency points specified in the 'Frequency' property. For MIMO systems with Nu inputs and Ny
          outputs, 'ResponseData' is an array of size [Ny Nu Nw], where Nw is the number of frequency
          points.
Frequency
          Frequency points of the frequency response data. Specify Frequency values in the units specified by
          the FrequencyUnit property.
FrequencyUnit
Units of the frequency vector in the Frequency property, specified as one of the following values:
          • 'rad/TimeUnit'
          • 'cycles/TimeUnit'
          • 'rad/s'
          • 'Hz'
          • 'kHz'
          • 'MHz'
          • 'GHz'
          • 'rpm'
          The units 'rad/TimeUnit' and 'cycles/TimeUnit' are relative to the time units specified in the
          TimeUnit property.
          Changing this property changes the overall system behavior. Use chgFreqUnit to convert between
          frequency units without modifying system behavior.
Default: 'rad/TimeUnit'
SpectrumData
          Power spectra and cross spectra of the system output disturbances (noise). Specify SpectrumData
          as a 3-D array of complex numbers.
          Specify SpectrumData as a 3-D array with dimension ny-by-ny-by-Nf. Here, ny is the number of
          outputs and Nf is the number of frequency points. SpectrumData(ky1,ky2,kf) is the cross
          spectrum between the noise at output ky1 and the noise at output ky2, at frequency Freqs(kf).
          When ky1 = ky2 the (power) spectrum of the noise at output ky1 is thus obtained.
CovarianceData
          Specify CovarianceData as a 5-D array with dimension ny-by-nu-by-Nf-by-2-by-2. Here, ny, nu, and
          Nf are the number of outputs, inputs and frequency points, respectively.
          CovarianceData(ky,ku,kf,:,:) is the 2-by-2 covariance matrix of the response data
1-474
                                                                                                   idfrd
ResponseData(ky,ku,kf). The 1-1 element is the variance of the real part, the 2-2 element is the
variance of the imaginary part, and the 1-2 and 2-1 elements are the covariance between the real and
imaginary parts.
squeeze(Covariance(ky,ku,kf,:,:))
NoiseCovariance
Specify NoiseCovariance as a 3-D array with dimension ny-by-ny-by-Nf. Here, ny is the number of
outputs and Nf is the number of frequency points. NoiseCovariance(ky1,ky1,kf) is the variance
of the corresponding power spectrum. To eliminate the influence of the noise component from the
model, specify NoiseVariance as 0. Zero variance makes the predicted output the same as the
simulated output.
Report
Summary report that contains information about the estimation options and results when the
frequency-response model is obtained using estimation commands, such as spa, spafdr, and etfe.
Use Report to query a model for how it was estimated, including its:
• Estimation method
• Estimation options
• Search termination conditions
• Estimation data fit and other quality metrics
The contents of Report are irrelevant if the model was created by construction.
f = logspace(-1,1,100);
[mag,phase] = bode(idtf([1 .2],[1 2 1 1]),f);
response = mag.*exp(1j*phase*pi/180);
m = idfrd(response,f,0.08);
m.Report.Method
ans =
''
If you obtain the frequency-response model using estimation commands, the fields of Report contain
information on the estimation data, options, and results.
load iddata3;
m = spa(z3);
m.Report.Method
ans =
SPA
For more information on this property and how to use it, see the Output Arguments section of the
corresponding estimation command reference page and “Estimation Report”.
                                                                                              1-475
1   Functions
InterSample
          Specifies the behavior of the input signals between samples for transformations between discrete-
          time and continuous-time. This property is meaningful for discrete-time idfrd models only.
          • 'zoh' — The input signal used for construction/estimation of the frequency response data was
            subject to a zero-order-hold filter.
          • 'foh' — The input signal was subject to a first-order-hold filter.
          • 'bl' — The input signal has no power above the Nyquist frequency (pi/sys.Ts rad/s). This is
            typically the case when the input signal is measured experimentally using an anti-aliasing filter
            and a sampler. Ideally, treat the data as continuous-time. That is, if the signals used for the
            estimation of the frequency response were subject to anti-aliasing filters, set sys.Ts to zero.
          For multi-input data, specify InterSample as an Nu-by-1 cell array, where Nu is the number of
          inputs.
IODelay
          Transport delays. IODelay is a numeric array specifying a separate transport delay for each input/
          output pair.
          For continuous-time systems, specify transport delays in the time unit stored in the TimeUnit
          property. For discrete-time systems, specify transport delays in integer multiples of the sample time,
          Ts.
          For a MIMO system with Ny outputs and Nu inputs, set IODelay to a Ny-by-Nu array. Each entry of
          this array is a numerical value that represents the transport delay for the corresponding input/output
          pair. You can also set IODelay to a scalar value to apply the same delay to all input/output pairs.
InputDelay
          Input delay for each input channel, specified as a scalar value or numeric vector. For continuous-time
          systems, specify input delays in the time unit stored in the TimeUnit property. For discrete-time
          systems, specify input delays in integer multiples of the sample time Ts. For example, InputDelay =
          3 means a delay of three sample times.
          For a system with Nu inputs, set InputDelay to an Nu-by-1 vector. Each entry of this vector is a
          numerical value that represents the input delay for the corresponding input channel.
You can also set InputDelay to a scalar value to apply the same delay to all channels.
Default: 0
OutputDelay
Output delays.
1-476
                                                                                                   idfrd
Ts
Sample time. For continuous-time models, Ts = 0. For discrete-time models, Ts is a positive scalar
representing the sample time expressed in the unit specified by the TimeUnit property of the model.
To denote a discrete-time model with unspecified sample time, set Ts = -1.
Default: 1
TimeUnit
Units for the time variable, the sample time Ts, and any time delays in the model, specified as one of
the following values:
• 'nanoseconds'
• 'microseconds'
• 'milliseconds'
• 'seconds'
• 'minutes'
• 'hours'
• 'days'
• 'weeks'
• 'months'
• 'years'
Changing this property has no effect on other properties, and therefore changes the overall system
behavior. Use chgTimeUnit to convert between time units without modifying system behavior.
Default: 'seconds'
InputName
Alternatively, use automatic vector expansion to assign input names for multi-input models. For
example, if sys is a two-input model, enter:
sys.InputName = 'controls';
When you estimate a model using an iddata object, data, the software automatically sets
InputName to data.InputName.
You can use the shorthand notation u to refer to the InputName property. For example, sys.u is
equivalent to sys.InputName.
                                                                                                  1-477
1   Functions
InputUnit
Use InputUnit to keep track of input signal units. InputUnit has no effect on system behavior.
InputGroup
          Input channel groups. The InputGroup property lets you assign the input channels of MIMO systems
          into groups and refer to each group by name. Specify input groups as a structure. In this structure,
          field names are the group names, and field values are the input channels belonging to each group.
          For example:
          sys.InputGroup.controls = [1 2];
          sys.InputGroup.noise = [3 5];
          creates input groups named controls and noise that include input channels 1, 2 and 3, 5,
          respectively. You can then extract the subsystem from the controls inputs to all outputs using:
sys(:,'controls')
OutputName
          Alternatively, use automatic vector expansion to assign output names for multi-output models. For
          example, if sys is a two-output model, enter:
sys.OutputName = 'measurements';
          When you estimate a model using an iddata object, data, the software automatically sets
          OutputName to data.OutputName.
          You can use the shorthand notation y to refer to the OutputName property. For example, sys.y is
          equivalent to sys.OutputName.
1-478
                                                                                                       idfrd
OutputUnit
Use OutputUnit to keep track of output signal units. OutputUnit has no effect on system behavior.
OutputGroup
Output channel groups. The OutputGroup property lets you assign the output channels of MIMO
systems into groups and refer to each group by name. Specify output groups as a structure. In this
structure, field names are the group names, and field values are the output channels belonging to
each group. For example:
sys.OutputGroup.temperature = [1];
sys.InputGroup.measurement = [3 5];
creates output groups named temperature and measurement that include output channels 1, and
3, 5, respectively. You can then extract the subsystem from all inputs to the measurement outputs
using:
sys('measurement',:)
Name
Default: ''
Notes
Any text that you want to associate with the system, stored as a string or a cell array of character
vectors. The property stores whichever data type you provide. For instance, if sys1 and sys2 are
dynamic system models, you can set their Notes properties as follows:
ans =
                                                                                                  1-479
1   Functions
ans =
UserData
Any type of data you want to associate with system, specified as any MATLAB data type.
Default: []
SamplingGrid
          For arrays of identified linear (IDLTI) models that are derived by sampling one or more independent
          variables, this property tracks the variable values associated with each model. This information
          appears when you display or plot the model array. Use this information to trace results back to the
          independent variables.
          Set the field names of the data structure to the names of the sampling variables. Set the field values
          to the sampled variable values associated with each model in the array. All sampling variables should
          be numeric and scalar valued, and all arrays of sampled values should match the dimensions of the
          model array.
          For example, if you collect data at various operating points of a system, you can identify a model for
          each operating point separately and then stack the results together into a single system array. You
          can tag the individual models in the array with information regarding the operating point:
          where sys is an array containing three identified models obtained at rpms 1000, 5000 and 10000,
          respectively.
          For model arrays generated by linearizing a Simulink® model at multiple parameter values or
          operating points, the software populates SamplingGrid automatically with the variable values that
          correspond to each entry in the array. For example, the Simulink Control Design™ commands
          linearize and slLinearizer populate SamplingGrid in this way.
Default: []
          Subreferencing
          The different channels of the idfrd are retrieved by subreferencing.
h(outputs,inputs)
          h(2,3) thus contains the response data from input channel 3 to output channel 2, and, if applicable,
          the output spectrum data for output channel 2. The channels can also be referred to by their names,
          as in h('power',{'voltage','speed'}).
1-480
                                                                                                   idfrd
Horizontal Concatenation
Adding input channels,
h = [h1,h2,...,hN]
creates an idfrd model h, with ResponseData containing all the input channels in h1,...,hN. The
output channels of hk must be the same, as well as the frequency vectors. SpectrumData is ignored.
Vertical Concatenation
Adding output channels,
h = [h1;h2;... ;hN]
creates an idfrd model h with ResponseData containing all the output channels in h1,
h2,...,hN. The input channels of hk must all be the same, as well as the frequency vectors.
SpectrumData is also appended for the new outputs. The cross spectrum between output channels
of h1, h2,...,hN is then set to zero.
Converting to iddata
You can convert an idfrd object to a frequency-domain iddata object by
Data = iddata(Idfrdmodel)
Seeiddata.
Examples
The following example shows how to create an idfrd object that contains 100 frequency-response
values with a sample time of 0.08s and get its properties.
f = logspace(-1,1,100);
[mag, phase] = bode(idtf([1 .2],[1 2 1 1]),f);
response = mag.*exp(1j*phase*pi/180);
fr_data = idfrd(response,f,0.08);
response and f are variables in the MATLAB Workspace browser, representing the frequency-
response data and frequency values, respectively.
You can use get(fr_data) to view all properties of the idfrd object. You can specify properties
when you create an idfrd object using the constructor syntax. For example, fr_data =
idfrd(y,u,Ts,'Property1',Value1,...,'PropertyN',ValueN) .
Use dot notation to change property values for an existing idfrd object. For example, change the
name of the idfrd object.
                                                                                             1-481
1   Functions
fr_data.Name = 'DC_Converter';
          If you import fr_data into the System Identification app, this data is named DC_Converter in the
          app, and not the variable name fr_data .
          See Also
          bode | etfe | freqresp | nyquist | spa | spafdr | tfest
1-482
                                                                                                  idgrey
idgrey
Linear ODE (grey-box model) with identifiable parameters
Syntax
sys   =   idgrey(odefun,parameters,fcn_type)
sys   =   idgrey(odefun,parameters,fcn_type,optional_args)
sys   =   idgrey(odefun,parameters,fcn_type,optional_args,Ts)
sys   =   idgrey(odefun,parameters,fcn_type,optional_args,Ts,Name,Value)
Description
sys = idgrey(odefun,parameters,fcn_type) creates a linear grey-box model with identifiable
parameters, sys. odefun specifies the user-defined function that relates the model parameters,
parameters, to its state-space representation.
Object Description
An idgrey model represents a system as a continuous-time or discrete-time state-space model with
identifiable (estimable) coefficients.
A state-space model of a system with input vector, u, output vector, y, and disturbance, e, takes the
following form in continuous time:
For idgrey models, the state-space matrices A, B, C, and D are expressed as a function of user-
defined parameters using a MATLAB function. You access estimated parameters using
sys.Structures.Parameters, where sys is an idgrey model.
Use an idgrey model when you know the system of equations governing the system dynamics
explicitly. You should be able to express these dynamics in the form of ordinary differential or
difference equations. You specify complex relationships and constraints among the parameters that
cannot be done through structured state-space models (idss).
                                                                                                 1-483
1   Functions
          You can create an idgrey model using the idgrey command. To do so, write a MATLAB function
          that returns the A, B, C, and D matrices for given values of the estimable parameters and sample
          time. The MATLAB function can also return the K matrix and accept optional input arguments. The
          matrices returned may represent a continuous-time or discrete-time model, as indicated by the
          sample time.
          Use the estimating functions pem or greyest to obtain estimated values for the unknown parameters
          of an idgrey model.
          You can convert an idgrey model into other dynamic systems, such as idpoly, idss, tf, ss etc. You
          cannot convert a dynamic system into an idgrey model.
Examples
          Create an idgrey model to represent a DC motor. Specify the motor time-constant as an estimable
          parameter and that the ODE function can return continuous- or discrete-time state-space matrices.
          odefun = 'motorDynamics';
          parameters = 1;
          fcn_type = 'cd';
          optional_args = 0.25;
          Ts = 0;
          sys = idgrey(odefun,parameters,fcn_type,optional_args,Ts);
          sys is an idgrey model that is configured to use the shipped file motorDynamics.m to return the A,
          B, C, D, and K matrices. motorDynamics.m also returns the initial conditions, X0. The motor
          constant, τ, is defined in motorDynamics.m as an estimable parameter, and parameters = 1
          specifies its initial value as 1.
          Specify the known parameters of a grey-box model as fixed for estimation. Also specify a minimum
          bound for an estimable parameter.
          Create an ODE file that relates the pendulum model coefficients to its state-space representation.
          Save this function as LinearPendulum.m such that it is in the MATLAB® search path.
1-484
                                                                                                idgrey
In this function:
m = 1;
g = 9.81;
l = 1;
b = 0.2;
parameters = {'mass',m;'gravity',g;'length',l;'friction',b};
fcn_type = 'c';
sys = idgrey(odefun,parameters,fcn_type);
Similarly, to specify an upper bound for an estimable parameter, use the Maximum field of the
parameter.
Create a grey-box model with identifiable parameters. Name the input and output channels of the
model, and specify seconds for the model time units.
Use Name,Value pair arguments to specify additional model properties on model creation.
odefun = 'motorDynamics';
parameters = 1;
fcn_type = 'cd';
optional_args = 0.25;
Ts = 0;
sys = idgrey(odefun,parameters,fcn_type,optional_args,Ts,'InputName','Voltage',...
            'OutputName',{'Angular Position','Angular Velocity'});
To change or specify more attributes of an existing model, you can use dot notation. For example:
                                                                                                1-485
1   Functions
sys.TimeUnit = 'seconds';
          odefun2 = 'motorDynamics';
          parameters2 = {[1 2]};
          optional_args2 = 0.5;
          sys2 = idgrey(odefun2,parameters2,fcn_type,optional_args2);
sysarr = stack(1,sys1,sys2);
          Input Arguments
          odefun
MATLAB function that relates the model parameters to its state-space representation.
          odefun specifies the name of a MATLAB function (.m, .p, a function handle or .mex* file). This
          function establishes the relationship between the model parameters, parameters, and its state-
          space representation. The function may optionally relate the model parameters to the disturbance
          matrix and initial states.
If the function is not on the MATLAB path, then specify the full file name, including the path.
The function outputs describe the model in the following linear state-space innovations form:
par1,par2,...,parN are model parameters. Each entry may be a scalar, vector or matrix.
          optional_arg1,optional_arg2,... are the optional inputs that odefun may require. The values
          of the optional input arguments are unchanged through the estimation process. However, the values
          of par1,par2,...,parN are updated during estimation to fit the data. Use optional input
          arguments to vary the constants and coefficients used by your model without editing odefun.
1-486
                                                                                                  idgrey
The disturbance matrix, K, and the initial state values, x0, are not parametrized. Instead, these values
are determined separately, using the DisturbanceModel and InitialState estimation options,
respectively. For more information regarding the estimation options, see greyestOptions.
A good choice for achieving the best simulation results is to set the DisturbanceModel option to
'none', which fixes K to zero.
(Optional) Parameterizing Disturbance: odefun can also return the disturbance component, K, using
the syntax:
[A,B,C,D,K] = odefun(par1,par2,...,parN,Ts,optional_arg1,optional_arg2,...)
If odefun returns a value for K that contains NaN values, then the estimating function assumes that K
is not parameterized. In this case, the value of the DisturbanceModel estimation option determines
how K is handled.
(Optional) Parameterizing Initial State Values: To make the model initial states, X0, dependent on the
model parameters, use the following syntax for odefun:
[A,B,C,D,K,X0] = odefun(par1,par2,...,parN,Ts,optional_arg1,optional_arg2,...)
If odefun returns a value for X0 that contains NaN values, then the estimating function assumes that
X0 is not parameterized. In this case, X0 may be fixed to zero or estimated separately, using the
InitialStates estimation option.
parameters
Specify parameters as a cell array containing the parameter initial values. If your model requires
only one parameter, which may itself be a vector or a matrix, you may specify parameters as a
matrix.
You may also specify parameter names using an N-by-2 cell array, where N is the number of
parameters. The first column specifies the names, and the second column specifies the values of the
parameters.
For example:
parameters = {'mass',par1;'stiffness',par2;'damping',par3}
fcn_type
   Otherwise, if Ts>0, odefun returns matrices corresponding to a discrete-time system. Select this
   option to sample your model using the values returned by odefun, rather than using the
   software’s internal sample time conversion routines.
                                                                                                 1-487
1   Functions
optional_args
If odefun does not require optional input arguments, specify optional_args as {}.
Ts
Name,Value
          Specify optional comma-separated pairs of Name,Value arguments, where Name is the argument
          name and Value is the corresponding value. Name must appear inside single quotes (' '). You can
          specify several name and value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
          Use Name,Value arguments to specify additional properties of idgrey models during model
          creation. For example, idgrey(odefun,parameters,fcn_type,'InputName','Voltage')
          creates an idgrey model with the InputName property set to Voltage.
          Properties
          idgrey object properties include:
A,B,C,D
          • A — State matrix A, an Nx-by-Nx matrix, as returned by the ODE function associated with the
            idgrey model. Nx is the number of states.
          • B — Input-to-state matrix B, an Nx-by-Nu matrix, as returned by the ODE function associated with
            the idgrey model. Nu is the number of inputs and Nx is the number of states.
          • C — State-to-output matrix C, an Ny-by-Nx matrix, as returned by the ODE function associated
            with the idgrey model. Nx is the number of states and Ny is the number of outputs.
          • D — Feedthrough matrix D, an Ny-by-Nu matrix, as returned by the ODE function associated with
            the idgrey model. Ny is the number of outputs and Nu is the number of inputs.
          The values A,B,C,D are returned by the ODE function associated with the idgrey model. Thus, you
          can only read these matrices; you cannot set their values.
1-488
                                                                                                  idgrey
K is Nx-by-Ny matrix, where Nx is the number of states and Ny is the number of outputs.
• If odefun parameterizes the K matrix, then K has the value returned by odefun. odefun
  parameterizes the K matrix if it returns at least five outputs and the value of the fifth output does
  not contain NaN values.
• If odefun does not parameterize the K matrix, then K is a zero matrix of size Nx-by-Ny. Nx is the
  number of states and Ny is the number of outputs. The value is treated as a fixed value of the K
  matrix during estimation. To make the value estimable, use the DisturbanceModel estimation
  option.
• Regardless of whether the K matrix is parameterized by odefun or not, you can set the value of
  the K property explicitly as an Nx-by-Ny matrix. Nx is the number of states and Ny is the number
  of outputs. The specified value is treated as a fixed value of the K matrix during estimation. To
  make the value estimable, use the DisturbanceModel estimation option.
StateName
StateUnit
Use StateUnit to keep track of the units each state is expressed in. StateUnit has no effect on
system behavior.
Structure
Structure stores information regarding the MATLAB function that parameterizes the idgrey
model.
• Structure.Function — Name or function handle of the MATLAB function used to create the
  idgrey model.
• Structure.FunctionType — Indicates whether the model is parameterized in continuous-time,
  discrete-time, or both.
• Structure.Parameters — Information about the estimated parameters.
  Structure.Parameters contains the following fields:
                                                                                                  1-489
1   Functions
                   Specify parameter units and labels as character vectors. For example, 'Time'.
          • Structure.ExtraArguments — Optional input arguments required by the ODE function.
          • Structure.StateName — Names of the model states.
          • Structure.StateUnit — Units of the model states.
NoiseVariance
          An identified model includes a white, Gaussian noise component, e(t). NoiseVariance is the
          variance of this noise component. Typically, the model estimation function (such as greyest or pem)
          determines this variance.
          For SISO models, NoiseVariance is a scalar. For MIMO models, NoiseVariance is a Ny-by-Ny
          matrix, where Ny is the number of outputs in the system.
Report
          Summary report that contains information about the estimation options and results when the grey-
          box model is obtained using the greyest estimation command. Use Report to query a model for
          how it was estimated, including its:
          • Estimation method
          • Estimation options
          • Search termination conditions
          • Estimation data fit and other quality metrics
The contents of Report are irrelevant if the model was created by construction.
          odefun = 'motorDynamics';
          m = idgrey(odefun,1,'cd',0.25,0);
          m.Report.OptionsUsed
ans =
[]
1-490
                                                                                                   idgrey
If you obtain the grey-box model using estimation commands, the fields of Report contain
information on the estimation data, options, and results.
load(fullfile(matlabroot,'toolbox','ident','iddemos','data','dcmotordata'));
data = iddata(y,u,0.1,'Name','DC-motor');
odefun = 'motorDynamics';
init_sys = idgrey('motorDynamics',1,'cd',0.25,0);
m = greyest(data,init_sys);
m.Report.OptionsUsed
InitialState: 'auto'
    DisturbanceModel:    'auto'
               Focus:    'prediction'
  EstimateCovariance:    1
             Display:    'off'
         InputOffset:    []
        OutputOffset:    []
      Regularization:    [1x1 struct]
        OutputWeight:    []
        SearchMethod:    'auto'
       SearchOptions:    [1x1 idoptions.search.identsolver]
            Advanced:    [1x1 struct]
For more information on this property and how to use it, see the Output Arguments section of the
corresponding estimation command reference page and “Estimation Report”.
InputDelay
Input delay for each input channel, specified as a scalar value or numeric vector. For continuous-time
systems, specify input delays in the time unit stored in the TimeUnit property. For discrete-time
systems, specify input delays in integer multiples of the sample time Ts. For example, InputDelay =
3 means a delay of three sample times.
For a system with Nu inputs, set InputDelay to an Nu-by-1 vector. Each entry of this vector is a
numerical value that represents the input delay for the corresponding input channel.
You can also set InputDelay to a scalar value to apply the same delay to all channels.
Default: 0
OutputDelay
Output delays.
Ts
Sample time.
                                                                                               1-491
1   Functions
For idgrey models, there is no unique default value for Ts. Ts depends on the value of fcn_type.
TimeUnit
          Units for the time variable, the sample time Ts, and any time delays in the model, specified as one of
          the following values:
          • 'nanoseconds'
          • 'microseconds'
          • 'milliseconds'
          • 'seconds'
          • 'minutes'
          • 'hours'
          • 'days'
          • 'weeks'
          • 'months'
          • 'years'
          Changing this property has no effect on other properties, and therefore changes the overall system
          behavior. Use chgTimeUnit to convert between time units without modifying system behavior.
Default: 'seconds'
InputName
          Alternatively, use automatic vector expansion to assign input names for multi-input models. For
          example, if sys is a two-input model, enter:
sys.InputName = 'controls';
          When you estimate a model using an iddata object, data, the software automatically sets
          InputName to data.InputName.
          You can use the shorthand notation u to refer to the InputName property. For example, sys.u is
          equivalent to sys.InputName.
1-492
                                                                                                  idgrey
InputUnit
Use InputUnit to keep track of input signal units. InputUnit has no effect on system behavior.
InputGroup
Input channel groups. The InputGroup property lets you assign the input channels of MIMO systems
into groups and refer to each group by name. Specify input groups as a structure. In this structure,
field names are the group names, and field values are the input channels belonging to each group.
For example:
sys.InputGroup.controls = [1 2];
sys.InputGroup.noise = [3 5];
creates input groups named controls and noise that include input channels 1, 2 and 3, 5,
respectively. You can then extract the subsystem from the controls inputs to all outputs using:
sys(:,'controls')
OutputName
Alternatively, use automatic vector expansion to assign output names for multi-output models. For
example, if sys is a two-output model, enter:
sys.OutputName = 'measurements';
When you estimate a model using an iddata object, data, the software automatically sets
OutputName to data.OutputName.
You can use the shorthand notation y to refer to the OutputName property. For example, sys.y is
equivalent to sys.OutputName.
                                                                                              1-493
1   Functions
OutputUnit
Use OutputUnit to keep track of output signal units. OutputUnit has no effect on system behavior.
OutputGroup
          Output channel groups. The OutputGroup property lets you assign the output channels of MIMO
          systems into groups and refer to each group by name. Specify output groups as a structure. In this
          structure, field names are the group names, and field values are the output channels belonging to
          each group. For example:
          sys.OutputGroup.temperature = [1];
          sys.InputGroup.measurement = [3 5];
          creates output groups named temperature and measurement that include output channels 1, and
          3, 5, respectively. You can then extract the subsystem from all inputs to the measurement outputs
          using:
sys('measurement',:)
Name
Default: ''
Notes
          Any text that you want to associate with the system, stored as a string or a cell array of character
          vectors. The property stores whichever data type you provide. For instance, if sys1 and sys2 are
          dynamic system models, you can set their Notes properties as follows:
ans =
ans =
1-494
                                                                                                  idgrey
UserData
Any type of data you want to associate with system, specified as any MATLAB data type.
Default: []
SamplingGrid
For arrays of identified linear (IDLTI) models that are derived by sampling one or more independent
variables, this property tracks the variable values associated with each model. This information
appears when you display or plot the model array. Use this information to trace results back to the
independent variables.
Set the field names of the data structure to the names of the sampling variables. Set the field values
to the sampled variable values associated with each model in the array. All sampling variables should
be numeric and scalar valued, and all arrays of sampled values should match the dimensions of the
model array.
For example, if you collect data at various operating points of a system, you can identify a model for
each operating point separately and then stack the results together into a single system array. You
can tag the individual models in the array with information regarding the operating point:
where sys is an array containing three identified models obtained at rpms 1000, 5000 and 10000,
respectively.
For model arrays generated by linearizing a Simulink model at multiple parameter values or
operating points, the software populates SamplingGrid automatically with the variable values that
correspond to each entry in the array. For example, the Simulink Control Design commands
linearize and slLinearizer populate SamplingGrid in this way.
Default: []
See Also
getpvec | greyest | greyestOptions | idnlgrey | idss | pem | setpvec | ssest
Topics
“Estimate Coefficients of ODEs to Fit Given Solution”
“Estimate Model Using Zero/Pole/Gain Parameters”
“Estimate Discrete-Time Grey-Box Model with Parameterized Disturbance”
“Specifying the Linear Grey-Box Model Structure”
                                                                                                 1-495
1   Functions
          idinput
          Generate input signals
          Syntax
          u = idinput(N)
          u = idinput([N,Nu])
          u = idinput([Period,Nu,NumPeriod])
          Description
          The idinput command generates an input signal with specified characteristics for your system. You
          can use the generated input, and simulate the response of your system to study system behavior. For
          example, you can study the system response to periodic inputs. The system can be an actual physical
          system or a model such as a Simulink model. You can also design optimal experiments. For example,
          you can determine which input signals isolate faults or nonlinearities in your system. You can also use
          idinput to design an input that has sufficient bandwidth to excite the dynamic range of your system.
          u = idinput(N) returns a single-channel random binary input signal u of length N. The generated
          signal values are either -1 or 1.
          u = idinput([N,Nu]) returns an Nu-channel random binary input signal, where each channel
          signal has length N. The signals in each channel differ from each other.
u = idinput( ___ ,Type) specifies the type of input to be generated as one of the following:
          u = idinput( ___ ,Type,Band) specifies the frequency band of the signal. For pseudorandom
          binary signals (PRBS), Band specifies the inverse of the clock period of the signal.
1-496
                                                                                               idinput
SineData. You can specify characteristics such as the number of sine waves and their frequency
separation. The frequencies of the sine waves are returned in freq.
Examples
Create an iddata object from the generated signal. For this example, specify the sample time as 1
second.
u = iddata([],u,1);
The generated signal is a random binary input signal with values -1 or 1. You can use the generated
input signal to simulate the output of your system using the sim command.
                                                                                               1-497
1   Functions
          N = 200;
          u = idinput([N,2]);
          Create an iddata object from the generated signal. For this example, specify the sample time as 1
          second.
u = iddata([],u,1);
Plot the signals for the two channels, and examine the signals.
plot(u)
The plot shows the two generated random binary signals with values -1 or 1.
1-498
                                                                                               idinput
Generate a single-channel periodic random binary input signal with a period of 10 samples and 5
periods in the signal.
NumChannel = 1;
Period = 10;
NumPeriod = 5;
u = idinput([Period,NumChannel,NumPeriod]);
Create an iddata object from the generated signal. Specify the sample time as 1 second.
u = iddata([],u,1);
plot(u)
As specified, the generated single-channel periodic random binary input signal has a period of 10
seconds, and there are 5 whole periods in the signal.
                                                                                               1-499
1   Functions
          Generate a single-channel periodic random Gaussian input signal with a period of 50 samples and 5
          periods in the signal. First generate the signal using the entire frequency range, then specify a
          passband.
          NumChannel = 1;
          Period = 50;
          NumPeriod = 5;
          u = idinput([Period,NumChannel,NumPeriod],'rgs');
          Create an iddata object from the generated signal, and plot the signal. For this example, specify the
          sample time as 0.01 seconds.
          u = iddata([],u,0.01);
          plot(u)
          The plot shows that u contains a random segment of 50 samples, repeated 5 times. The signal is a
          Gaussian white noise signal with zero mean and variance one.
          Since the sample time is 0.01 seconds, the generated signal has a period of 0.5 seconds. The
          frequency content of the signal spans the entire available range (0-50 Hz).
Now specify a passband between 0 and 25 Hz ( = 0.5 times the Nyquist frequency).
1-500
                                                                                                 idinput
Band = [0 0.5];
u2 = idinput([Period,NumChannel,NumPeriod],'rgs',Band);
u2 = iddata([],u2,0.01);
plot(u2)
A pseudorandom binary input signal (PRBS) is a deterministic signal whose frequency properties
                                                                                     n
mimic white noise. A PRBS is inherently periodic with a maximum period length of 2 − 1, where
integer n is the order of the PRBS. For more information, see “Pseudorandom Binary Signals” on page
1-513.
Range = [-2,2];
Specify the clock period of the signal as 1 sample. That is, the signal value can change at each time
step. For PRBS signals, the clock period is specified in Band = [0 B], where B is the inverse of the
required clock period.
                                                                                                 1-501
1   Functions
Band = [0 1];
u = idinput(100,'prbs',Band,Range);
Warning: The PRBS signal delivered is the 100 first values of a full sequence of length 127.
          A PRBS is inherently periodic. To generate a nonperiodic signal, the software generates a maximum
          length PRBS of length 127 that has a period greater than the required number of samples, 100. The
          software returns the first 100 samples of the generated PRBS. This action ensures that the generated
          signal is not periodic, as indicated in the generated warning.
          Create an iddata object from the generated signal. For this example, specify the sample time as 1
          second.
u = iddata([],u,1);
          plot(u);
          title('Non-Periodic Signal')
The generated signal is a nonperiodic PRBS of length 100 that switches between -2 and 2.
1-502
                                                                                                 idinput
Specify that the pseudorandom binary input signal (PRBS) switches between -2 and 2.
Range = [-2,2];
Specify the clock period of the signal as 1 sample. That is, the signal value can change at each time
step. For PRBS signals, the clock period is specified in Band = [0 B], where B is the inverse of the
required clock period.
Band = [0 1];
Generate a single-channel, periodic PRBS with a period of 100 samples and 3 periods in the signal.
u1 = idinput([100,1,3],'prbs',Band,Range);
Warning: The period of the PRBS signal was changed to 63. Accordingly, the length of the generate
                                                                  n
A PRBS is inherently periodic with a maximum period length of 2 − 1, where integer n is the order of
the PRBS. If the period you specify is not equal to a maximum length PRBS, the software adjusts the
period of the generated signal to obtain an integer number of maximum length PRBS, and issues a
warning. For more information about maximum length PRBS, see “Pseudorandom Binary Signals” on
page 1-513. In this example, the desired period, 100, is not equal to a maximum length PRBS, thus
the software instead generates a maximum length PRBS of order n = floor(log2(Period)) = 6.
                                               6
Thus, the period of the PRBS signal is 63 ( = 2 − 1), and the length of the generated signal is 189 (=
NumPeriod*63). This result is indicated in the generated warning.
Create an iddata object from the generated signal, and plot the signal. Specify the period of the
signal as 63 samples.
u1 = iddata([],u1,1,'Period',63);
plot(u1)
title('Periodic Signal')
                                                                                                 1-503
1   Functions
          Generate periodic and nonperiodic pseudorandom binary input signals (PRBS) with specified clock
          period.
          Generate a single-channel PRBS that switches between -2 and 2. Specify the clock period of the
          signal as 4 samples. That is, the signal has to stay constant for at least 4 consecutive samples before
          it can change. For PRBS signals, the clock period is specified in Band = [0 B], where B is the inverse
          of the required clock period.
          Range = [-2,2];
          Band = [0 1/4];
Warning: The PRBS signal delivered is the 100 first values of a full sequence of length 124.
          To understand the generated warning, first note that the code is equivalent to generating a single-
          channel PRBS with a 100-sample period and 1 period.
u1 = idinput([100,1,1],'prbs',Band,Range);
1-504
                                                                                                  idinput
The generated PRBS signal has to remain constant for at least 4 samples before the value can
change. To satisfy this requirement, the software first computes the order of the smallest possible
                                                                               n
maximum length PRBS as n = floor(log2(Period*B)) = 4 and period 2 − 1 = 15. For
information about maximum length PRBS, see “Pseudorandom Binary Signals” on page 1-513. The
software then stretches this PRBS such that the period of the stretched signal is
           n
P = (1/B)(2 − 1) = 60.
However, since this period is less than the specified length, 100, the software computes instead a
maximum length PRBS of order m = n+1 = 5. The software then stretches this PRBS such that the
                           m
period is now P2 = (1/B)(2 − 1) = 124. The software returns the first 100 samples of this signal as
u1. This result ensures that the generated signal is not periodic but is constant for every 4 samples.
Create an iddata object from the generated signal. For this example, specify the sample time as 1
second.
u1 = iddata([],u1,1);
The generated signal is a nonperiodic PRBS of length 100. The signal remains constant for at least 4
samples before each change in value. Thus, the signal satisfies the clock period specified in Band.
                                                                                                 1-505
1   Functions
u2 = idinput([100,1,3],'prbs',Band,Range);
Warning: The period of the PRBS signal was changed to 60. Accordingly, the length of the generate
          To generate a periodic signal with specified clock period, the software generates u2 as 3 repetitions
          of the original stretched signal of period P = 60. Thus, the length of u2 is P*NumPeriod = 60*3 =
          180. This change in period and length of the generated signal is indicated in the generated warning.
          Create an iddata object from the generated signal, and plot the signal. Specify the period of the
          signal as 60 seconds.
          u2 = iddata([],u2,1,'Period',60);
          plot(u2)
          title('Periodic Signal')
          The generated signal is a periodic PRBS with a 60-second period and 3 periods. The signal remains
          constant for at least 4 samples before each change in value. Thus, the signal satisfies the specified
          clock period.
          You can generate a sum-of-sinusoids signal using default characteristics for the sine waves.
          Alternatively, you configure the number of sine waves, and the frequencies and phases of the sine
          waves. This example shows both approaches.
1-506
                                                                                                    idinput
Specify that the signal has 50 samples in each period and 3 periods. Also specify that the signal
amplitude range is between -1 and 1.
Period = 50;
NumPeriod = 3;
Range = [-1 1];
Specify the frequency range of the signal. For a sum-of-sinusoids signal, you specify the lower and
upper frequencies of the passband in fractions of the Nyquist frequency. In this example, use the
entire frequency range between 0 and Nyquist frequency.
Band = [0 1];
First generate the signal using default characteristics for the sine waves. By default, the software
uses 10 sine waves to generate the signal. The software assigns a random phase to each sinusoid, and
then changes these phases 10 times to get the smallest signal spread. The signal spread is the
difference between the minimum and the maximum value of the signal over all samples.
The software returns the sum-of-sinusoids signal in u and the frequencies of the sinusoids in freq.
The values in freq are scaled assuming that the sample time is 1 time unit. Suppose that the sample
time is 0.01 hours. To retrieve the actual frequencies in rad/hours, divide the values by the sample
time.
ans = 12.5664
freq(1) is the frequency of the first sine wave. To see how the software chooses the frequencies, see
the SineData argument description on the idinput reference page.
To verify that 10 sine waves were used to generate the signal, you can view the frequency content of
the signal. Perform a Fourier transform of the signal, and plot the single-sided amplitude spectrum of
the signal.
ufft = fft(u);
Fs = 2*pi/Ts; % Sampling frequency in rad/hour
L = length(u);
w = (0:L-1)*Fs/L;
stem(w(1:L/2),abs(ufft(1:L/2))) % Plot until Nyquist frequency
title('Single-Sided Amplitude Spectrum of u(t)')
xlabel('Frequency (rad/hour)')
ylabel('Amplitude')
                                                                                                    1-507
1   Functions
          The generated plot shows the frequencies of the 10 sine waves used to generate the signal. For
          example, the plot shows that the first sine wave has a frequency of 12.57 rad/hour, the same as
          freq(1).
          Convert the generated signal into an iddata object, and plot the signal. Specify the sample time as
          0.01 hours.
          u = iddata([],u,Ts,'TimeUnit','hours');
          plot(u)
1-508
                                                                                                idinput
The signal u is generated using 10 sinusoids and has a period of 0.5 hours and 3 periods.
Now modify the number, frequency, and phase of the sinusoids that are used to generate the sum-of-
sinusoids signal. Use 12 sinusoids and try 15 different sets of phases. To set the frequencies of the
sinusoids, specify GridSkip = 2. The software selects the frequencies of the sinusoids from the
intersection of the frequency grid 2*pi*[1:GridSkip:fix(Period/2)]/Period and the
passband pi*Band.
NumSinusoids = 12;
NumTrials = 15;
GridSkip = 2;
SineData = [NumSinusoids,NumTrials,GridSkip];
u2 = idinput([Period 1 NumPeriod],'sine',Band,Range,SineData);
Convert the generated signal into an iddata object, and plot the signal.
u2 = iddata([],u2,Ts,'TimeUnit','hours');
plot(u2)
                                                                                                1-509
1   Functions
The signal u2 is generated using 12 sinusoids and has a period of 0.5 hours and 3 periods.
          Input Arguments
          N — Number of generated input data samples
          real positive integer
          Number of generated input data samples, specified as a real positive integer. For a single-channel
          input data, the generated input u has N rows. For an Nu-channel input data, u is returned as an N-by-
          Nu matrix, where each channel signal has length N.
          Number of samples in each period of generated signal, specified as a real positive integer. Use this
          input to specify a periodic signal. Also specify the number of periods in NumPeriod. Each generated
          input channel signal has NumPeriod*Period samples.
1-510
                                                                                                  idinput
Number of periods in generated signal, specified as a real positive integer. Use this input to specify a
periodic signal. Also specify the signal Period. Each generated input channel signal has
NumPeriod*Period samples.
• 'rbs' — Generates a random binary signal. A random binary signal is a random process that
  assumes only two values. You can specify these values using Range. To generate a band-limited
  signal, specify the passband in Band. To generate a periodic signal, specify Period and
  NumPeriod.
• 'rgs' — Generates a random Gaussian signal. The generated Gaussian signal has mean μ and
  standard deviation σ such that [μ-σ, μ+σ] equals Range. To generate a band-limited Gaussian
  signal, specify the passband in Band. To generate a periodic Gaussian signal with an n samples
  period that repeats itself m times, specify Period as n and NumPeriod as m.
• 'prbs'— Generates a pseudorandom binary signal (PRBS). A PRBS is a periodic, deterministic
  signal with white-noise-like properties that shifts between two values. You can specify these two
  values using Range. You can also specify the clock period, the minimum number of sampling
  intervals for which the value of the signal does not change. You specify the inverse of the clock
  period in Band.
   The length of the generated signal is not always the same as what you specify. The length depends
   on whether you require a periodic or nonperiodic signal and also on the clock period you specify.
   For more information, see “Pseudorandom Binary Signals” on page 1-513.
• 'sine'— Generates a signal that is a sum-of-sinusoids. The software selects the frequencies of
  the sinusoids to be equally spread over a chosen grid and assigns each sinusoid a random phase.
  The software then tries several random phases for each sinusoid and selects the phases that give
  the smallest signal spread. The signal spread is the difference between the minimum and the
  maximum value of the signal over all samples. The amplitude of the generated sum-of-sinusoids
  signal is scaled to satisfy the Range you specify.
   You can specify the characteristics of the sine waves used to generate the signal, such as the
   number of sine waves and their frequency separation, in the SineData argument.
Frequency range of generated signal, specified as a 1-by-2 row vector containing minimum and
maximum frequency values.
• If Type is 'rgs', 'rbs', or 'sine' — Specify Band as a passband [wlow whigh]. Where, wlow
  and whigh are the lower and upper frequencies of the passband, expressed in fractions of the
  Nyquist frequency. For example, to generate an input with white noise characteristics, use Band
  = [0 1].
   The software achieves the frequency contents for a random Gaussian signal ('rgs') using
   idfilt with an eighth-order Butterworth, noncausal filter. For generating a random binary signal
   ('rbs'), the software uses the same filter and then makes the signal binary. Thus, the frequency
   content in the generated random binary signal may not match the specified passband.
                                                                                                  1-511
1   Functions
                For 'sine' signals, the frequencies of the sinusoids are selected to be equally spread over a
                chosen grid in the specified passband. For more information, see the SineData argument
                description.
          • If Type is 'prbs' — Specify Band as [0 B], where B is the inverse of the clock period of the
            signal. The clock period is the minimum number of sampling intervals for which the value of the
            signal does not change. Thus, the generated signal is constant over intervals of length 1/B
            samples. If 1/B is not an integer, the software uses floor(1/B) as the clock period.
Generated input signal range, specified as a two-element row vector of the form [umin,umax].
          • If Type is 'rbs' or 'prbs'— The generated signal u has values umin or umax.
          • If Type is 'sine' — The generated signal u has values between umin and umax.
          • If Type is 'rgs' — The generated Gaussian signal has mean μ and standard deviation σ such that
            umin and umax are equal to μ-σ and μ+σ, respectively. For example, Range = [-1,1] returns a
            Gaussian white noise signal with zero mean and variance one.
          • NumSinusoids is the number of sinusoids used to generate the signal. The default value is 10.
          • NumTrials is the number of different random relative phases of the sinusoids that the software
            tries to find the lowest signal spread. The signal spread is the difference between the minimum
            and the maximum value of the signal over all samples.
                The maximum amplitude of the sum-of-sinusoids signal depends on the relative phases of the
                different sinusoids. To find the phases that give the smallest signal spread, the software tries
                NumTrials different random choices of phases to find the best phase values. For example,
                suppose that NumSinusoids is 20 and NumTrials is 5. The software tries 5 different sets of
                relative phases for the 20 sinusoids, and selects the phases that give the smallest signal spread.
                The default value for NumTrials is 10.
          • GridSkip is used to characterize the frequency of the sinusoids. The software selects the
            frequency of the sinusoids from the intersection of the frequency grid
            2*pi*[1:GridSkip:fix(Period/2)]/Period and the pass band pi*[Band(1) Band(2)].
            For multichannel input signals, the software uses different frequencies from this frequency grid to
            generate the different input channels. You can use GridSkip for controlling odd and even
            frequency multiples, for example, to detect nonlinearities of different kinds.
                To extract the frequencies freq that are selected by the software to generate the signal, use the
                following syntax.
[u,freq] = idinput(__)
          Output Arguments
          u — Generated input signal
          column vector | matrix
1-512
                                                                                                   idinput
Generated input signal, returned as a column vector of length N for a single-channel input or an N-by-
Nu matrix for an Nu-channel signal. You use the generated signal to simulate the response of your
system using sim.
You can create an iddata object from u by specifying output data as [].
u = iddata([],u);
In the iddata object, you can also specify the properties of the signal such as sample time, input
names, and periodicity.
Frequencies of sine waves used for sum-of-sinusoids signal, returned as a column vector of length
equal to the number of sinusoids, NumSinusoids. You specify NumSinusoids in the SineData
argument. The frequency values are scaled assuming the sample time is 1 time unit. To retrieve the
actual frequencies, divide the values by the sample time. For an example, see “Generate a Sum-of-
Sinusoids Signal” on page 1-506.
For multichannel input signals, freq is an Nu-by-NumSinusoids matrix where the kth row contains
the frequencies corresponding to the kth channel. For information about how the software selects the
frequencies, see the SineData argument description.
More About
Pseudorandom Binary Signals
Here, u(t − 1), …u(t − n) is the vector of past inputs, n is the PRBS order, and rem denotes the
remainder when a1u(t − 1) + …anu(t − n) is divided by 2. Thus, a PRBS can only take the values 0
and 1. The software scales these values according to the Range you specify. In addition, the vector of
past inputs u(t − 1), …u(t − n) can only take 2n values. Out of these values, the state with all zeros is
ignored because it will result in future signals equal to zero. Thus, a PRBS is an inherently periodic
signal with a maximum period length of 2n-1. The following table lists the maximum length possible
for different orders n of the PRBS.
                                                                                                   1-513
1   Functions
Note The software does not generate signals with period greater than 232-1.
          Since PRBS are inherently periodic, the length and period of the generated signal depends on the
          clock period that you specify and whether you require a periodic or nonperiodic signal. The clock
          period is the minimum number of sampling intervals for which the value of the signal does not
          change. You specify the clock period in Band.
          • To generate a nonperiodic signal of length N, (NumPeriod = 1), the software first computes a
            maximum length PRBS with a period greater than N. The software then returns the first N samples
            of the PRBS as u. This action ensures that u is not periodic. For example, if N is 100, the software
            creates a maximum length PRBS of period 127 (order 7), and returns the first 100 samples as u.
                For an example, see “Generate a Nonperiodic Pseudorandom Binary Input Signal” on page 1-501.
          • To generate a periodic signal (NumPeriod > 1), the software adjusts the period of the signal to
            obtain an integer number of maximum length PRBS. To do so, the software computes a PRBS of
            order n = floor(log2(Period)) and period P = 2n-1. The signal u is then generated as
            NumPeriod repetitions of this PRBS signal of period P. Thus, the length of u is P*NumPeriod.
For an example, see “Generate a Periodic Pseudorandom Binary Input Signal” on page 1-502.
                In the multiple-input channel case, the signals are maximally shifted. That is, the overlap between
                the different inputs is minimized. This means Period/NumPeriod is an upper bound for the
                model orders that you can estimate using such a signal.
          The generated signal has to remain constant for at least 1/B samples. To satisfy this requirement, the
          software first computes the order of the smallest possible maximum length PRBS as n =
          floor(log2(Period*B)) and period 2n-1. The software then stretches the PRBS such that period
          of the stretched signal is P = B-1(2n-1).
          • To generate a nonperiodic signal of length N , if the period P of the stretched signal is greater than
            or equal to N, the software returns the first N samples of the stretched signal as u. This ensures
            that u is nonperiodic but constant for every 1/B samples. Note that for a nonperiodic signal,
            Period is equal to N.
                If the period P is less than N, the software computes instead a maximum length PRBS of order n2
                = n+1. The software then stretches this PRBS such that the period is now P2 = B-1(2n2-1). The
                software then returns the first N samples of this signal as u.
          • To generate a periodic signal, the software generates u as NumPeriod repetitions of the stretched
            signal of period P. Thus, the length of u is P*NumPeriod.
          For an example, see “Generate Pseudorandom Binary Input Signal with Specified Clock Period” on
          page 1-504.
1-514
                                                                                                 idinput
References
[1] Söderström, T. and P. Stoica., Chapter C5.3 in System Identification, Prentice Hall, 1989.
[2] Ljung, L., Section 13.3 in System Identification: Theory for the User, Prentice Hall PTR, 1999.
See Also
iddata | sim
Topics
“Ways to Obtain Identification Data”
“Generate Data Using Simulation”
“Simulate and Predict Identified Model Output”
                                                                                                 1-515
1   Functions
          idnlarx
          Nonlinear ARX model
          Syntax
          sys   =   idnlarx(Orders)
          sys   =   idnlarx(Orders,Nonlinearity)
          sys   =   idnlarx(Orders,Nonlinearity,Name,Value)
          sys   =   idnlarx(LinModel)
          sys   =   idnlarx(LinModel,Nonlinearity)
          sys   =   idnlarx(LinModel,Nonlinearity,Name,Value)
          Description
          sys = idnlarx(Orders) creates a nonlinear ARX model with the specified orders using a default
          wavelet network nonlinearity estimator.
          sys = idnlarx(LinModel) uses a linear ARX model LinModel to specify the model orders and
          the initial values of the linear coefficients of the model.
          Object Description
          idnlarx represents a nonlinear ARX model, which is an extension of the linear ARX structure and
          contains linear and nonlinear functions. For more information, see “Nonlinear ARX Model Extends
          the Linear ARX Structure”.
Use the nlarx command to both construct an idnlarx object and estimate the model parameters.
          You can also use the idnlarx constructor to create the nonlinear ARX model and then estimate the
          model parameters using nlarx or pem.
Examples
m = idnlarx([2 2 1]);
1-516
                                                                                  idnlarx
M = idnlarx([3 2 1]);
M.Nonlinearity = 'sigmoidnet';
M.NonlinearRegressors = 'input';
m = idnlarx([2 3 1],sigmoidnet('NumberOfUnits',15));
m = idnlarx([2 2 1],[]);
C = {'y1(t-1)^2','y1(t-2)*u1(t-3)'};
Create a nonlinear ARX model with custom regressors and no standard regressors.
A = [1 -1.2 0.5];
B = [0.8 1];
LinearModel = idpoly(A, B, 'Ts', 0.1);
m1 = idnlarx(LinearModel);
                                                                                  1-517
1   Functions
          Input Arguments
          Orders — Model orders and delays
          1-by-3 vector of positive integers | 1-by-3 vector of matrices
          Model orders and delays for defining the regressor configuration, specified as a 1-by-3 vector, [na
          nb nk].
          • na is an ny-by-ny matrix, where na(i,j) specifies the number of regressors from the jth output
            used to predict the ith output.
          • nb is an ny-by-nu matrix, where nb(i,j) specifies the number of regressors from the jth input
            used to predict the ith output.
          • nk is an ny-by-nu matrix, where nk(i,j) specifies the lag in the jth input used to predict the ith
            output.
          na = [1 2; 2 3]
          nb = [1 2 3; 2 3 1];
          nk = [2 0 3; 1 0 5];
          The estimation data for this system has three inputs (u1, u2, u3) and two outputs (y1, y2). Consider
          the regressors used to predict output, y2(t):
• Since na(2,:) is [2 3], the contributing regressors from the outputs are:
          Note The minimum lag for regressors based on output variables is always 1, while the minimum lag
          for regressors based on input variables is dictated by nk. Use getreg to view the complete set of
          regressors used by the nonlinear ARX model.
1-518
                                                                                                       idnlarx
For more information, see “Available Nonlinearity Estimators for Nonlinear ARX Models”.
        Specifying a character vector, for example 'sigmoidnet', creates a nonlinearity estimator object
        with default settings. Alternatively, you can specify nonlinearity estimator settings in two ways:
• Use the associated nonlinearity estimator function with Name-Value pair arguments.
           NL = sigmoidnet('NumberOfUnits',10);
        • Create and modify a default nonlinearity estimator object.
           NL = sigmoidnet;
           NL.NumberOfUnits = 10;
        For ny output channels, you can specify nonlinear estimators individually for each channel by setting
        Nonlinearity to an ny-by-1 array of nonlinearity estimator objects. To specify the same nonlinearity
        for all outputs, specify Nonlinearity as a character vector or a single nonlinearity estimator object.
        Example: 'sigmoidnet' specifies a sigmoid network nonlinearity with a default configuration.
        Example: treepartition('NumberOfUnits',5) specifies a binary-tree nonlinearity with 5 terms
        in the binary tree expansion.
        Example: [wavenet('NumberOfUnits',10);sigmoidnet] specifies different nonlinearity
        estimators for two output channels.
        Discrete time input-output polynomial model of ARX structure, specified as an idpoly model. Create
        this object using the idpoly constructor or estimate it using the arx command.
        Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
        Value is the corresponding value. Name must appear inside quotes. You can specify several name and
        value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
        Use Name,Value arguments to specify additional properties on page 1-519 of idnlarx models
        during model creation. For example, m = idnlarx([2 3
        1],'treepartition','InputName','Pressure','Ts',0.1) creates an idnlarx model with
        the input name Pressure, and a sample time of 0.1 seconds
        Properties
        na, nb, nk
Model orders and delays for defining the regressor configuration, specified as nonnegative integers.
                                                                                                       1-519
1   Functions
          • na is an ny-by-ny matrix, where na(i,j) specifies the number of regressors from the jth output
            used to predict the ith output.
          • nb is an ny-by-nu matrix, where nb(i,j) specifies the number of regressors from the jth input
            used to predict the ith output.
          • nk is an ny-by-nu matrix, where nk(i,j) specifies the lag in the jth input used to predict the ith
            output.
          na = [1 2; 2 3]
          nb = [1 2 3; 2 3 1];
          nk = [2 0 3; 1 0 5];
          The estimation data for this system has three inputs (u1, u2, u3) and two outputs (y1, y2). Consider
          the regressors used to predict output, y2(t):
• Since na(2,:) is [2 3], the contributing regressors from the outputs are:
          Note The minimum lag for regressors based on output variables is always 1, while the minimum lag
          for regressors based on input variables is dictated by nk. Use getreg to view the complete set of
          regressors used by the nonlinear ARX model.
CustomRegressors
Regressors constructed from combinations of inputs and outputs, specified as one of the following:
• {'y1(t-3)^3','y2(t-1)*u1(t-3)','sin(u3(t-2))'}
                Each character vector must represent a valid formula for a regressor contributing towards the
                prediction of the model output. The formula must be written using the input and output names
                and the time-variable name as variables.
          • Array of custom regressor objects, created using customreg or polyreg.
          For a model with ny outputs, specify an ny-by-1 cell array of customreg objects arrays or an ny-by-1
          cell array of cell array of character vectors.
These regressors are in addition to the standard regressors based on na, nb, and nk.
Default: {}
1-520
                                                                                                           idnlarx
NonlinearRegressors
         Subset of regressors that enter as inputs to the nonlinear block of the model, specified as one of the
         following:
         For a model with multiple outputs, specify a cell array of ny elements, where ny is the number of
         output channels. For each output, specify one of the preceding options. Alternatively, to apply the
         same regressor subset to all model outputs, specify [] or any of the character vector options alone,
         for example 'standard'.
Default: 'all'
Nonlinearity
For more information, see “Available Nonlinearity Estimators for Nonlinear ARX Models”.
         Specifying a character vector, for example 'sigmoidnet', creates a nonlinearity estimator object
         with default settings. Alternatively, you can specify nonlinearity estimator settings in two ways:
         • Use the associated nonlinearity estimator function with Name-Value pair arguments:
            NL = sigmoidnet('NumberOfUnits',10);
         • Create and modify a default nonlinearity estimator object:
            NL = sigmoidnet;
            NL.NumberOfUnits = 10;
         For ny output channels, you can specify nonlinear estimators individually for each channel by setting
         Nonlinearity to an array of ny nonlinearity estimator objects, where ny is the number of outputs. To
                                                                                                          1-521
1   Functions
          specify the same nonlinearity for all outputs, specify Nonlinearity as a character vector or a single
          nonlinearity estimator object.
Default: 'wavenet'
Report
          Summary report that contains information about the estimation options and results when the model is
          estimated using the nlarx command. Use Report to query a model for how it was estimated,
          including its:
          • Estimation method
          • Estimation options
          • Search termination conditions
          • Estimation data fit
          m = idnlarx([2 2 1]);
          m.Report.OptionsUsed
ans =
[]
          If you use nlarx to estimate the model, the fields of Report contain information on the estimation
          data, options, and results.
          load iddata1;
          m = nlarx(z1, [2 2 1]);
          m.Report.OptionsUsed
                IterativeWavenet:   'auto'
                           Focus:   'prediction'
                         Display:   'off'
                  Regularization:   [1x1 struct]
                    SearchMethod:   'auto'
                   SearchOptions:   [1x1 idoptions.search.identsolver]
                    OutputWeight:   'noise'
                        Advanced:   [1x1 struct]
          For more information on this property and how to use it, see “Output Arguments” on page 1-771 in
          the nlarx reference page and “Estimation Report”.
TimeVariable
          Independent variable for the inputs, outputs, and—when available—internal states, specified as a
          character vector.
1-522
                                                                                                  idnlarx
NoiseVariance
Ts
Sample time. Ts is a positive scalar representing the sampling period. This value is expressed in the
unit specified by the TimeUnit property of the model.
Default: 1
TimeUnit
Units for the time variable, the sample time Ts, and any time delays in the model, specified as one of
the following values:
• 'nanoseconds'
• 'microseconds'
• 'milliseconds'
• 'seconds'
• 'minutes'
• 'hours'
• 'days'
• 'weeks'
• 'months'
• 'years'
Changing this property has no effect on other properties, and therefore changes the overall system
behavior. Use chgTimeUnit to convert between time units without modifying system behavior.
Default: 'seconds'
InputName
Alternatively, use automatic vector expansion to assign input names for multi-input models. For
example, if sys is a two-input model, enter:
sys.InputName = 'controls';
When you estimate a model using an iddata object, data, the software automatically sets
InputName to data.InputName.
You can use the shorthand notation u to refer to the InputName property. For example, sys.u is
equivalent to sys.InputName.
                                                                                                  1-523
1   Functions
InputUnit
Use InputUnit to keep track of input signal units. InputUnit has no effect on system behavior.
InputGroup
          Input channel groups. The InputGroup property lets you assign the input channels of MIMO systems
          into groups and refer to each group by name. Specify input groups as a structure. In this structure,
          field names are the group names, and field values are the input channels belonging to each group.
          For example:
          sys.InputGroup.controls = [1 2];
          sys.InputGroup.noise = [3 5];
          creates input groups named controls and noise that include input channels 1, 2 and 3, 5,
          respectively. You can then extract the subsystem from the controls inputs to all outputs using:
sys(:,'controls')
OutputName
          Alternatively, use automatic vector expansion to assign output names for multi-output models. For
          example, if sys is a two-output model, enter:
sys.OutputName = 'measurements';
          When you estimate a model using an iddata object, data, the software automatically sets
          OutputName to data.OutputName.
          You can use the shorthand notation y to refer to the OutputName property. For example, sys.y is
          equivalent to sys.OutputName.
1-524
                                                                                                  idnlarx
OutputUnit
Use OutputUnit to keep track of output signal units. OutputUnit has no effect on system behavior.
OutputGroup
Output channel groups. The OutputGroup property lets you assign the output channels of MIMO
systems into groups and refer to each group by name. Specify output groups as a structure. In this
structure, field names are the group names, and field values are the output channels belonging to
each group. For example:
sys.OutputGroup.temperature = [1];
sys.InputGroup.measurement = [3 5];
creates output groups named temperature and measurement that include output channels 1, and
3, 5, respectively. You can then extract the subsystem from all inputs to the measurement outputs
using:
sys('measurement',:)
Name
Default: ''
Notes
Any text that you want to associate with the system, stored as a string or a cell array of character
vectors. The property stores whichever data type you provide. For instance, if sys1 and sys2 are
dynamic system models, you can set their Notes properties as follows:
ans =
                                                                                                  1-525
1   Functions
ans =
UserData
Any type of data you want to associate with system, specified as any MATLAB data type.
Default: []
          Output Arguments
          sys — Nonlinear ARX model
          idnlarx object
          Nonlinear ARX model, returned as an idnlarx object. This model is created using the specified
          model orders, nonlinearity estimator, and properties.
          More About
          Nonlinear ARX Model Structure
          A nonlinear ARX model consists of model regressors and a nonlinearity estimator. The nonlinearity
          estimator comprises both linear and nonlinear functions that act on the model regressors to give the
          model output. This block diagram represents the structure of a nonlinear ARX model in a simulation
          scenario.
The software computes the nonlinear ARX model output y in two stages:
1 It computes regressor values from the current and past input values and past output data.
                In the simplest case, regressors are delayed inputs and outputs, such as u(t-1) and y(t-3). These
                kind of regressors are called standard regressors. You specify the standard regressors using the
                model orders and delay. For more information, see “Nonlinear ARX Model Orders and Delay”. You
                can also specify custom regressors, which are nonlinear functions of delayed inputs and outputs.
                For example, u(t-1)*y(t-3). To create a set of polynomial type regressors, use polyreg.
1-526
                                                                                                    idnlarx
    By default, all regressors are inputs to both the linear and the nonlinear function blocks of the
    nonlinearity estimator. You can choose a subset of regressors as inputs to the nonlinear function
    block.
2   It maps the regressors to the model output using the nonlinearity estimator block. The
    nonlinearity estimator block can include linear and nonlinear blocks in parallel. For example:
F(x) = LT (x − r) + d + g Q(x − r)
    Here, x is a vector of the regressors, and r is the mean of the regressors x. LT (x) + d is the output
    of the linear function block and is affine when d ≠ 0. d is a scalar offset. g Q(x − r) represents
    the output of the nonlinear function block. Q is a projection matrix that makes the calculations
    well conditioned. The exact form of F(x) depends on your choice of the nonlinearity estimator.
    You can select from available nonlinearity estimators, such as tree-partition networks, wavelet
    networks, and multilayer neural networks. You can also exclude either the linear or the nonlinear
    function block from the nonlinearity estimator.
    When estimating a nonlinear ARX model, the software computes the model parameter values,
    such as L, r, d, Q, and other parameters specifying g.
Resulting nonlinear ARX models are idnlarx objects that store all model data, including model
regressors and parameters of the nonlinearity estimator. For more information about these objects,
see “Nonlinear Model Structures”.
The states of an idnlarx object are an ordered list of delayed input and output variables that define
the structure of the model. The toolbox uses this definition of states for creating the initial state
vector that is used during simulation and prediction with sim, predict, and compare. This
definition is also used for linearization of nonlinear ARX models using linearize.
This toolbox provides several options to facilitate how you specify the initial states. For example, you
can use findstates and data2state to search for state values in simulation and prediction
applications. For linearization, use findop. You can also specify the states manually.
The states of an idnlarx model depend on the maximum delay in each input and output variable
used by the regressors. If a variable p has a maximum delay of D samples, then it contributes D
elements to the state vector at time t: p(t-1), p(t-2), ..., p(t-D).
m = idnlarx([2 3 0],'wavenet','CustomRegressors',{'y1(t-10)*u1(t-1)'});
getreg(m)
Regressors:
    y1(t-1)
    y1(t-2)
    u1(t)
    u1(t-1)
    u1(t-2)
    y1(t-10)*u1(t-1)
                                                                                                   1-527
1   Functions
          The regressors show that the maximum delay in the output variable y1 is 10 samples and the
          maximum delay in the input u1 is two samples. Thus, this model has a total of 12 states:
X(t) = [y1(t-1),y2(t-2),…,y1(t-10),u1(t-1),u1(t-2)]
Note The state vector includes the output variables first, followed by input variables.
getreg(m)
          Regressors:
            For output 1:
              y1(t-1)
              y1(t-2)
              u1(t-1)
              u1(t-2)
              u2(t)
              u2(t-1)
              u3(t)
            For output 2:
              y1(t-1)
              u1(t-1)
              u2(t-1)
              u2(t-2)
              u2(t-3)
              u2(t-4)
              u2(t-5)
          The maximum delay in output variable y1 is two samples. This delay occurs in the regressor set for
          output 1. The maximum delays in the three input variables are 2, 5, and 0, respectively. Thus, the
          state vector is:
          Variables y2 and u3 do not contribute to the state vector because the maximum delay in these
          variables is zero.
          A simpler way to determine states by inspecting regressors is to use getDelayInfo, which returns
          the maximum delays in all I/O variables across all model outputs. For the multiple-input multiple-
          output model m, getDelayInfo returns:
maxDel = getDelayInfo(m)
maxDel = 1×5
2 0 2 5 0
          maxDel contains the maximum delays for all input and output variables in the order (y1, y2, u1, u2,
          u3). The total number of model states is sum(maxDel) = 9.
1-528
                                                                                    idnlarx
See Also
addreg | customnet | customreg | getreg | idnlarx/findop | linear | linearize | nlarx |
pem | polyreg | sigmoidnet | wavenet
Topics
“Use nlarx to Estimate Nonlinear ARX Models”
“Estimate Nonlinear ARX Models Initialized Using Linear ARX Models”
“Initialize Nonlinear ARX Estimation Using Linear Model”
“Identifying Nonlinear ARX Models”
“Nonlinear Model Structures”
Introduced in R2007a
                                                                                    1-529
1   Functions
          idnlgrey
          Nonlinear grey-box model
          Syntax
          sys   =   idnlgrey(FileName,Order,Parameters)
          sys   =   idnlgrey(FileName,Order,Parameters,InitialStates)
          sys   =   idnlgrey(FileName,Order,Parameters,InitialStates,Ts)
          sys   =   idnlgrey(FileName,Order,Parameters,InitialStates,Ts,Name,Value)
          Description
          sys = idnlgrey(FileName,Order,Parameters) creates a nonlinear grey-box model using the
          specified model structure in FileName, number of outputs, inputs, and states in Order, and the
          model parameters.
          Object Description
          idnlgrey represents a nonlinear grey-box model. For information about the nonlinear grey-box
          models, see “Estimate Nonlinear Grey-Box Models”.
          Use the idnlgrey constructor to create the nonlinear grey-box model and then estimate the model
          parameters using nlgreyest.
Examples
          Load data.
          load(fullfile(matlabroot,'toolbox','ident','iddemos','data','dcmotordata'));
          z = iddata(y,u,0.1,'Name','DC-motor');
          The data is from a linear DC motor with one input (voltage), and two outputs (angular position and
          angular velocity). The structure of the model is specified by dcmotor_m.m file.
1-530
                                                                                                  idnlgrey
file_name = 'dcmotor_m';
Order = [2 1 2];
Parameters = [1;0.28];
InitialStates = [0;0];
Load data.
load(fullfile(matlabroot,'toolbox','ident','iddemos','data','twotankdata'));
z = iddata(y,u,0.2,'Name','Two tanks');
The data contains 3000 input-output data samples of a two tank system. The input is the voltage
applied to a pump, and the output is the liquid level of the lower tank.
Specify file describing the model structure for a two-tank system. The file specifies the state
derivatives and model outputs as a function of time, states, inputs, and model parameters.
FileName = 'twotanks_c';
Order = [1 1 2];
InitialStates = [0;0.1];
Ts = 0;
nlgr.Parameters(1).Fixed = true;
nlgr.Parameters(4).Fixed = true;
nlgr.Parameters(5).Fixed = true;
nlgr = nlgreyest(z,nlgr);
                                                                                                  1-531
1   Functions
          Input Arguments
          FileName — Name of the function or MEX-file that stores the model structure
          character vector | function handle
          Name of the function or MEX-file storing the model structure, specified as a character vector (without
          the file extension) or a function handle for computing the states and the outputs. If FileName is a
          character vector, for example 'twotanks_c', then it must point to a MATLAB file, P-code file, or
          MEX-file. For more information about the file variables, see “Specifying the Nonlinear Grey-Box
          Model Structure”.
Number of outputs, inputs, and states of the model, specified as one of the following:
          • Vector [Ny Nu Nx], specifying the number of model outputs Ny, inputs Nu, and states Nx.
          • Structure with fields'Ny', 'Nu', and 'Nx'.
For time series, Nu is set to 0, and for static model structures, Nx is set to 0.
          • Np-by-1 structure array, where Np is the number of parameters. The structure contains the
            following fields:
1-532
                                                                                                    idnlgrey
   Use dot notation to access the subfields of the ith parameter. For example, for idnlgrey model
   M, the ith parameter is accessed through M.Parameters(i) and its subfield Fixed by
   M.Parameters(i).Fixed.
• Np-by-1 vector of real finite initial values, InParameters.
   The data is converted into a structure with default values for the fields Name, Unit, Minimum,
   Maximum, and Fixed.
Default values are used for the fields Name, Unit, Minimum, Maximum, and Fixed.
• Nx-by-1 structure array, where Nx is the number of states. The structure contains the following
  fields:
                                                                                                     1-533
1   Functions
                Use dot notation to access the subfields of the ith initial state. For example, for idnlgrey model
                M, the ith initial state is accessed through M.InitialStates(i) and its subfield Fixed by
                M.InitialStates(i).Fixed.
          • [].
                A structure is created with default values for the fields Name, Unit, Minimum, Maximum, and
                Fixed.
                Value of the ith structure array element is InitStates(i,Ne), a row vector with Ne elements.
                Minimum, Maximum, and Fixed will be -Inf, Inf and true row vectors of the same size as
                InitStates(i,Ne).
          • Cell array with finite real vectors of size 1-by-Ne or {} (same as []).
          Ts — Sample time
          0 (default) | scalar
          Sample time, specified as a positive scalar representing the sampling period. The value is expressed
          in the unit specified by the TimeUnit property of the model. For a continuous time model Ts is equal
          to 0 (default).
1-534
                                                                                                   idnlgrey
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Use Name,Value arguments to specify additional properties on page 1-535 of idnlgrey models
during model creation.
Properties
idnlgrey object properties include:
FileName
Name of the function or MEX-file storing the model structure, specified as a character vector (without
extension) or a function handle for computing the states and the outputs. If FileName is a character
vector, for example 'twotanks_c', then it must point to a MATLAB file, P-code file, or MEX-file. For
more information about the file variables, see “Specifying the Nonlinear Grey-Box Model Structure”.
Order
Number of outputs, inputs, and states of the model, specified as one of the following:
• Vector [Ny Nu Nx], specifying the number of model outputs Ny, inputs Nu, and states Nx.
• Structure with fields'Ny', 'Nu', and 'Nx'.
For time series, Nu is set to 0, and for static model structures, Nx is set to 0.
Parameters
• Np-by-1 structure array, where Np is the number of parameters. The structure contains the
  following fields:
                                                                                                    1-535
1   Functions
                The data is converted into a structure with default values for the fields Name, Unit, Minimum,
                Maximum, and Fixed.
                A structure is created with default values for the fields Name, Unit, Minimum, Maximum, and
                Fixed.
          Use dot notation to access the subfields of the ith parameter. For example, for idnlgrey model M,
          the ith parameter is accessed through M.Parameters(i) and its subfield Fixed by
          M.Parameters(i).Fixed.
InitialStates
          • Nx-by-1 structure array, where Nx is the number of states. The structure contains the following
            fields:
1-536
                                                                                                idnlgrey
   A structure is created with default values for the fields Name, Unit, Minimum, Maximum, and
   Fixed.
   Value of the ith structure array element is InitStates(i,Ne), a row vector with Ne elements.
   Minimum, Maximum, and Fixed will be -Inf, Inf and true row vectors of the same size as
   InitStates(i,Ne).
• Cell array with finite real vectors of size 1-by-Ne or {} (same as []).
   A structure is created with default values for the fields Name, Unit, Minimum, Maximum, and
   Fixed.
Use dot notation to access the subfields of the ith initial state. For example, for idnlgrey model M,
the ith initial state is accessed through M.InitialStates(i) and its subfield Fixed by
M.InitialStates(i).Fixed.
                                                                                                 1-537
1   Functions
FileArgument
          Contains auxiliary variables passed to the ODE file (function or MEX-file) specified in FileName,
          specified as a cell array. These variables are used as extra inputs for specifying the state and/or
          output equations.
          Default: {}.
SimulationOptions
A structure that specifies the simulation method and related options, containing the following fields:
Assignable values:
                    Assignable values: 1, 2, 3, 4 or 5.
MaxStep             Specifies the largest time step of the ODE solver.       'Auto'
1-538
                                                                                             idnlgrey
                                                                                              1-539
1   Functions
Report
          Summary report that contains information about the estimation options and results when the model is
          estimated using the nlgreyest command. Use Report to query a model for how it was estimated,
          including:
          • Estimation method
          • Estimation options
          • Search termination conditions
          • Estimation data fit
The contents of Report are irrelevant if the model was created by construction.
1-540
                                                                                               idnlgrey
nlgr = idnlgrey('dcmotor_m',[2,1,2],[1;0.28],[0;0],0,'Name','DC-motor');
nlgr.Report.OptionsUsed
ans =
[]
If you use nlgreyest to estimate the model, the fields of Report contain information on the
estimation data, options, and results.
load(fullfile(matlabroot,'toolbox','ident','iddemos','data','dcmotordata'));
z = iddata(y,u,0.1,'Name','DC-motor');
nlgr = idnlgrey('dcmotor_m',[2,1,2],[1;0.28],[0;0],0,'Name','DC-motor');
nlgr = nlgreyest(z,nlgr);
nlgr.Report.OptionsUsed
For more information on this property and how to use it, see “Output Arguments” on page 1-788 in
the nlgreyest reference page and “Estimation Report”.
TimeVariable
Independent variable for the inputs, outputs, and—when available—internal states, specified as a
character vector.
Default: 't'
NoiseVariance
Ts
Sample time. Ts is a positive scalar representing the sampling period. This value is expressed in the
unit specified by the TimeUnit property of the model. For a continuous time model, Ts is equal to 0
(default).
Default: 0
                                                                                                1-541
1   Functions
TimeUnit
          Units for the time variable, the sample time Ts, and any time delays in the model, specified as one of
          the following values:
          • 'nanoseconds'
          • 'microseconds'
          • 'milliseconds'
          • 'seconds'
          • 'minutes'
          • 'hours'
          • 'days'
          • 'weeks'
          • 'months'
          • 'years'
          Changing this property has no effect on other properties, and therefore changes the overall system
          behavior. Use chgTimeUnit to convert between time units without modifying system behavior.
Default: 'seconds'
InputName
          Alternatively, use automatic vector expansion to assign input names for multi-input models. For
          example, if sys is a two-input model, enter:
          sys.InputName = 'controls';
          When you estimate a model using an iddata object, data, the software automatically sets
          InputName to data.InputName.
          You can use the shorthand notation u to refer to the InputName property. For example, sys.u is
          equivalent to sys.InputName.
InputUnit
1-542
                                                                                              idnlgrey
Use InputUnit to keep track of input signal units. InputUnit has no effect on system behavior.
InputGroup
Input channel groups. The InputGroup property lets you assign the input channels of MIMO systems
into groups and refer to each group by name. Specify input groups as a structure. In this structure,
field names are the group names, and field values are the input channels belonging to each group.
For example:
sys.InputGroup.controls = [1 2];
sys.InputGroup.noise = [3 5];
creates input groups named controls and noise that include input channels 1, 2 and 3, 5,
respectively. You can then extract the subsystem from the controls inputs to all outputs using:
sys(:,'controls')
OutputName
Alternatively, use automatic vector expansion to assign output names for multi-output models. For
example, if sys is a two-output model, enter:
sys.OutputName = 'measurements';
When you estimate a model using an iddata object, data, the software automatically sets
OutputName to data.OutputName.
You can use the shorthand notation y to refer to the OutputName property. For example, sys.y is
equivalent to sys.OutputName.
OutputUnit
                                                                                              1-543
1   Functions
Use OutputUnit to keep track of output signal units. OutputUnit has no effect on system behavior.
OutputGroup
          Output channel groups. The OutputGroup property lets you assign the output channels of MIMO
          systems into groups and refer to each group by name. Specify output groups as a structure. In this
          structure, field names are the group names, and field values are the output channels belonging to
          each group. For example:
          sys.OutputGroup.temperature = [1];
          sys.InputGroup.measurement = [3 5];
          creates output groups named temperature and measurement that include output channels 1, and
          3, 5, respectively. You can then extract the subsystem from all inputs to the measurement outputs
          using:
sys('measurement',:)
Name
Default: ''
Notes
          Any text that you want to associate with the system, stored as a string or a cell array of character
          vectors. The property stores whichever data type you provide. For instance, if sys1 and sys2 are
          dynamic system models, you can set their Notes properties as follows:
ans =
ans =
1-544
                                                                                              idnlgrey
UserData
Any type of data you want to associate with system, specified as any MATLAB data type.
Default: []
Output Arguments
sys — Nonlinear grey-box model
idnlgrey object
More About
Definition of idnlgrey States
The states of an idnlgrey model are defined explicitly in the function or MEX-file storing the model
structure. States are required for simulation and prediction of nonlinear grey-box models. Use
findstates to search for state values for simulation and prediction with sim, predict, and
compare.
Note The initial values of the states are configured by the InitialStates property of the
idnlgrey model.
See Also
get | getinit | getpar | nlgreyest | pem | set | setinit | setpar
Topics
“Represent Nonlinear Dynamics Using MATLAB File for Grey-Box Estimation”
“Creating IDNLGREY Model Files”
“Estimate Nonlinear Grey-Box Models”
Introduced in R2007a
                                                                                               1-545
1   Functions
          idnlhw
          Hammerstein-Wiener model
          Syntax
          sys   =   idnlhw(Orders)
          sys   =   idnlhw(Orders,InputNL,OutputNL)
          sys   =   idnlhw(Orders,InputNL,OutputNL,Name,Value)
          sys   =   idnlhw(LinModel)
          sys   =   idnlhw(LinModel,InputNL,OutputNL)
          sys   =   idnlhw(LinModel,InputNL,OutputNL,Name,Value)
          Description
          sys = idnlhw(Orders) creates a Hammerstein-Wiener model with the specified orders, and using
          piecewise linear functions as input and output nonlinearity estimators.
          sys = idnlhw(LinModel) uses a linear model LinModel to specify the model orders and default
          piecewise linear functions for the input and output nonlinearity estimators.
          Object Description
          idnlhw represents a Hammerstein-Wiener model. The Hammerstein-Wiener structure on page 1-
          556 represents a linear model with input-output nonlinearities.
Use the nlhw command to both construct an idnlhw object and estimate the model parameters.
          You can also use the idnlhw constructor to create the Hammerstein-Wiener model and then estimate
          the model parameters using nlhw.
Examples
1-546
                                                                                 idnlhw
m = idnlhw([2 2 1]);
m = idnlhw([2 2 1],'sigmoidnet','deadzone');
m = idnlhw([2 2 1],'sig','dead');
m = idnlhw([2 2 1],sigmoidnet('num',5),deadzone([-1,2]),'InputName','Volts','OutputName','Time');
m = idnlhw([2 2 1],[],'saturation');
load iddata1;
m = nlhw(z1,m);
B = [0.8 1];
F = [1 -1.2 0.5];
LinearModel = idpoly(1,B,1,1,F,'Ts',0.1);
m1 = idnlhw(LinearModel,'saturation',[],'InputName','Control');
Input Arguments
Orders — Order and delays of the linear subsystem transfer function
[nb nf nk] vector of positive integers | [nb nf nk] vector of matrices
                                                                                 1-547
1   Functions
Order and delays of the linear subsystem transfer function, specified as a [nb nf nk] vector.
Dimensions of Orders:
                nb is the number of zeros plus 1, nf is the number of poles, and nk is the input delay.
          • For a MIMO transfer function with nu inputs and ny outputs, Orders is a vector of matrices.
                nb, nf, and nk are ny-by-nu matrices whose i-jth entry specifies the orders and delay of the
                transfer function from the jth input to the ith output.
          Specifying a character vector, for example 'sigmoidnet', creates a nonlinearity estimator object
          with default settings. Use object representation instead to configure the properties of a nonlinearity
          estimator.
          InputNL = wavenet;
          InputNL.NumberOfUnits = 10;
          Alternatively, use the associated input nonlinearity estimator function with Name-Value pair
          arguments.
InputNL = wavenet('NumberOfUnits',10);
          For nu input channels, you can specify nonlinear estimators individually for each input channel by
          setting InputNL to an nu-by-1 array of nonlinearity estimators.
To specify the same nonlinearity for all inputs, specify a single input nonlinearity estimator.
1-548
                                                                                                         idnlhw
        Specifying a character vector creates a nonlinearity estimator object with default settings. Use object
        representation instead to configure the properties of a nonlinearity estimator.
        OutputNL = sigmoidnet;
        OutputNL.NumberOfUnits = 10;
        Alternatively, use the associated input nonlinearity estimator function with Name-Value pair
        arguments.
OutputNL = sigmoidnet('NumberOfUnits',10);
        For ny output channels, you can specify nonlinear estimators individually for each output channel by
        setting OutputNL to an ny-by-1 array of nonlinearity estimators. To specify the same nonlinearity for
        all outputs, specify a single output nonlinearity estimator.
Discrete-time linear model used to specify the linear subsystem, specified as one of the following:
        Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
        Value is the corresponding value. Name must appear inside quotes. You can specify several name and
        value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
        Use Name,Value arguments to specify additional properties on page 1-550 of idnlhw models
        during model creation. For example, m = idnlhw([2 3
        1],'pwlinear','wavenet','InputName','Volts','Ts',0.1) creates an idnlhw model
        object with input nonlinearity estimator 'pwlinear', output nonlinearity estimator 'wavenet',
        input name Volts, and a sample time of 0.1 seconds.
                                                                                                         1-549
1   Functions
          Properties
          idnlhw object properties include:
nb, nf, nk
          Model orders and delays of the linear subsystem transfer function, where nb is the number of zeros
          plus 1, nf is the number of poles, and nk is the input delay.
          For a MIMO transfer function with nu inputs and ny outputs, nb, nf, and nk are ny-by-nu matrices
          whose i-jth entry specifies the orders and delay of the transfer function from the jth input to the ith
          output.
          B polynomial of the linear block in the model structure on page 1-556, specified as a cell array of ny-
          by-nu elements, where ny is the number of outputs and nu is the number of inputs. An element
          B{i,j} is a row vector representing the numerator polynomial for the jth input to ith output
          transfer function. The element contains nk leading zeros, where nk is the number of input delays.
          F polynomial of the linear block in the model structure on page 1-556, specified as a cell array of ny-
          by-nu elements, where ny is the number of outputs and nu is the number of inputs. An element
          F{i,j} is a row vector representing the denominator polynomial for the jth input to ith output
          transfer function.
InputNonlinearity
          Specifying a character vector creates a nonlinearity estimator object with default settings. Use object
          representation instead to configure the properties of a nonlinearity estimator.
          InputNonlinearity = wavenet;
          InputNonlinearity.NumberOfUnits = 10;
          Alternatively, use the associated input nonlinearity estimator function with Name-Value pair
          arguments.
InputNonlinearity = wavenet('NumberOfUnits',10);
1-550
                                                                                                         idnlhw
        For nu input channels, you can specify nonlinear estimators individually for each input channel by
        setting InputNL to an nu-by-1 array of nonlinearity estimators. To specify the same nonlinearity for
        all inputs, specify a single input nonlinearity estimator.
Default: 'pwlinear'
OutputNonlinearity
        Specifying a character vector creates a nonlinearity estimator object with default settings. Use object
        representation instead to configure the properties of a nonlinearity estimator.
        OutputNonlinearity = sigmoidnet;
        OutputNonlinearity.NumberOfUnits = 10;
        Alternatively, use the associated input nonlinearity estimator function with Name-Value pair
        arguments.
OutputNonlinearity = sigmoidnet('NumberOfUnits',10);
        For ny output channels, you can specify nonlinear estimators individually for each output channel by
        setting OutputNL to an ny-by-1 array of nonlinearity estimators. To specify the same nonlinearity for
        all outputs, specify a single output nonlinearity estimator.
Default: 'pwlinear'
LinearModel
        The linear model in the linear block of the model structure, represented as an idpoly object. This
        property is read only.
Report
        Summary report that contains information about the estimation options and results when the model is
        estimated using the nlhw command. Use Report to query a model for how it was estimated,
        including:
        • Estimation method
        • Estimation options
        • Search termination conditions
                                                                                                         1-551
1   Functions
The contents of Report are irrelevant if the model was created by construction.
          m = idnlhw([2 2 1]);
          m.Report.OptionsUsed
ans =
[]
          If you use nlhw to estimate the model, the fields of Report contain information on the estimation
          data, options, and results.
          load iddata1;
          m = nlhw(z1,[2 2 1],[],'pwlinear');
          m.Report.OptionsUsed
                InitialCondition:   'zero'
                         Display:   'off'
                  Regularization:   [1x1 struct]
                    SearchMethod:   'auto'
                    SearchOption:   [1x1 idoptions.search.identsolver]
                    OutputWeight:   'noise'
                        Advanced:   [1x1 struct]
          For more information on this property and how to use it, see “Output Arguments” on page 1-809 in
          the nlhw reference page and “Estimation Report”.
TimeVariable
          Independent variable for the inputs, outputs, and—when available—internal states, specified as a
          character vector.
Default: 't'
NoiseVariance
Ts
          Sample time. Ts is a positive scalar representing the sampling period. This value is expressed in the
          unit specified by the TimeUnit property of the model.
Default: 1
1-552
                                                                                                  idnlhw
TimeUnit
Units for the time variable, the sample time Ts, and any time delays in the model, specified as one of
the following values:
• 'nanoseconds'
• 'microseconds'
• 'milliseconds'
• 'seconds'
• 'minutes'
• 'hours'
• 'days'
• 'weeks'
• 'months'
• 'years'
Changing this property has no effect on other properties, and therefore changes the overall system
behavior. Use chgTimeUnit to convert between time units without modifying system behavior.
Default: 'seconds'
InputName
Alternatively, use automatic vector expansion to assign input names for multi-input models. For
example, if sys is a two-input model, enter:
sys.InputName = 'controls';
When you estimate a model using an iddata object, data, the software automatically sets
InputName to data.InputName.
You can use the shorthand notation u to refer to the InputName property. For example, sys.u is
equivalent to sys.InputName.
InputUnit
                                                                                                  1-553
1   Functions
Use InputUnit to keep track of input signal units. InputUnit has no effect on system behavior.
InputGroup
          Input channel groups. The InputGroup property lets you assign the input channels of MIMO systems
          into groups and refer to each group by name. Specify input groups as a structure. In this structure,
          field names are the group names, and field values are the input channels belonging to each group.
          For example:
          sys.InputGroup.controls = [1 2];
          sys.InputGroup.noise = [3 5];
          creates input groups named controls and noise that include input channels 1, 2 and 3, 5,
          respectively. You can then extract the subsystem from the controls inputs to all outputs using:
sys(:,'controls')
OutputName
          Alternatively, use automatic vector expansion to assign output names for multi-output models. For
          example, if sys is a two-output model, enter:
sys.OutputName = 'measurements';
          When you estimate a model using an iddata object, data, the software automatically sets
          OutputName to data.OutputName.
          You can use the shorthand notation y to refer to the OutputName property. For example, sys.y is
          equivalent to sys.OutputName.
OutputUnit
1-554
                                                                                                  idnlhw
Use OutputUnit to keep track of output signal units. OutputUnit has no effect on system behavior.
OutputGroup
Output channel groups. The OutputGroup property lets you assign the output channels of MIMO
systems into groups and refer to each group by name. Specify output groups as a structure. In this
structure, field names are the group names, and field values are the output channels belonging to
each group. For example:
sys.OutputGroup.temperature = [1];
sys.InputGroup.measurement = [3 5];
creates output groups named temperature and measurement that include output channels 1, and
3, 5, respectively. You can then extract the subsystem from all inputs to the measurement outputs
using:
sys('measurement',:)
Name
Default: ''
Notes
Any text that you want to associate with the system, stored as a string or a cell array of character
vectors. The property stores whichever data type you provide. For instance, if sys1 and sys2 are
dynamic system models, you can set their Notes properties as follows:
ans =
ans =
                                                                                                  1-555
1   Functions
UserData
Any type of data you want to associate with system, specified as any MATLAB data type.
Default: []
          Output Arguments
          sys — Hammerstein-Wiener model
          idnlhw object
          Hammerstein-Wiener model, returned as an idnlhw object. This model is created using the specified
          model orders and delays, input and output nonlinearity estimators, and properties.
          More About
          Hammerstein-Wiener Model Structure
Where,
                w(t), an internal variable, is the output of the Input Nonlinearity block and has the same
                dimension as u(t).
          • B/F is a linear transfer function that transforms w(t) as x(t) = (B/F)w(t).
x(t), an internal variable, is the output of the Linear block and has the same dimension as y(t).
                B and F are similar to polynomials in a linear Output-Error model. For more information about
                Output-Error models, see “What Are Polynomial Models?”.
For ny outputs and nu inputs, the linear block is a transfer function matrix containing entries:
                 B j, i(q)
                 F j, i(q)
          Because f acts on the input port of the linear block, this function is called the input nonlinearity.
          Similarly, because h acts on the output port of the linear block, this function is called the output
          nonlinearity. If your system contains several inputs and outputs, you must define the functions f and h
          for each input and output signal. You do not have to include both the input and the output
          nonlinearity in the model structure. When a model contains only the input nonlinearity f, it is called a
          Hammerstein model. Similarly, when the model contains only the output nonlinearity h, it is called a
          Wiener model.
1-556
                                                                                                  idnlhw
    The input nonlinearity is a static (memoryless) function, where the value of the output a given
    time t depends only on the input value at time t.
    You can configure the input nonlinearity as a sigmoid network, wavelet network, saturation, dead
    zone, piecewise linear function, one-dimensional polynomial, or a custom network. You can also
    remove the input nonlinearity.
2   Compute the output of the linear block using w(t) and initial conditions: x(t) = (B/F)w(t).
    You can configure the linear block by specifying the orders of numerator B and denominator F.
3   Compute the model output by transforming the output of the linear block x(t) using the nonlinear
    function h as y(t) = h(x(t)).
    Similar to the input nonlinearity, the output nonlinearity is a static function. You can configure
    the output nonlinearity in the same way as the input nonlinearity. You can also remove the output
    nonlinearity, such that y(t) = x(t).
Resulting models are idnlhw objects that store all model data, including model parameters and
nonlinearity estimators. For more information about these objects, see “Nonlinear Model Structures”.
The states of a Hammerstein-Wiener model correspond to the states of the linear block in the model
structure. The linear block contains all the dynamic elements of the model. If the linear block is not a
state-space structure, the states are defined as those of model Mss, where Mss =
idss(Model.LinearModel) and Model is the idnlhw object.
States are required for simulation, prediction, and linearization of Hammerstein-Wiener models. To
specify the initial states:
• Use findstates to search for state values for simulation and prediction with sim, predict, and
  compare.
• Use findop when linearizing the model with linearize.
• Alternatively, specify the states manually.
See Also
customnet | findop | linear | linearize | nlhw | pem | poly1d | saturation | saturation |
sigmoidnet | wavenet
Topics
“Estimate Multiple Hammerstein-Wiener Models”
“Estimate Hammerstein-Wiener Models Initialized Using Linear OE Models”
“Identifying Hammerstein-Wiener Models”
“Initialize Hammerstein-Wiener Estimation Using Linear Model”
Introduced in R2007a
                                                                                                  1-557
1   Functions
          idpar
          Create parameter for initial states and input level estimation
          Syntax
          p = idpar(paramvalue)
          p = idpar(paramname,paramvalue)
          Description
          p = idpar(paramvalue) creates an estimable parameter with initial value paramvalue. The
          parameter, p, is either scalar or array-valued, with the same dimensions as paramvalue. You can
          configure attributes of the parameter, such as which elements are fixed and which are estimated, and
          lower and upper bounds.
          Input Arguments
          paramvalue
          paramvalue is a numeric scalar or array that determines both the dimensions and initial values of
          the estimable parameter p. For example, p = idpar(eye(3)) creates a 3-by-3 parameter whose
          initial value is the identity matrix.
          • A column vector of length Nx, the number of states to estimate, if you are using p for initial state
            estimation.
          • An Nx-by-Ne array, if you are using p for initial state estimation with multi-experiment data. Ne is
            the number of experiments.
          • A column vector of length Nu, the number of inputs to estimate, if you are using p for input level
            estimation.
          • An Nu-by-Ne array, if you are using p for input level estimation with multi-experiment data.
paramname
          Name property of p, specified as a character vector. For example, you can assign 'x0' as the name of
          a parameter created for initial state estimation.
          The Name property is not used in state estimation or input level estimation. You can optionally assign
          a name for convenience.
Default: 'par'
1-558
                                                                                                 idpar
Output Arguments
p
p can be either scalar- or array-valued. p takes its dimensions and initial value from paramvalue.
    The dimension and initial value of p.Value are taken from paramvalue when p is created.
• Minimum — Lower bound for the parameter value. When you use p in state estimation or input
  value estimation, the estimated value of the parameter does not drop below p.Minimum.
    • Specify lower bounds on individual array elements. For example, p.Minimum([1 4]) = -5 .
    • Use scalar expansion to set the lower bound for all array elements. For example,
      p.Minimum = -5
    Default: -Inf
• Maximum — Upper bound for the parameter value. When you use p in state estimation or input
  value estimation, the estimated value of the parameter does not exceed p.Maximum.
    • Specify upper bounds on individual array elements. For example, p.Maximum([1 4]) = 5 .
    • Use scalar expansion to set the upper bound for all array elements. For example,
      p.Maximum = 5
    Default: Inf
• Free — Boolean specifying whether the parameter is a free estimation variable.
    The dimensions of p.Free must match the dimensions of p.Value. By default, all values are free
    (p.Free = true).
    If you want to estimate p.Value(k) , set p.Free(k) = true. To fix p.Value(k), set
    p.Free(k) = false. Doing so allows you to control which states or input values are estimated
    and which are not.
                                                                                               1-559
1   Functions
                Default: 1
          • Info — Structure array for storing parameter units and labels. The structure has Label and
            Unit fields.
                Use these fields for your convenience, to store parameter units and labels. For example,
                p.Info(1,1).Unit = 'rad/m'; p.Info(1,1).Label = 'engine speed'.
                This property is read-only. It is set to the paramname input argument when you create the
                parameter.
Default: ''
Examples
          Create and configure a parameter for estimating the initial state values of a 4-state system. Fix the
          first state value to 1. Limit the second and third states to values between 0 and 1.
          The column vector paramvalue specifies an initial value of 1 for the first state. paramvalue further
          specifies unknown values for the remaining 3 states.
Setting p.Free(1) to false fixes p.Value(1) to 1. Estimation using p does not alter that value.
          Setting p.Minimum and p.Maximum for the second and third entries in p limits the range that those
          values can take when p is used in estimation.
          You can now use p in initial state estimation, such as with the findstates command. For example,
          use opt = findstatesOptions('InitialState',p) to create a findstates options set that
          uses p. Then, call findstates with that options set.
          Tips
          Use idpar to create estimable parameters for:
          • Initial state estimation for state-space model estimation (ssest), prediction (predict), and
            forecasting (forecast)
1-560
                                                                                                     idpar
Specifying estimable state values or input levels gives you explicit control over the behavior of
individual state values during estimation.
See Also
findstates | findstatesOptions | forecast | pem | predict | ssest
Introduced in R2012a
                                                                                                    1-561
1   Functions
          idpoly
          Polynomial model with identifiable parameters
          Syntax
          sys = idpoly(A,B,C,D,F,NoiseVariance,Ts)
          sys = idpoly(A,B,C,D,F,NoiseVariance,Ts,Name,Value)
          sys = idpoly(A)
          sys = idpoly(A,[],C,D,[],NoiseVariance,Ts)
          sys = idpoly(A,[],C,D,[],NoiseVariance,Ts,Name,Value)
          sys = idpoly(sys0)
          sys = idpoly(sys0,'split')
          Description
          sys = idpoly(A,B,C,D,F,NoiseVariance,Ts) creates a polynomial model with identifiable
          coefficients. A, B, C, D, and F specify the initial values of the coefficients. NoiseVariance specifies
          the initial value of the variance of the white noise source. Ts is the model sample time.
          sys = idpoly(A) creates a time-series model with only an autoregressive term. In this case, sys
          represents the AR model given by A(q–1) y(t) = e(t). The noise e(t) has variance 1. A specifies the
          initial values of the estimable coefficients.
A q−1 y t = C q−1 e t .
sys = idpoly(sys0) converts any dynamic system model, sys0, to idpoly model form.
          sys = idpoly(sys0,'split') converts sys0 to idpoly model form, and treats the last Ny input
          channels of sys0 as noise channels in the returned model. sys0 must be a numeric (nonidentified)
          tf, zpk, or ss model object. Also, sys0 must have at least as many inputs as outputs.
          Object Description
          An idpoly model represents a system as a continuous-time or discrete-time polynomial model with
          identifiable (estimable) coefficients.
1-562
                                                                                                   idpoly
A polynomial model of a system with input vector u, output vector y, and disturbance e takes the
following form in discrete time:
                 B(q)        C(q)
    A(q)y(t) =        u(t) +      e(t)
                 F(q)        D(q)
                 B(s)        C(s)
    A(s)Y(s) =        U(s) +      E(s)
                 F(s)        D(s)
U(s) are the Laplace transformed inputs to sys. Y(s) are the Laplace transformed outputs. E(s) is the
Laplace transform of the disturbance.
For idpoly models, the coefficients of the polynomials A, B, C, D, and F can be estimable
parameters. The idpoly model stores the values of these matrix elements in the A, B, C, D, and F
properties of the model.
Time-series models are special cases of polynomial models for systems without measured inputs. For
AR models, B and F are empty, and C and D are 1 for all outputs. For ARMA models, B and F are
empty, while D is 1.
• Estimate the idpoly model based on output or input-output measurements of a system, using
  commands such as polyest, arx, armax, oe, bj, iv4, or ivar. These commands estimate the
  values of the free polynomial coefficients. The estimated values are stored in the A, B, C, D, and F
  properties of the resulting idpoly model. The Report property of the resulting model stores
  information about the estimation, such as handling of initial conditions and options used in
  estimation.
   When you obtain an idpoly model by estimation, you can extract estimated coefficients and their
   uncertainties from the model using commands such as polydata, getpar, or getcov.
• Create an idpoly model using the idpoly command. You can create an idpoly model to
  configure an initial parameterization for estimation of a polynomial model to fit measured
  response data. When you do so, you can specify constraints on the polynomial coefficients. For
  example, you can fix the values of some coefficients, or specify minimum or maximum values for
  the free coefficients. You can then use the configured model as an input argument to polyest to
  estimate parameter values with those constraints.
• Convert an existing dynamic system model to an idpoly model using the idpoly command.
Examples
Create an idpoly model representing the one-input, two-output ARMAX model described by the
following equations:
                                                                                                 1-563
1   Functions
          y1 and y2 are the two outputs, and u is the input. e1 and e2 are the white noise disturbances on the
          outputs y1 and y2 respectively.
          To create the idpoly model, define the A, B, and C polynomials that describe the relationships
          between the outputs, inputs, and noise values. (Because there are no denominator terms in the
          system equations, B and F are 1.)
          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];
          You can read the values of each entry in the A cell array from the left side of the equations describing
          the system. For example, A{1,1} describes the polynomial that gives the dependence of y1 on itself.
          This polynomial is A11 = 1 + 0 . 5q−1, because each factor of q−1 corresponds to a unit time
          decrement. Therefore, A{1,1} = [1 0.5], giving the coefficients of A11 in increasing exponents of
          q−1.
          Similarly, A{1,2} describes the polynomial that gives the dependence of y1 on y2. From the
          equations, A12 = 0 + 0 . 9q−1 + 0 . 1q−2. Thus, A{1,2} = [0 0.9 0.1].
          B = cell(2,1);
          B{1,1} = [1 5 2];
          B{2,1} = [0 0 10];
          B describes the polynomials that give the dependence of the outputs y1 and y2 on the input u. From
          the equations, B11 = 1 + 5q−1 + 2q−2. Therefore, B{1,1} = [1 5 2].
Similarly, from the equations, B21 = 0 + 0q−1 + 10q−2. Therefore, B{2,1} = [0 0 10].
          C = cell(2,1);
          C{1,1} = [1 0.01];
          C{2,1} = [1 0.1 0.02];
          C describes the polynomials that give the dependence of the outputs y1 and y2 on the noise terms e1
          and e2. The entries of C can be read from the equations similarly to those of A and B.
sys = idpoly(A,B,C)
          sys =
          Discrete-time ARMAX model:
            Model for output number 1: A(z)y_1(t) = - A_i(z)y_i(t) + B(z)u(t) + C(z)e_1(t)
              A(z) = 1 + 0.5 z^-1
1-564
                                                                                                    idpoly
B(z) = 10 z^-2
Parameterization:
   Polynomial orders:   na=[1 2;0 2]   nb=[3;1]   nc=[1;2]
   nk=[0;2]
   Number of free coefficients: 12
   Use "polydata", "getpvec", "getcov" for parameters and their uncertainties.
Status:
Created by direct construction or transformation. Not estimated.
The display shows all the polynomials and allows you to verify them. The display also states that there
are 12 free coefficients. Leading terms of diagonal entries in A are always fixed to 1. Leading terms of
all other entries in A are always fixed to 0.
You can use sys to specify an initial parameterization for estimation with such commands as
polyest or armax.
Input Arguments
A,B,C,D,F
For SISO models, specify the initial values of the polynomial coefficients as row vectors. Specify the
coefficients in order of:
The leading coefficients of A, C, D, and F must be 1. Use NaN for any coefficient whose initial value is
not known.
For MIMO models with Ny outputs and Nu inputs, A, B, C, D, and F are cell arrays of row vectors. Each
entry in the cell array contains the coefficients of a particular polynomial that relates input, output,
and noise values.
                                                                                                   1-565
1   Functions
          The leading coefficients of the diagonal entries of A (A{i,i},i=1:Ny) must be 1. The leading
          coefficients of the off-diagonal entries of A must be zero, for causality. The leading coefficients of all
          entries of C, D, and F , must be 1.
          Use [] for any polynomial that is not present in the wanted model structure. For example, to create
          an ARX model, use [] for C, D, and F. For an ARMA time series, use [] for B and F.
Ts
          Sample time. For continuous-time models, Ts = 0. For discrete-time models, Ts is a positive scalar
          representing the sample time expressed in the unit specified by the TimeUnit property of the model.
          To denote a discrete-time model with unspecified sample time, set Ts = -1.
NoiseVariance
          An identified model includes a white, Gaussian noise component e(t). NoiseVariance is the variance
          of this noise component. Typically, a model estimation function (such as polyest) determines this
          variance. Use this input to specify an initial value for the noise variance when you create an idpoly
          model.
          For SISO models, NoiseVariance is a scalar. For MIMO models, NoiseVariance is a Ny-by-Ny
          matrix, where Ny is the number of outputs in the system.
sys0
Dynamic system.
          When sys0 is an identified model, its estimated parameter covariance is lost during conversion. If
          you want to translate the estimated parameter covariance during the conversion, use
          translatecov.
          For the syntax sys = idpoly(sys0,'split'), sys0 must be a numeric (non-identified) tf, zpk,
          or ss model object. Also, sys0 must have at least as many inputs as outputs. Finally, the subsystem
          sys0(:,Ny+1:Nu) must be biproper.
1-566
                                                                                                       idpoly
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Use Name,Value arguments to specify additional properties on page 1-567 of idpoly models
during model creation. For example, idpoly(A,B,C,D,F,1,0,'InputName','Voltage') creates
an idpoly model with the InputName property set to Voltage.
Properties
idpoly object properties include:
A,B,C,D,F
If you create an idpoly model sys using the idpoly command, sys.A, sys.B, sys.C, sys.D, and
sys.F contain the initial coefficient values that you specify with the A, B, C, D, and F input
arguments, respectively.
If you obtain an idpoly model by identification, then sys.A, sys.B, sys.C, sys.D, and sys.F
contain the estimated values of the coefficients.
For an idpoly model sys, each property sys.A, sys.B, sys.C, sys.D, and sys.F is an alias to the
corresponding Value entry in the Structure property of sys. For example, sys.A is an alias to the
value of the property sys.Structure.A.Value.
For SISO polynomial models, the values of the numerator coefficients are stored as a row vector in
order of:
The leading coefficients of A, C, and D are fixed to 1. Any coefficient whose initial value is not known
is stored as NaN.
For MIMO models with Ny outputs and Nu inputs, A, B, C, D, and F are cell arrays of row vectors. Each
entry in the cell array contains the coefficients of a particular polynomial that relates input, output,
and noise values.
The leading coefficients of the diagonal entries of A (A{i,i}, i=1:Ny) are fixed to 1. The leading
coefficients of the off-diagonal entries of A are fixed to zero. The leading coefficients of all entries of
C, D, and F , are fixed to 1.
                                                                                                      1-567
1   Functions
Variable
          The value of Variable is reflected in the display, and also affects the interpretation of the A, B, C, D,
          and F coefficient vectors for discrete-time models. For Variable = 'z^-1' or 'q^-1', the
          coefficient vectors are ordered as ascending powers of the variable.
IODelay
          Transport delays. IODelay is a numeric array specifying a separate transport delay for each input/
          output pair.
          If you create an idpoly model sys using the idpoly command, sys.IODelay contains the initial
          values of the transport delay that you specify with a Name,Value argument pair.
          For an idpoly model sys, the property sys.IODelay is an alias to the value of the property
          sys.Structure.IODelay.Value.
          For continuous-time systems, transport delays are expressed in the time unit stored in the TimeUnit
          property. For discrete-time systems, transport delays are expressed as integers denoting delay of a
          multiple of the sample time Ts.
          For a MIMO system with Ny outputs and Nu inputs, set IODelay is a Ny-by-Nu array, where each
          entry is a numerical value representing the transport delay for the corresponding input/output pair.
          You can set IODelay to a scalar value to apply the same delay to all input/output pairs.
IntegrateNoise
          IntegrateNoise(i) = true indicates that the noise channel for the ith output contains an
          integrator. In this case, the corresponding D polynomial contains an additional term which is not
          represented in the property sys.D. This integrator term is equal to [1 0] for continuous-time
          systems, and equal to [1 -1] for discrete-time systems.
Structure
1-568
                                                                                               idpoly
   For SISO models, each property sys.A, sys.B, sys.C, sys.D, sys.F, and sys.IODelay is an
   alias to the corresponding Value entry in the Structure property of sys. For example, sys.A is
   an alias to the value of the property sys.Structure.A.Value
   For fixed values, such as the leading coefficients in sys.Structure.B.Value, the corresponding
   value of Free is always false.
• Scale — Scale of the parameter’s value. Scale is not used in estimation.
• Info — Structure array for storing parameter units and labels. The structure has Label and
  Unit fields.
Specify parameter units and labels as character vectors. For example, 'Time'.
For a MIMO model with Ny outputs and Nu inputs, the dimensions of the Structure elements are as
follows:
• sys.Structure.A — Ny-by-Ny
• sys.Structure.B — Ny-by-Nu
• sys.Structure.C — Ny-by-1
• sys.Structure.D — Ny-by-1
• sys.Structure.F — Ny-by-Nu
                                                                                            1-569
1   Functions
NoiseVariance
          An identified model includes a white Gaussian noise component e(t). NoiseVariance is the variance
          of this noise component. Typically, the model estimation function (such as arx) determines this
          variance.
          For SISO models, NoiseVariance is a scalar. For MIMO models, NoiseVariance is a Ny-by-Ny
          matrix, where Ny is the number of outputs in the system.
Report
          Summary report that contains information about the estimation options and results when the
          polynomial model is obtained using estimation commands, such as polyest, armax, oe, and bj. Use
          Report to query a model for how it was estimated, including its:
          • Estimation method
          • Estimation options
          • Search termination conditions
          • Estimation data fit and other quality metrics
The contents of Report are irrelevant if the model was created by construction.
ans =
[]
          If you obtain the polynomial model using estimation commands, the fields of Report contain
          information on the estimation data, options, and results.
                  InitialCondition:   'auto'
                             Focus:   'prediction'
                EstimateCovariance:   1
                           Display:   'off'
                       InputOffset:   []
                      OutputOffset:   []
                    Regularization:   [1x1 struct]
                      SearchMethod:   'auto'
                     SearchOptions:   [1x1 idoptions.search.identsolver]
                          Advanced:   [1x1 struct]
          For more information on this property and how to use it, see the Output Arguments section of the
          corresponding estimation command reference page and “Estimation Report”.
1-570
                                                                                                   idpoly
InputDelay
Input delay for each input channel, specified as a scalar value or numeric vector. For continuous-time
systems, specify input delays in the time unit stored in the TimeUnit property. For discrete-time
systems, specify input delays in integer multiples of the sample time Ts. For example, InputDelay =
3 means a delay of three sample times.
For a system with Nu inputs, set InputDelay to an Nu-by-1 vector. Each entry of this vector is a
numerical value that represents the input delay for the corresponding input channel.
You can also set InputDelay to a scalar value to apply the same delay to all channels.
Default: 0
OutputDelay
Output delays.
Ts
Sample time. For continuous-time models, Ts = 0. For discrete-time models, Ts is a positive scalar
representing the sample time expressed in the unit specified by the TimeUnit property of the model.
To denote a discrete-time model with unspecified sample time, set Ts = -1.
Changing this property does not discretize or resample the model. Use c2d and d2c to convert
between continuous- and discrete-time representations. Use d2d to change the sample time of a
discrete-time system.
TimeUnit
Units for the time variable, the sample time Ts, and any time delays in the model, specified as one of
the following values:
• 'nanoseconds'
• 'microseconds'
• 'milliseconds'
• 'seconds'
• 'minutes'
• 'hours'
• 'days'
• 'weeks'
• 'months'
• 'years'
Changing this property has no effect on other properties, and therefore changes the overall system
behavior. Use chgTimeUnit to convert between time units without modifying system behavior.
Default: 'seconds'
                                                                                                 1-571
1   Functions
InputName
          Alternatively, use automatic vector expansion to assign input names for multi-input models. For
          example, if sys is a two-input model, enter:
sys.InputName = 'controls';
          When you estimate a model using an iddata object, data, the software automatically sets
          InputName to data.InputName.
          You can use the shorthand notation u to refer to the InputName property. For example, sys.u is
          equivalent to sys.InputName.
InputUnit
Use InputUnit to keep track of input signal units. InputUnit has no effect on system behavior.
InputGroup
          Input channel groups. The InputGroup property lets you assign the input channels of MIMO systems
          into groups and refer to each group by name. Specify input groups as a structure. In this structure,
          field names are the group names, and field values are the input channels belonging to each group.
          For example:
          sys.InputGroup.controls = [1 2];
          sys.InputGroup.noise = [3 5];
          creates input groups named controls and noise that include input channels 1, 2 and 3, 5,
          respectively. You can then extract the subsystem from the controls inputs to all outputs using:
sys(:,'controls')
1-572
                                                                                                idpoly
OutputName
Alternatively, use automatic vector expansion to assign output names for multi-output models. For
example, if sys is a two-output model, enter:
sys.OutputName = 'measurements';
When you estimate a model using an iddata object, data, the software automatically sets
OutputName to data.OutputName.
You can use the shorthand notation y to refer to the OutputName property. For example, sys.y is
equivalent to sys.OutputName.
OutputUnit
Use OutputUnit to keep track of output signal units. OutputUnit has no effect on system behavior.
OutputGroup
Output channel groups. The OutputGroup property lets you assign the output channels of MIMO
systems into groups and refer to each group by name. Specify output groups as a structure. In this
structure, field names are the group names, and field values are the output channels belonging to
each group. For example:
sys.OutputGroup.temperature = [1];
sys.InputGroup.measurement = [3 5];
creates output groups named temperature and measurement that include output channels 1, and
3, 5, respectively. You can then extract the subsystem from all inputs to the measurement outputs
using:
sys('measurement',:)
                                                                                               1-573
1   Functions
Name
Default: ''
Notes
          Any text that you want to associate with the system, stored as a string or a cell array of character
          vectors. The property stores whichever data type you provide. For instance, if sys1 and sys2 are
          dynamic system models, you can set their Notes properties as follows:
ans =
ans =
UserData
Any type of data you want to associate with system, specified as any MATLAB data type.
Default: []
SamplingGrid
          For arrays of identified linear (IDLTI) models that are derived by sampling one or more independent
          variables, this property tracks the variable values associated with each model. This information
          appears when you display or plot the model array. Use this information to trace results back to the
          independent variables.
          Set the field names of the data structure to the names of the sampling variables. Set the field values
          to the sampled variable values associated with each model in the array. All sampling variables should
          be numeric and scalar valued, and all arrays of sampled values should match the dimensions of the
          model array.
          For example, if you collect data at various operating points of a system, you can identify a model for
          each operating point separately and then stack the results together into a single system array. You
          can tag the individual models in the array with information regarding the operating point:
1-574
                                                                                             idpoly
where sys is an array containing three identified models obtained at rpms 1000, 5000 and 10000,
respectively.
For model arrays generated by linearizing a Simulink model at multiple parameter values or
operating points, the software populates SamplingGrid automatically with the variable values that
correspond to each entry in the array. For example, the Simulink Control Design commands
linearize and slLinearizer populate SamplingGrid in this way.
Default: []
Tips
• Although idpoly supports continuous-time models, idtf and idproc enable more choices for
  estimation of continuous-time models. Therefore, for some continuous-time applications, these
  model types are preferable.
See Also
ar | armax | arx | bj | idproc | idss | idtf | iv4 | ivar | oe | polydata | polyest |
setPolyFormat | translatecov
Topics
“Estimate Polynomial Models in the App”
“Estimate Polynomial Models at the Command Line”
“Polynomial Sizes and Orders of Multi-Output Polynomial Models”
“What Are Polynomial Models?”
“Dynamic System Models”
                                                                                            1-575
1   Functions
          idproc
          Continuous-time process model with identifiable parameters
          Syntax
          sys = idproc(type)
          sys = idproc(type,Name,Value)
          Description
          sys = idproc(type) creates a continuous-time process model with identifiable parameters. type
          specifies aspects of the model structures, such as the number of poles in the model, whether the
          model includes an integrator, and whether the model includes a time delay.
          Object Description
          An idproc model represents a system as a continuous-time process model with identifiable
          (estimable) coefficients.
A simple SISO process model has a gain, a time constant, and a delay:
                           Kp     −T s
                sys =            e d .
                        1 + Tp1s
          Kp is a proportional gain. Kp1 is the time constant of the real pole, and Td is the transport delay (dead
          time).
More generally, idproc can represent process models with up to three poles and a zero:
                                    1 + T zs           −T s
                sys = Kp                              e d .
                           1 + Tp1s 1 + Tp2s 1 + Tp3s
          Two of the poles can be a complex conjugate (underdamped) pair. In that case, the general form of
          the process model is:
                                        1 + T zs                   −Tds
                sys = Kp                       2
                                                                   e      .
                           1 + 2ζTωs + Tωs             1 + Tp3s
Tω is the time constant of the complex pair of poles, and ζ is the associated damping constant.
          In addition, any idproc model can have an integrator. For example, the following is a process model
          that you can represent with idproc:
                                    1                   −Tds
                sys = Kp                           2
                                                       e       .
                           s 1 + 2ζTωs + Tωs
1-576
                                                                                                     idproc
This model has no zero (Tz = 0). The model has a complex pair of poles. The model also has an
integrator, represented by the 1/s term.
For idproc models, all the time constants, the delay, the proportional gain, and the damping
coefficient can be estimable parameters. The idproc model stores the values of these parameters in
properties of the model such as Kp, Tp1, and Zeta. (See “Properties” on page 1-581 for more
information.)
A MIMO process model contains a SISO process model corresponding to each input-output pair in the
system. For idproc models, the form of each input-output pair can be independently specified. For
example, a two-input, one-output process can have one channel with two poles and no zero, and
another channel with a zero, a pole, and an integrator. All the coefficients are independently
estimable parameters.
• Estimate the idproc model based on output or input-output measurements of a system, using the
  procest command. procest estimates the values of the free parameters such as gain, time
  constants, and time delay. The estimated values are stored as properties of the resulting idproc
  model. For example, the properties sys.Tz and sys.Kp of an idproc model sys store the zero
  time constant and the proportional gain, respectively. (See “Properties” on page 1-581 for more
  information.) The Report property of the resulting model stores information about the estimation,
  such as handling of initial conditions and options used in estimation.
   When you obtain an idproc model by estimation, you can extract estimated coefficients and their
   uncertainties from the model using commands such as getpar and getcov.
• Create an idproc model using the idproc command.
   You can create an idproc model to configure an initial parameterization for estimation of a
   process model. When you do so, you can specify constraints on the parameters. For example, you
   can fix the values of some coefficients, or specify minimum or maximum values for the free
   coefficients. You can then use the configured model as an input argument to procest to estimate
   parameter values with those constraints.
Examples
Create SISO Process Model with Complex Poles and Time Delay
Create a process model with a pair of complex poles and a time delay. Set the initial value of the
model to the following:
                     0 . 01
    sys =                            2
                                         e−5s
            1 + 2 0 . 1 10 s + 10s
sys = idproc('P2DU')
sys =
Process model with transfer function:
                  Kp
  G(s) = --------------------- * exp(-Td*s)
         1+2*Zeta*Tw*s+(Tw*s)^2
                                                                                                 1-577
1   Functions
                      Kp   =   NaN
                      Tw   =   NaN
                    Zeta   =   NaN
                      Td   =   NaN
          Parameterization:
              {'P2DU'}
             Number of free coefficients: 4
             Use "getpvec", "getcov" for parameters and their uncertainties.
          Status:
          Created by direct construction or transformation. Not estimated.
          The input 'P2DU' specifies an underdamped pair of poles and a time delay. The display shows that
          sys has the desired structure. The display also shows that the four free parameters, Kp, Tw, Zeta,
          and Td are all initialized to NaN.
          sys.Kp =    0.01;
          sys.Tw =    10;
          sys.Zeta    = 0.1;
          sys.Td =    5;
          You can use sys to specify this parameterization and these initial guesses for process model
          estimation with procest.
          Create a one-input, three-output process model, where each channel has two real poles and a zero,
          but only the first channel has a time delay, and only the first and third channels have an integrator.
          type = {'P2ZDI';'P2Z';'P2ZI'};
          sys = idproc(type)
          sys =
          Process model with 3 outputs: y_k = Gk(s)u
            From input 1 to output 1:
                              1+Tz*s
            G1(s) = Kp * ------------------- * exp(-Td*s)
                         s(1+Tp1*s)(1+Tp2*s)
                      Kp   =   NaN
                     Tp1   =   NaN
                     Tp2   =   NaN
                      Td   =   NaN
                      Tz   =   NaN
Kp = NaN
1-578
                                                                                                 idproc
         Tp1 = NaN
         Tp2 = NaN
          Tz = NaN
          Kp     =   NaN
         Tp1     =   NaN
         Tp2     =   NaN
          Tz     =   NaN
Parameterization:
    {'P2DIZ'}
    {'P2Z' }
    {'P2IZ' }
   Number of free coefficients: 13
   Use "getpvec", "getcov" for parameters and their uncertainties.
Status:
Created by direct construction or transformation. Not estimated.
idproc creates a MIMO model where each character vector in the type array defines the structure
of the corresponding I/O pair. Since type is a column vector of character vectors, sys is a one-input,
three-output model having the specified parameterization structure. type{k,1} specifies the
structure of the subsystem sys(k,1). All identifiable parameters are initialized to NaN.
Create a 3-by-1 array of process models, each containing one output and two input channels.
Specify the structure for each model in the array of process models.
type1 = {'P1D','P2DZ'};
type2 = {'P0','P3UI'};
type3 = {'P2D','P2DI'};
type = cat(3,type1,type2,type3);
size(type)
ans = 1×3
1 2 3
sysarr = idproc(type);
The first two dimensions of the cell array type set the output and input dimensions of each model in
the array of process models. The remaining dimensions of the cell array set the array dimensions.
Thus, sysarr is a 3-model array of 2-input, one-output process models.
                                                                                                1-579
1   Functions
sysarr(:,:,2)
          ans =
          Process model with 2 inputs: y = G11(s)u1 + G12(s)u2
            From input 1 to output 1:
            G11(s) = Kp
Kp = NaN
                      Kp   =   NaN
                      Tw   =   NaN
                    Zeta   =   NaN
                     Tp3   =   NaN
          Parameterization:
              {'P0'}    {'P3IU'}
             Number of free coefficients: 5
             Use "getpvec", "getcov" for parameters and their uncertainties.
          Status:
          Created by direct construction or transformation. Not estimated.
This two-input, one-output model corresponds to the type2 entry in the type cell array.
          Input Arguments
          type
          For SISO models, type is a character vector made up of one or more of the following characters that
          specify aspects of the model structure:
           Characters                Meaning
           Pk                        A process model with k poles (not including an integrator). k must be 0, 1, 2,
                                     or 3.
           Z                         The process model includes a zero (Tz ≠ 0). A type with P0 cannot include Z
                                     (a process model with no poles cannot include a zero).
           D                         The process model includes a time delay (deadtime) (Td ≠ 0).
           I                         The process model includes an integrator (1/s).
           U                         The process model is underdamped. In this case, the process model includes
                                     a complex pair of poles
          Every type character vector must begin with one of P0, P1, P2, or P3. All other components are
          optional. For example:
• 'P1D' specifies a process model with one pole and a time delay (deadtime) term:
1-580
                                                                                                  idproc
               Kp     −T s
    sys =            e d .
            1 + Tp1s
                    Kp
    sys =                     2
                                  .
            1 + 2ζTωs + Tωs
   Kp, Tw, and Zeta are the identifiable parameters of this model.
• 'P3ZDI' creates a process model with three poles. All poles are real, because U is not included.
  The model also includes a zero, a time delay, and an integrator:
                          1 + T zs           −T s
    sys = Kp                                e d .
               s 1 + Tp1s 1 + Tp2s 1 + Tp3s
The identifiable parameters of this model are Kp, Tz, Tp1, Tp2, Tp3, and Td.
The values of all parameters in a particular model structure are initialized to NaN. You can change
them to finite values by setting the values of the corresponding idproc model properties after you
create the model. For example, sys.Td = 5 sets the initial value of the time delay of sys to 5.
For a MIMO process model with Ny outputs and Nu inputs, type is an Ny-by-Nu cell array of
character vectors specifying the structure of each input/output pair in the model. For example,
type{i,j} specifies the type of the subsystem sys(i,j) from the jth input to the yth output.
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Use Name,Value arguments to specify parameter initial values and additional properties on page 1-
581 of idproc models during model creation. For example, sys =
idproc('p2z','InputName','Voltage','Kp',10,'Tz',0); creates an idproc model with the
InputName property set to Voltage. The command also initializes the parameter Kp to a value of 10,
and Tz to 0.
Properties
idproc object properties include:
Type
For a SISO model sys, the property sys.Type contains a character vector specifying the structure of
the system. For example, 'P1D'.
For a MIMO model with Ny outputs and Nu inputs, sys.Type is an Ny-by-Nu cell array of character
vectors specifying the structure of each input/output pair in the model. For example, type{i,j}
specifies the structure of the subsystem sys(i,j) from the jth input to the ith output.
                                                                                                  1-581
1   Functions
          The character vectors are made up of one or more of the following characters that specify aspects of
          the model structure:
           Characters             Meaning
           Pk                     A process model with k poles (not including an integrator). k is 0, 1, 2, or 3.
           Z                      The process model includes a zero (Tz ≠ 0).
           D                      The process model includes a time delay (deadtime) (Td ≠ 0).
           I                      The process model includes an integrator (1/s).
           U                      The process model is underdamped. In this case, the process model includes
                                  a complex pair of poles
          If you create an idproc model sys using the idproc command, sys.Type contains the model
          structure that you specify with the type input argument.
          If you obtain an idproc model by identification using procest, then sys.Type contains the model
          structures that you specified for that identification.
          In general, you cannot change the type of an existing model. However, you can change whether the
          model contains an integrator using the property sys.Integration.
Kp,Tp1,Tp2,Tp3,Tz,Tw,Zeta,Td
          If you create an idproc model using the idproc command, the values of all parameters present in
          the model structure initialize by default to NaN. The values of parameters not present in the model
          structure are fixed to 0. For example, if you create a model, sys, of type 'P1D', then Kp, Tp1, and Td
          are initialized to NaN and are identifiable (free) parameters. All remaining parameters, such as Tp2
          and Tz, are inactive in the model. The values of inactive parameters are fixed to zero and cannot be
          changed.
          For a MIMO model with Ny outputs and Nu inputs, each parameter value is an Ny-by-Nu cell array of
          character vectors specifying the corresponding parameter value for each input/output pair in the
          model. For example, sys.Kp(i,j) specifies the Kp value of the subsystem sys(i,j) from the jth
          input to the ith output.
          For an idproc model sys, each parameter value property such as sys.Kp, sys.Tp1, sys.Tz, and
          the others is an alias to the corresponding Value entry in the Structure property of sys. For
          example, sys.Tp3 is an alias to the value of the property sys.Structure.Tp3.Value.
          Default: For each parameter value, NaN if the process model structure includes the particular
          parameter; 0 if the structure does not include the parameter.
Integration
          Logical value or matrix denoting the presence or absence of an integrator in the transfer function of
          the process model.
For a SISO model sys, sys.Integration = true if the model contains an integrator.
          For a MIMO model, sys.Integration(i,j) = true if the transfer function from the jth input to
          the ith output contains an integrator.
1-582
                                                                                                  idproc
When you create a process model using the idproc command, the value of sys.Integration is
determined by whether the corresponding type contains I.
NoiseTF
sys.NoiseTF stores the coefficients of the numerator and the denominator polynomials for the noise
transfer function H(s) = N(s)/D(s).
sys.NoiseTF is a structure with fields num and den. Each field is a cell array of Ny row vectors,
where Ny is the number of outputs of sys. These row vectors specify the coefficients of the noise
transfer function numerator and denominator in order of decreasing powers of s.
Typically, the noise transfer function is automatically computed by the estimation function procest.
You can specify a noise transfer function that procest uses as an initial value. For example:
Default: struct('num',{num2cell(ones(Ny,1))},'den',{num2cell(ones(Ny,1))})
Structure
sys.Structure includes one entry for each parameter in the model structure of sys. For example,
if sys is of type 'P1D', then sys includes identifiable parameters Kp, Tp1, and Td. Correspondingly,
sys.Structure.Kp, sys.Structure.Tp1, and sys.Structure.Td contain information about
each of these parameters, respectively.
   For SISO models, each parameter value property such as sys.Kp, sys.Tp1, sys.Tz, and the
   others is an alias to the corresponding Value entry in the Structure property of sys. For
   example, sys.Tp3 is an alias to the value of the property sys.Structure.Tp3.Value.
                                                                                                 1-583
1   Functions
          • Maximum — Maximum value that the parameter can assume during estimation.
          • Free — Logical value 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, to fix the dead time to 5:
                sys.Td = 5;
                sys.Structure.Td.Free = false;
          • Scale — Scale of the parameter’s value. Scale is not used in estimation.
          • Info — Structure array for storing parameter units and labels. The structure has Label and
            Unit fields.
Specify parameter units and labels as character vectors. For example, 'Time'.
          Structure also includes a field Integration that stores a logical array indicating whether each
          corresponding process model has an integrator. sys.Structure.Integration is an alias to
          sys.Integration.
          For a MIMO model with Ny outputs and Nu input, Structure is an Ny-by-Nu array. The element
          Structure(i,j) contains information corresponding to the process model for the (i,j) input-
          output pair.
NoiseVariance
          An identified model includes a white, Gaussian noise component e(t). NoiseVariance is the variance
          of this noise component. Typically, the model estimation function (such as procest) determines this
          variance.
          For SISO models, NoiseVariance is a scalar. For MIMO models, NoiseVariance is a Ny-by-Ny
          matrix, where Ny is the number of outputs in the system.
Report
          Summary report that contains information about the estimation options and results when the process
          model is obtained using the procest estimation command. Use Report to query a model for how it
          was estimated, including its:
          • Estimation method
          • Estimation options
          • Search termination conditions
          • Estimation data fit and other quality metrics
          The contents of Report are irrelevant if the model was created by construction.
          m = idproc('P2DU');
          m.Report.OptionsUsed
ans =
[]
          If you obtain the process model using estimation commands, the fields of Report contain information
          on the estimation data, options, and results.
1-584
                                                                                                 idproc
DisturbanceModel: 'estimate'
    InitialCondition: 'auto'
               Focus: 'prediction'
  EstimateCovariance: 1
             Display: 'off'
         InputOffset: [1x1 param.Continuous]
        OutputOffset: []
      Regularization: [1x1 struct]
        SearchMethod: 'auto'
       SearchOptions: [1x1 idoptions.search.identsolver]
        OutputWeight: []
            Advanced: [1x1 struct]
For more information on this property and how to use it, see the Output Arguments section of the
corresponding estimation command reference page and “Estimation Report”.
InputDelay
Input delays. InputDelay is a numeric vector specifying a time delay for each input channel. Specify
input delays in the time unit stored in the TimeUnit property.
For a system with Nu inputs, set InputDelay to an Nu-by-1 vector, where each entry is a numerical
value representing the input delay for the corresponding input channel. You can also set InputDelay
to a scalar value to apply the same delay to all channels.
OutputDelay
Output delays.
Ts
Sample time. For idproc, Ts is fixed to zero because all idproc models are continuous time.
TimeUnit
Units for the time variable, the sample time Ts, and any time delays in the model, specified as one of
the following values:
• 'nanoseconds'
• 'microseconds'
• 'milliseconds'
• 'seconds'
• 'minutes'
• 'hours'
                                                                                                 1-585
1   Functions
          • 'days'
          • 'weeks'
          • 'months'
          • 'years'
          Changing this property has no effect on other properties, and therefore changes the overall system
          behavior. Use chgTimeUnit to convert between time units without modifying system behavior.
Default: 'seconds'
InputName
          Alternatively, use automatic vector expansion to assign input names for multi-input models. For
          example, if sys is a two-input model, enter:
sys.InputName = 'controls';
          When you estimate a model using an iddata object, data, the software automatically sets
          InputName to data.InputName.
          You can use the shorthand notation u to refer to the InputName property. For example, sys.u is
          equivalent to sys.InputName.
InputUnit
Use InputUnit to keep track of input signal units. InputUnit has no effect on system behavior.
InputGroup
          Input channel groups. The InputGroup property lets you assign the input channels of MIMO systems
          into groups and refer to each group by name. Specify input groups as a structure. In this structure,
1-586
                                                                                                  idproc
field names are the group names, and field values are the input channels belonging to each group.
For example:
sys.InputGroup.controls = [1 2];
sys.InputGroup.noise = [3 5];
creates input groups named controls and noise that include input channels 1, 2 and 3, 5,
respectively. You can then extract the subsystem from the controls inputs to all outputs using:
sys(:,'controls')
OutputName
Alternatively, use automatic vector expansion to assign output names for multi-output models. For
example, if sys is a two-output model, enter:
sys.OutputName = 'measurements';
When you estimate a model using an iddata object, data, the software automatically sets
OutputName to data.OutputName.
You can use the shorthand notation y to refer to the OutputName property. For example, sys.y is
equivalent to sys.OutputName.
OutputUnit
Use OutputUnit to keep track of output signal units. OutputUnit has no effect on system behavior.
OutputGroup
Output channel groups. The OutputGroup property lets you assign the output channels of MIMO
systems into groups and refer to each group by name. Specify output groups as a structure. In this
                                                                                               1-587
1   Functions
          structure, field names are the group names, and field values are the output channels belonging to
          each group. For example:
          sys.OutputGroup.temperature = [1];
          sys.InputGroup.measurement = [3 5];
          creates output groups named temperature and measurement that include output channels 1, and
          3, 5, respectively. You can then extract the subsystem from all inputs to the measurement outputs
          using:
          sys('measurement',:)
Name
Default: ''
Notes
          Any text that you want to associate with the system, stored as a string or a cell array of character
          vectors. The property stores whichever data type you provide. For instance, if sys1 and sys2 are
          dynamic system models, you can set their Notes properties as follows:
          sys1.Notes = "sys1 has a string.";
          sys2.Notes = 'sys2 has a character vector.';
          sys1.Notes
          sys2.Notes
ans =
ans =
UserData
Any type of data you want to associate with system, specified as any MATLAB data type.
Default: []
SamplingGrid
          For arrays of identified linear (IDLTI) models that are derived by sampling one or more independent
          variables, this property tracks the variable values associated with each model. This information
          appears when you display or plot the model array. Use this information to trace results back to the
          independent variables.
1-588
                                                                                                  idproc
Set the field names of the data structure to the names of the sampling variables. Set the field values
to the sampled variable values associated with each model in the array. All sampling variables should
be numeric and scalar valued, and all arrays of sampled values should match the dimensions of the
model array.
For example, if you collect data at various operating points of a system, you can identify a model for
each operating point separately and then stack the results together into a single system array. You
can tag the individual models in the array with information regarding the operating point:
where sys is an array containing three identified models obtained at rpms 1000, 5000 and 10000,
respectively.
For model arrays generated by linearizing a Simulink model at multiple parameter values or
operating points, the software populates SamplingGrid automatically with the variable values that
correspond to each entry in the array. For example, the Simulink Control Design commands
linearize and slLinearizer populate SamplingGrid in this way.
Default: []
See Also
idss | idtf | pem | procest | ssest | tfest
                                                                                                 1-589
1   Functions
          idresamp
          Resample time-domain data by decimation or interpolation
          Syntax
          datar = idresamp(data,R)
          datar = idresamp(data,R,order,tol)
          [datar,res_fact] = idresamp(data,R,order,tol)
          Description
          datar = idresamp(data,R) resamples data on a new sample interval R and stores the resampled
          data as datar.
          Input Arguments
          data
                Name of time-domain iddata object or a matrix of data. Can be input-output or time-series data.
                Any positive number you specify is replaced by the rational approximation, Q/P.
          order
                Order of the filters applied before interpolation and decimation.
                Default: 8
          tol
                Tolerance of the rational approximation for the resampling factor R.
                Smaller tolerance might result in larger P and Q values, which produces more accurate answers
                at the expense of slower computation.
Default: 0.1
          Output Arguments
          datar
                Name of the resampled data variable. datar class matches the data class, as specified.
1-590
                                                                                            idresamp
res_fact
   Rational approximation for the specified resampling factor R and tolerance tol.
   Any positive number you specify is replaced by the rational approximation, Q/P, where the data is
   interpolated by a factor P and then decimated by a factor Q.
See Also
resample
Introduced in R2007a
                                                                                              1-591
1   Functions
          idss
          State-space model with identifiable parameters
          Description
          Use idss to create a continuous-time or discrete-time state-space model with identifiable (estimable)
          coefficients, or to convert “Dynamic System Models” to state-space form.
          A state-space model of a system with input vector u, output vector y, and disturbance e takes the
          following form in continuous time:
                 dx t
                      = Ax t + Bu t + Ke t
                  dt
                  y t = Cx t + Du t + e t
                 x k + 1 = Ax k + Bu k + Ke k
                    y k = Cx k + Du k + e k
          For idss models, the elements of the state-space matrices A, B, C, and D can be estimable
          parameters. The elements of the state disturbance K can also be estimable parameters. The idss
          model stores the values of these matrix elements in the A, B, C, D, and K properties of the model.
          Creation
          You can obtain an idss model object in one of three ways.
          • Estimate the idss model based on the input-output measurements of a system by using n4sid or
            ssest. These estimation commands estimate the values of the estimable elements of the state-
            space matrices. The estimated values are stored in the A, B, C, D, and K properties of the resulting
            idss model. The Report property of the resulting model stores information about the estimation,
            such as on the handling of initial state values and the options used in estimation. For example:
                sys = ssest(data,nx);
                A = sys.A;
                B = sys.B;
                sys.Report
sys = idss(A,B,C,D)
                You can create an idss model to configure an initial parameterization for estimation of a state-
                space model to fit measured response data. When you do so, you can specify constraints on one or
                more of the state-space matrix elements. For instance, you can fix the values of some elements, or
                specify minimum or maximum values for the free elements. You can then use the configured model
                as an input argument to an estimation command (ssest or n4sid) to estimate parameter values
1-592
                                                                                                 idss
   with those constraints. For examples, see “Create State-Space Model with Identifiable
   Parameters” on page 1-602 and “Configure Identifiable Parameters of State-Space Model” on
   page 1-603.
• Convert an existing dynamic system model to an idss model using the idss command. For
  example:
sys_ss = idss(sys_tf);
For information on functions you can use to extract information from or transform idss model
objects, see “Object Functions” on page 1-601.
Syntax
sys   =   idss(A,B,C,D)
sys   =   idss(A,B,C,D,K)
sys   =   idss(A,B,C,D,K,x0)
sys   =   idss(A,B,C,D,K,x0,Ts)
sys   =   idss( ___ ,Name,Value)
sys = idss(sys0)
sys = idss(sys0,'split')
Description
Create State-Space Model
sys = idss(A,B,C,D) creates a state-space model with specified state-space matrices A,B,C,D.
By default, sys is a discrete-time model with an unspecified sample time and no state disturbance
element. Use this syntax especially when you want to configure an initial parameterization as an
input to a state-space estimation function such as n4sid or ssest.
sys = idss(A,B,C,D,K,x0) initializes the state values with the vector x0.
sys = idss(A,B,C,D,K,x0,Ts) specifies the sample time property Ts. Use Ts = 0 to create a
continuous-time model.
sys = idss( ___ ,Name,Value) sets additional properties using one or more name-value pair
arguments. Specify name-value pair arguments after any of the input argument combinations in the
previous syntaxes.
Convert Dynamic System Model to State-Space Model
sys = idss(sys0) converts any dynamic system model sys0 to idss model form.
sys = idss(sys0,'split') converts sys0 to idss model form, and treats the last Ny input
channels of sys0 as noise channels in the returned model. sys0 must be a numeric (nonidentified)
tf, zpk, or ss model object. Also, sys0 must have at least as many inputs as outputs.
Input Arguments
                                                                                               1-593
1   Functions
          • When sys0 is an identified model, its estimated parameter covariance is lost during conversion. If
            you want to translate the estimated parameter covariance during the conversion, use
            translatecov.
          • When sys0 is a numeric (nonidentified) model, the state-space data of sys0 defines the A, B, C,
            and D matrices of the converted model. The disturbance matrix K is fixed to zero. The
            NoiseVariance value defaults to eye(Ny), where Ny is the number of outputs of sys.
          For the syntax sys = idss(sys0,'split'), sys0 must be a numeric (nonidentified) tf, zpk, or
          ss model object. Also, sys0 must have at least as many inputs as outputs. Finally, the subsystem
          sys0(:,Ny+1:Ny+Nu) must contain a nonzero feedthrough term (the subsystem must be biproper).
          Properties
          A,B,C,D — Values of state-space matrices
          matrices
          Values of the state-space matrices, specified as matrices that correspond to each of the A, B, C, and D
          matrices.
          For a system with Ny outputs, Nu inputs, and Nx states, the state-space matrices have the following
          dimensions:
          • A — Nx-by-Nx matrix
          • B — Nx-by-Nu matrix
          • C — Ny-by-Nx matrix
          • D — Ny-by-Nu matrix
          If you obtain an idss model sys by identification using ssest or n4sid, then sys.A, sys.B, sys.C,
          and sys.D contain the estimated values of the matrix elements.
          If you create an idss model sys using the idss command, sys.A, sys.B, sys.C, and sys.D
          contain the initial values of the state-space matrices that you specify with the A,B,C,D input
          arguments.
          For an idss model sys, each property sys.A, sys.B, sys.C, and sys.D is an alias of the
          corresponding Value entry in the Structure property of sys. For example, sys.A is an alias of the
          value of the property sys.Structure.A.Value.
          Value of the state disturbance matrix K, specified as an Nx-by-Ny matrix, where Nx is the number of
          states and Ny is the number of outputs.
          If you obtain an idss model sys by identification using ssest or n4sid, then sys.K contains the
          estimated values of the matrix elements.
1-594
                                                                                                   idss
If you create an idss model sys using the idss command, sys.K contains the initial values of the
state-space matrices that you specify with the K input argument.
For an idss model sys, sys.K is an alias to the value of the property sys.Structure.K.Value.
Use StateUnit to keep track of the units each state is expressed in. StateUnit has no effect on
system behavior.
Example: 'rad' corresponds to the units of the only state in a first-order model
Information about the estimable parameters of the idss model, specified as property-specific values.
Structure.A, Structure.B, Structure.C, Structure.D, and Structure.K contain information
about the A, B, C, D, and K matrices, respectively. Each parameter in Structure contains the
following fields.
                                                                                                 1-595
1   Functions
          For an example of configuring model parameters using the Structure property, see “Configure
          Identifiable Parameters of State-Space Model” on page 1-603.
          An identified model includes a white Gaussian noise component e(t). NoiseVariance is the variance
          of this noise component. Typically, the model estimation function (such as ssest) determines this
          variance.
          Summary report that contains information about the estimation options and results for a state-space
          model obtained using estimation commands, such as ssest, ssregest, and n4sid. Use Report to
          find estimation information for the identified model, including the:
          • Estimation method
          • Estimation options
          • Search termination conditions
          • Estimation data fit and other quality metrics
If you create the model by construction, the contents of Report are irrelevant.
1-596
                                                                                                   idss
ans =
[]
If you obtain the using estimation commands, the fields of Report contain information on the
estimation data, options, and results.
InitialState: 'auto'
          N4Weight: 'auto'
         N4Horizon: 'auto'
             Focus: 'prediction'
EstimateCovariance: 1
           Display: 'off'
       InputOffset: []
      OutputOffset: []
      OutputWeight: []
      SearchMethod: 'auto'
     SearchOptions: [1x1 idoptions.search.identsolver]
    Regularization: [1x1 struct]
          Advanced: [1x1 struct]
For more information on this property and how to use it, see the Output Arguments section of the
corresponding estimation command reference page and “Estimation Report”.
Input delay for each input channel, specified as a scalar value or numeric vector. For continuous-time
systems, specify input delays in the time unit stored in the TimeUnit property. For discrete-time
systems, specify input delays in integer multiples of the sample time Ts. For example, setting
InputDelay to 3 specifies a delay of three sample times.
For a system with Nu inputs, set InputDelay to an Nu-by-1 vector. Each entry of this vector is a
numerical value that represents the input delay for the corresponding input channel.
You can also set InputDelay to a scalar value to apply the same delay to all channels.
Ts — Sample Time
-1 (default) | 0 | positive scalar
                                                                                                1-597
1   Functions
          • Continuous-time model — 0
          • Discrete-time model with a specified sampling time — a positive scalar representing the sampling
            period expressed in the unit specified by the TimeUnit property of the model
          • Discrete-time model with unspecified sample time — -1
          Changing this property does not discretize or resample the model. Use c2d and d2c to convert
          between continuous- and discrete-time representations. Use d2d to change the sample time of a
          discrete-time system.
          Units for the time variable, the sample time Ts, and any time delays in the model, specified as a
          scalar.
          Changing this property does not resample or convert the data. Modifying the property changes only
          the interpretation of the existing data. Use chgTimeUnit to convert data to different time units
          Alternatively, use automatic vector expansion to assign input names for multi-input models. For
          example, if sys is a two-input model, enter:
sys.InputName = 'controls';
          When you estimate a model using an iddata object data, the software automatically sets
          InputName to data.InputName.
          You can use the shorthand notation u to refer to the InputName property. For example, sys.u is
          equivalent to sys.InputName.
1-598
                                                                                                    idss
Use InputUnit to keep track of input signal units. InputUnit has no effect on system behavior.
Input channel groups, specified as a structure. The InputGroup property lets you divide the input
channels of MIMO systems into groups so that you can refer to each group by name. In the
InputGroup structure, set field names to the group names, and field values to the input channels
belonging to each group.
For example, create input groups named controls and noise that include input channels 1, 2 and
3, 5, respectively.
sys.InputGroup.controls = [1 2];
sys.InputGroup.noise = [3 5];
You can then extract the subsystem from the controls inputs to all outputs using the following
syntax:
sys(:,'controls')
Alternatively, use automatic vector expansion to assign output names for multi-output models. For
example, if sys is a two-output model, enter:
sys.OutputName = 'measurements';
When you estimate a model using an iddata object, data, the software automatically sets
OutputName to data.OutputName.
You can use the shorthand notation y to refer to the OutputName property. For example, sys.y is
equivalent to sys.OutputName.
                                                                                              1-599
1   Functions
Use OutputUnit to keep track of output signal units. OutputUnit has no effect on system behavior.
          Output channel groups, specified as a structure. The OutputGroup property lets you divide the
          output channels of MIMO systems into groups and refer to each group by name. In the OutputGroup
          structure, set field names to the group names, and field values to the output channels belonging to
          each group.
          For example, create output groups named temperature and measurement that include output
          channels 1, and 3, 5, respectively.
          sys.OutputGroup.temperature = [1];
          sys.OutputGroup.measurement = [3 5];
          You can then extract the subsystem from all inputs to the measurement outputs using the following
          syntax:
sys('measurement',:)
          Any text that you want to associate with the system, specified as a string or a cell array of character
          vectors. The property stores whichever data type you provide. For instance, if sys1 and sys2 are
          dynamic system models, you can set their Notes properties as follows.
ans =
ans =
Data to associate with the system, specified as any MATLAB data type.
1-600
                                                                                                    idss
For arrays of identified linear (IDLTI) models that you derive by sampling one or more independent
variables, this property tracks the variable values associated with each model. This information
appears when you display or plot the model array. Use this information to trace results back to the
independent variables.
Set the field names of the data structure to the names of the sampling variables. Set the field values
to the sampled variable values associated with each model in the array. All sampling variables must
be numeric and scalar valued, and all arrays of sampled values must match the dimensions of the
model array.
For example, suppose that you collect data at various operating points of a system. You can identify a
model for each operating point separately and then stack the results together into a single system
array. You can tag the individual models in the array with information regarding the operating point.
Here, sys is an array containing three identified models obtained at 1000, 5000, and 10000 rpm,
respectively.
For model arrays that you generate by linearizing a Simulink model at multiple parameter values or
operating points, the software populates SamplingGrid automatically with the variable values that
correspond to each entry in the array.
Object Functions
In general, any function applicable to “Dynamic System Models” is applicable to an idss model
object. These functions are of four general types.
• Functions that operate and return idss model objects enable you to transform and manipulate
  idss models. For instance:
The following lists contain a representative subset of the functions that you can use with idss
models.
                                                                                                  1-601
1   Functions
Examples
          Create a 4th-order SISO state-space model with identifiable parameters. Initialize the initial state
          values to 0.1 for all entries. Set the sample time to 0.1 s.
sys = idss(A,B,C,D,K,x0,Ts);
1-602
                                                                                                    idss
sys is a 4th-order SISO idss model. The number of states and input-output dimensions are
determined by the dimensions of the state-space matrices. By default, all entries in the matrices A, B,
C, D, and K are identifiable parameters.
You can use sys to specify an initial parameterization for state-space model estimation with ssest or
n4sid.
Create a 4th-order SISO state-space model with identifiable parameters. Name the input and output
channels of the model, and specify minutes as the model time unit.
You can use name-value pair arguments to specify additional model properties during model creation.
sys = idss(A,B,C,D,'InputName','Drive','TimeUnit','minutes');
To change or specify most attributes of an existing model, you can use dot notation. For example,
change the output name.
sys.OutputName = 'Torque';
Configure an idss model so that it has no state disturbance element and only the nonzero entries of
the A matrix are estimable. Additionally, fix the values of the B matrix.
You can configure individual parameters of an idss model to specify constraints for state-space
model estimation with ssest or n4sid.
sys = idss(A,B,C,D,K,x0,0);
Setting all entries of K to 0 creates an idss model with no state disturbance element.
Use the Structure property of the model to fix the values of some of the parameters.
sys.Structure.A.Free = (A~=0);
sys.Structure.B.Free = false;
sys.Structure.K.Free = false;
                                                                                                 1-603
1   Functions
          The entries in sys.Structure.A.Free determine whether the corresponding entries in sys.A are
          free (identifiable) or fixed. The first line sets sys.Structure.A.Free to a logical matrix that is
          true wherever A is nonzero, and false everywhere else. This setting fixes the values of the zero
          entries in sys.A.
          The remaining lines fix all the values in sys.B and sys.K to the values that you specified during
          model creation.
          Model a dynamic system using a transfer function. Then use idss to convert the transfer-function
          model into state-space form.
                              s+4
                 G(s) =
                           s2 + 20s + 5
          num = [1 4];
          den = [1 20 5];
          G = idtf(num,den)
G =
                    s + 4
                --------------
                s^2 + 20 s + 5
          Parameterization:
             Number of poles: 2   Number of zeros: 1
             Number of free coefficients: 4
             Use "tfdata", "getpvec", "getcov" for parameters and their uncertainties.
          Status:
          Created by direct construction or transformation. Not estimated.
          sys0 =
            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    -20    -2.5
                 x2      2       0
                B =
                      u1
1-604
                                                                                                   idss
   x1    2
   x2    0
  C =
         x1    x2
   y1   0.5     1
  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 uncertainties.
Status:
Created by direct construction or transformation. Not estimated.
When you provide a multi-dimensional array to idss in place of one of the state-space matrices, the
first two dimensions specify the numbers of states, inputs, or outputs of each model in the array. The
remaining dimensions specify the dimensions of the array itself. A is a 2-by-2-by-3-by-4 array.
Therefore, sysarr is a 3-by-4 array of idss models. Each model in sysarr has two states, specified
by the first two dimensions of A. Further, each model in sysarr has the same B, C, and D values.
                                                                                                1-605
1   Functions
          The first command preallocates the array. The first two dimensions of the array are the I/O
          dimensions of each model in the array. Therefore, sysarr is a 2-element vector of SISO models.
          The remaining commands assign an idss model to each position in sysarr. Each model in an array
          must have the same I/O dimensions.
          This command adds another idss model along the first array dimension of sysarr. sysarr is now a
          3-by-1 array of SISO idss models.
          See Also
          idgrey | idpoly | idproc | idssdata | idtf | n4sid | pem | ssest | ssestOptions |
          translatecov
          Topics
          “Dynamic System Models”
          “What Are State-Space Models?”
          “Canonical State-Space Realizations”
          “Estimate State-Space Models with Structured Parameterization”
Introduced in R2006a
1-606
                                                                                                idssdata
idssdata
State-space data of identified system
Syntax
[A,B,C,D,K] = idssdata(sys)
[A,B,C,D,K,x0] = idssdata(sys)
[A,B,C,D,K,x0,dA,dB,dC,dD,dK,dx0] = idssdata(sys)
[A,B,C,D,K, ___ ] = idssdata(sys,j1,...,jN)
[A,B,C,D,K, ___ ] = idssdata(sys,'cell')
Description
[A,B,C,D,K] = idssdata(sys) returns the A,B,C,D and K matrices of the identified state-space
model sys.
[A,B,C,D,K, ___ ] = idssdata(sys,j1,...,jN) returns data for the j1, ..., jn entries in
the model array sys.
[A,B,C,D,K, ___ ] = idssdata(sys,'cell') returns data for all the entries in the model array
sys as separate cells in cell arrays.
Input Arguments
sys
Identified model.
If sys is not an identified state-space model (idss or idgrey), then it is first converted to an idss
model. This conversion results in a loss of the model uncertainty information.
j1,...,jN
Output Arguments
A,B,C,D,K
                                                                                                 1-607
1   Functions
          If sys is an array of identified models, then A,B,C,D,K are multi-dimension arrays. To access the
          state-space matrix, say A, for the k-th entry of sys, use A(:,:,k).
x0
Initial state.
          If sys is an idss or idgrey model, then x0 is the value obtained during estimation. It is also stored
          using the Report.Parameters property of sys.
If sys is an array of identified models, then x0 contains a column for each entry in sys.
dA,dB,dC,dD,dK
          If sys is an array of identified models, then dA,dB,dC,dD,dK are multi-dimension arrays. To access
          the state-space matrix, say A, for the k-th entry of sys, use A(:,:,k).
dx0
If sys is an array of identified models, then dx0 contains a column for each entry in sys.
Examples
Obtain the identified state-space matrices for a model estimated from data.
          load icEngine.mat
          data = iddata(y,u,0.04);
          sys = n4sid(data,4,'InputDelay',2);
data is an iddata object representing data sampled at a sampling rate of 0.04 seconds.
[A,B,C,D,K] = idssdata(sys);
1-608
                                                                                                  idssdata
load icEngine.mat
data = iddata(y,u,0.04);
sys = n4sid(data,4,'InputDelay',2);
data is an iddata object representing data sampled at a sampling rate of 0.04 seconds.
[A,B,C,D,K,x0] = idssdata(sys);
A, B, C, D and K represent the state-space matrices of the identified model sys. x0 is the initial state
identified for sys.
load icEngine.mat
data = iddata(y,u,0.04);
sys = n4sid(data,4,'InputDelay',2);
data is an iddata object representing data sampled at a sampling rate of 0.04 seconds.
Obtain the uncertainty matrices associated with the state-space matrices of sys.
[A,B,C,D,K,x0,dA,dB,dC,dD,dx0] = idssdata(sys);
dA, dB, dC, dD and dK represent the uncertainty associated with the state-space matrices of the
identified model sys. dx0 represents the uncertainty associated with the estimated initial state.
Obtain the state-space matrices for multiple models from an array of identified models.
load   icEngine.mat
data   = iddata(y,u,0.04);
sys2   = n4sid(data,2,'InputDelay',2);
sys3   = n4sid(data,3,'InputDelay',2);
                                                                                                   1-609
1   Functions
          sys4 = n4sid(data,4,'InputDelay',2);
          sys = stack(1,sys2,sys3,sys4);
data is an iddata object representing data sampled at a sampling rate of 0.04 seconds.
          sys is an array of idss models. The first entry of sys is a second-order identified system. The second
          and third entries of sys are third- and fourth-order identified systems, respectively.
Obtain the state-space matrices for the first and third entries of sys.
          [A,B,C,D,K,x0] = idssdata(sys,1);
          [A,B,C,D,K,x0] = idssdata(sys,3);
          load icEngine.mat
          data = iddata(y,u,0.04);
          sys3 = n4sid(data,3,'InputDelay',2);
          sys4 = n4sid(data,4,'InputDelay',2);
          sys = stack(1,sys3,sys4);
data is an iddata object representing data sampled at a sampling rate of 0.04 seconds.
          sys is an array of idss models. The first entry of sys is a third-order identified system and the
          second entry is a fourth-order identified system.
[A,B,C,D,K,x0] = idssdata(sys,'cell');
          A, B, C, D and K are cell arrays containing the state-space matrices of the individual entries of the
          identified model array sys. x0 is a cell array containing the estimated initial state of the individual
          entries of the identified model array sys.
          See Also
          idss | polydata | ssdata | tfdata | zpkdata
Introduced in R2012a
1-610
                                                                                                     idtf
idtf
Transfer function model with identifiable parameters
Syntax
sys = idtf(num,den)
sys = idtf(num,den,Ts)
sys = idtf( ___ ,Name,Value)
sys = idtf(sys0)
Description
sys = idtf(num,den) creates a continuous-time transfer function with identifiable parameters (an
idtf model). num specifies the current values of the transfer function numerator coefficients. den
specifies the current values of the transfer function denominator coefficients.
sys = idtf( ___ ,Name,Value) creates a transfer function with properties on page 1-618
specified by one or more Name,Value pair arguments.
sys = idtf(sys0) converts any dynamic system model, sys0, to idtf model form.
Object Description
An idtf model represents a system as a continuous-time or discrete-time transfer function with
identifiable (estimable) coefficients.
A SISO transfer function is a ratio of polynomials with an exponential term. In continuous time,
In discrete time,
In discrete time, z–k represents a time delay of kTs, where Ts is the sample time.
For idtf models, the denominator coefficients a0,...,am–1 and the numerator coefficients b0,...,bn can
be estimable parameters. (The leading denominator coefficient is always fixed to 1.) The time delay τ
(or kin discrete time) can also be an estimable parameter. The idtf model stores the polynomial
coefficients a0,...,am–1 and b0,...,bn in the Denominator and Numerator properties of the model,
respectively. The time delay τ or k is stored in the IODelay property of the model.
                                                                                                   1-611
1   Functions
          A MIMO transfer function contains a SISO transfer function corresponding to each input-output pair
          in the system. For idtf models, the polynomial coefficients and transport delays of each input-output
          pair are independently estimable parameters.
          • Estimate the idtf model based on input-output measurements of a system, using tfest. The
            tfest command estimates the values of the transfer function coefficients and transport delays.
            The estimated values are stored in the Numerator, Denominator, and IODelay properties of the
            resulting idtf model. The Report property of the resulting model stores information about the
            estimation, such as handling of initial conditions and options used in estimation.
                When you obtain an idtf model by estimation, you can extract estimated coefficients and their
                uncertainties from the model. To do so, use commands such as tfdata, getpar, or getcov.
          • Create an idtf model using the idtf command.
                You can create an idtf model to configure an initial parameterization for estimation of a transfer
                function to fit measured response data. When you do so, you can specify constraints on such
                values as the numerator and denominator coefficients and transport delays. For example, you can
                fix the values of some parameters, or specify minimum or maximum values for the free
                parameters. You can then use the configured model as an input argument to tfest to estimate
                parameter values with those constraints.
          • Convert an existing dynamic system model to an idtf model using the idtf command.
Note Unlike idss and idpoly, idtf uses a trivial noise model and does not parameterize the noise.
So, H = 1 in y = Gu + He.
Examples
                              s+4
                 G(s) =
                          s2 + 20s + 5
          num = [1 4];
          den = [1 20 5];
          G = idtf(num,den);
          G is an idtf model. num and den specify the initial values of the numerator and denominator
          polynomial coefficients in descending powers of s. The numerator coefficients having initial values 1
          and 4 are estimable parameters. The denominator coefficient having initial values 20 and 5 are also
          estimable parameters. The leading denominator coefficient is always fixed to 1.
You can use G to specify an initial parameterization for estimation with tfest.
1-612
                                                                                                      idtf
Create Transfer Function with Known Input Delay and Specified Attributes
Specify a continuous-time, SISO transfer function with known input delay. The transfer function initial
values are given by:
                       5
    G(s) = e−5 . 8s
                      s+5
Label the input of the transfer function with the name 'Voltage' and specify the input units as
volt.
Use Name,Value input pairs to specify the delay, input name, and input unit.
num = 5;
den = [1 5];
input_delay = 5.8;
input_name = 'Voltage';
input_unit = 'volt';
G = idtf(num,den,'InputDelay',input_delay,...
         'InputName',input_name,'InputUnit',input_unit);
G is an idtf model. You can use G to specify an initial parameterization for estimation with tfest. If
you do so, model properties such as InputDelay, InputName, and InputUnit are applied to the
estimated model. The estimation process treats InputDelay as a fixed value. If you want to estimate
the delay and specify an initial value of 5.8 s, use the IODelay property instead.
Specify a discrete-time SISO transfer function with estimable parameters. The initial values of the
transfer function are:
             z − 0.1
    H(z) =
             z + 0.8
num = [1 -0.1];
den = [1 0.8];
Ts = 0.2;
H = idtf(num,den,Ts);
num and den are the initial values of the numerator and denominator polynomial coefficients. For
discrete-time systems, specify the coefficients in ascending powers of z−1.
Ts specifies the sample time for the transfer function as 0.2 seconds.
H is an idtf model. The numerator and denominator coefficients are estimable parameters (except
for the leading denominator coefficient, which is fixed to 1).
                                                                                                1-613
1   Functions
          Specify a discrete-time, two-input, two-output transfer function. The initial values of the MIMO
          transfer function are:
                          1       z
                       z + 0.2 z + 0.7
                H(z) =
                       −z + 2     3
                       z − 0.3 z + 0.3
          nums = {1,[1,0];[-1,2],3};
          dens = {[1,0.2],[1,0.7];[1,-0.3],[1,0.3]};
          Ts = 0.2;
          H = idtf(nums,dens,Ts);
          nums and dens specify the initial values of the coefficients in cell arrays. Each entry in the cell array
          corresponds to the numerator or denominator of the transfer function of one input-output pair. For
          example, the first row of nums is {1,[1,0]}. This cell array specifies the numerators across the first
          row of transfer functions in H. Likewise, the first row of dens, {[1,0.2],[1,0.7]}, specifies the
          denominators across the first row of H.
Ts specifies the sample time for the transfer function as 0.2 seconds.
          H is an idtf model. All of the polynomial coefficients are estimable parameters, except for the
          leading coefficient of each denominator polynomial. These coefficients are always fixed to 1.
                                1 + 0 . 4q−1
                H(q−1) =
                           1 + 0 . 1q−1 − 0 . 3q−2
          num = [1 0.4];
          den = [1 0.1 -0.3];
          Ts = 0.1;
          convention_variable = 'q^-1';
          H = idtf(num,den,Ts,'Variable',convention_variable);
num and den are the numerator and denominator polynomial coefficients in ascending powers of q−1.
Ts specifies the sample time for the transfer function as 0.1 seconds.
H is an idtf model.
1-614
                                                                                                         idtf
Specify a transfer function with estimable coefficients whose initial value is the static gain matrix:
           1 0 1
    H(s) = 1 1 0
           3 0 2
M = [1 0 1; 1 1 0; 3 0 2];
H = idtf(M);
H is an idtf model that describes a three input (Nu=3), three output (Ny=3) transfer function. Each
input/output channel is an estimable static gain. The initial values of the gains are given by the values
in the matrix M.
Convert a state-space model with identifiable parameters to a transfer function with identifiable
parameters.
    ∼       −0 . 2 0         −2        0.1
    x (t) =           x(t) +    u(t) +     e(t)
             0 −0 . 3         4        0.2
    y(t) = 1 1 x(t)
A = [-0.2, 0; 0, -0.3];
B = [2;4];
C = [1, 1];
D = 0;
K = [0.1; 0.2];
sys0 = idss(A,B,C,D,K,'NoiseVariance',0.1);
sys = idtf(sys0);
A, B, C, D and K are matrices that specify sys0, an identifiable state-space model with a noise
variance of 0.1.
Load time-domain system response data and use it to estimate a transfer function for the system.
                                                                                                   1-615
1   Functions
To see the numerator and denominator coefficients of the resulting estimated model sys, enter:
sys.Numerator
ans = 1×2
2.4554 176.9856
sys.Denominator
ans = 1×3
          To view the uncertainty in the estimates of the numerator and denominator and other information,
          use tfdata.
          Create an array of transfer function models with identifiable coefficients. Each transfer function in
          the array is of the form:
                          a
                Hs =         .
                         s+a
The initial value of the coefficient a varies across the array, from 0.1 to 1.0, in increments of 0.1.
          H = idtf(zeros(1,1,10));
          for k = 1:10
              num = k/10;
              den = [1 k/10];
              H(:,:,k) = idtf(num,den);
          end
          The first command preallocates a one-dimensional, 10-element array, H, and fills it with empty idtf
          models.
          The first two dimensions of a model array are the output and input dimensions. The remaining
                                                                                   th
          dimensions are the array dimensions. H(:,:,k) represents the k                model in the array. Thus, the for
                                 th
          loop replaces the k         entry in the array with a transfer function whose coefficients are initialized with
          a = k/10.
          Input Arguments
          num
1-616
                                                                                                       idtf
For SISO transfer functions, specify the initial values of the numerator coefficients num as a row
vector. Specify the coefficients in order of:
Use NaN for any coefficient whose initial value is not known.
For MIMO transfer functions with Ny outputs and Nu inputs, num is a Ny-by-Nu cell array of
numerator coefficients for each input/output pair.
den
For SISO transfer functions, specify the initial values of the denominator coefficients den as a row
vector. Specify the coefficients in order of:
The leading coefficient in den must be 1. Use NaN for any coefficient whose initial value is not known.
For MIMO transfer functions with Ny outputs and Nu inputs, den is a Ny-by-Nu cell array of
denominator coefficients for each input/output pair.
Ts
Sample time. For continuous-time models, Ts = 0. For discrete-time models, Ts is a positive scalar
representing the sampling period. This value is expressed in the unit specified by the TimeUnit
property of the model. To denote a discrete-time model with unspecified sample time, set Ts = -1.
Changing this property does not discretize or resample the model. Use c2d and d2c to convert
between continuous- and discrete-time representations. Use d2d to change the sample time of a
discrete-time system.
sys0
Dynamic system.
When sys0 is an identified model, its estimated parameter covariance is lost during conversion. If
you want to translate the estimated parameter covariance during the conversion, use
translatecov.
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
                                                                                                 1-617
1   Functions
          Use Name,Value arguments to specify additional properties on page 1-618 of idtf models during
          model creation. For example, idtf(num,den,'InputName','Voltage') creates an idtf model
          with the InputName property set to Voltage.
          Properties
          idtf object properties include:
Numerator
          If you create an idtf model sys using the idtf command, sys.Numerator contains the initial
          values of numerator coefficients that you specify with the num input argument.
          If you obtain an idtf model by identification using tfest, then sys.Numerator contains the
          estimated values of the numerator coefficients.
          For an idtf model sys, the property sys.Numerator is an alias for the value of the property
          sys.Structure.Numerator.Value.
          For SISO transfer functions, the values of the numerator coefficients are stored as a row vector in
          order of:
          For MIMO transfer functions with Ny outputs and Nu inputs, Numerator is a Ny-by-Nu cell array of
          numerator coefficients for each input/output pair.
Denominator
          If you create an idtf model sys using the idtf command, sys.Denominator contains the initial
          values of denominator coefficients that you specify with the den input argument.
          If you obtain an idtf model sys by identification using tfest, then sys.Denominator contains the
          estimated values of the denominator coefficients.
          For an idtf model sys, the property sys.Denominator is an alias for the value of the property
          sys.Structure.Denominator.Value.
          For SISO transfer functions, the values of the denominator coefficients are stored as a row vector in
          order of:
          The leading coefficient in Denominator is fixed to 1. Any coefficient whose initial value is not known
          is stored as NaN.
1-618
                                                                                                      idtf
For MIMO transfer functions with Ny outputs and Nu inputs, Denominator is a Ny-by-Nu cell array of
denominator coefficients for each input/output pair.
Variable
The value of Variable is reflected in the display, and also affects the interpretation of the num and
den coefficient vectors for discrete-time models. For Variable = 'z^-1' or 'q^-1', the
coefficient vectors are ordered as ascending powers of the variable.
IODelay
Transport delays. IODelay is a numeric array specifying a separate transport delay for each input/
output pair.
If you create an idtf model sys using the idtf command, sys.IODelay contains the initial values
of the transport delay that you specify with a Name,Value argument pair.
If you obtain an idtf model sys by identification using tfest, then sys.IODelay contains the
estimated values of the transport delay.
For an idtf model sys, the property sys.IODelay is an alias for the value of the property
sys.Structure.IODelay.Value.
For continuous-time systems, transport delays are expressed in the time unit stored in the TimeUnit
property. For discrete-time systems, specify transport are expressed as integers denoting delay of a
multiple of the sample time Ts.
For a MIMO system with Ny outputs and Nu inputs, set IODelay as a Ny-by-Nu array. Each entry of
this array is a numerical value representing the transport delay for the corresponding input/output
pair. You can set IODelay to a scalar value to apply the same delay to all input/output pairs.
Structure
   NaN represents unknown parameter values. For denominators, the value of the leading coefficient,
   specified by sys.Structure.Denominator.Value(1) is fixed to 1.
                                                                                                 1-619
1   Functions
                For SISO models, sys.Numerator, sys.Denominator, and sys.IODelay are aliases for
                sys.Structure.Numerator.Value, sys.Structure.Denominator.Value, and
                sys.Structure.IODelay.Value, respectively.
                For denominators, the value of Free for the leading coefficient, specified by
                sys.Structure.Denominator.Free(1), is always false (the leading denominator coefficient
                is always fixed to 1).
          • Scale — Scale of the parameter’s value. Scale is not used in estimation.
          • Info — Structure array for storing parameter units and labels. The structure has Label and
            Unit fields.
Specify parameter units and labels as character vectors. For example, 'Time'.
          For a MIMO model with Ny outputs and Nu input, Structure is an Ny-by-Nu array. The element
          Structure(i,j) contains information corresponding to the transfer function for the (i,j) input-
          output pair.
NoiseVariance
          An identified model includes a white, Gaussian noise component e(t). NoiseVariance is the variance
          of this noise component. Typically, the model estimation function (such as tfest) determines this
          variance.
          For SISO models, NoiseVariance is a scalar. For MIMO models, NoiseVariance is a Ny-by-Ny
          matrix, where Ny is the number of outputs in the system.
Report
          Summary report that contains information about the estimation options and results when the transfer
          function model is obtained using estimation commands, such as tfest and impulseest. Use
          Report to query a model for how it was estimated, including its:
          • Estimation method
          • Estimation options
1-620
                                                                                                        idtf
The contents of Report are irrelevant if the model was created by construction.
ans =
[]
If you obtain the transfer function model using estimation commands, the fields of Report contain
information on the estimation data, options, and results.
    InitializeMethod:     'iv'
   InitializeOptions:     [1x1 struct]
    InitialCondition:     'auto'
               Focus:     'simulation'
  EstimateCovariance:     1
             Display:     'off'
         InputOffset:     []
        OutputOffset:     []
      Regularization:     [1x1 struct]
        SearchMethod:     'auto'
       SearchOptions:     [1x1 idoptions.search.identsolver]
        OutputWeight:     []
            Advanced:     [1x1 struct]
For more information on this property and how to use it, see the Output Arguments section of the
corresponding estimation command reference page and “Estimation Report”.
InputDelay
Input delays. InputDelay is a numeric vector specifying a time delay for each input channel. For
continuous-time systems, specify input delays in the time unit stored in the TimeUnit property. For
discrete-time systems, specify input delays in integer multiples of the sample time Ts. For example,
InputDelay = 3 means a delay of three sample times.
For a system with Nu inputs, set InputDelay to an Nu-by-1 vector. Each entry of this vector is a
numerical value representing the input delay for the corresponding input channel. You can also set
InputDelay to a scalar value to apply the same delay to all channels.
Estimation treats InputDelay as a fixed constant of the model. Estimation uses the IODelay
property for estimating time delays. To specify initial values and constraints for estimation of time
delays, use sys.Structure.IODelay.
                                                                                                  1-621
1   Functions
OutputDelay
Output delays.
Ts
          Sample time. For continuous-time models, Ts = 0. For discrete-time models, Ts is a positive scalar
          representing the sampling period. This value is expressed in the unit specified by the TimeUnit
          property of the model. To denote a discrete-time model with unspecified sample time, set Ts = -1.
          Changing this property does not discretize or resample the model. Use c2d and d2c to convert
          between continuous- and discrete-time representations. Use d2d to change the sample time of a
          discrete-time system.
TimeUnit
          Units for the time variable, the sample time Ts, and any time delays in the model, specified as one of
          the following values:
          • 'nanoseconds'
          • 'microseconds'
          • 'milliseconds'
          • 'seconds'
          • 'minutes'
          • 'hours'
          • 'days'
          • 'weeks'
          • 'months'
          • 'years'
          Changing this property has no effect on other properties, and therefore changes the overall system
          behavior. Use chgTimeUnit to convert between time units without modifying system behavior.
Default: 'seconds'
InputName
          Alternatively, use automatic vector expansion to assign input names for multi-input models. For
          example, if sys is a two-input model, enter:
sys.InputName = 'controls';
1-622
                                                                                                    idtf
When you estimate a model using an iddata object, data, the software automatically sets
InputName to data.InputName.
You can use the shorthand notation u to refer to the InputName property. For example, sys.u is
equivalent to sys.InputName.
InputUnit
Use InputUnit to keep track of input signal units. InputUnit has no effect on system behavior.
InputGroup
Input channel groups. The InputGroup property lets you assign the input channels of MIMO systems
into groups and refer to each group by name. Specify input groups as a structure. In this structure,
field names are the group names, and field values are the input channels belonging to each group.
For example:
sys.InputGroup.controls = [1 2];
sys.InputGroup.noise = [3 5];
creates input groups named controls and noise that include input channels 1, 2 and 3, 5,
respectively. You can then extract the subsystem from the controls inputs to all outputs using:
sys(:,'controls')
OutputName
Alternatively, use automatic vector expansion to assign output names for multi-output models. For
example, if sys is a two-output model, enter:
sys.OutputName = 'measurements';
                                                                                              1-623
1   Functions
          When you estimate a model using an iddata object, data, the software automatically sets
          OutputName to data.OutputName.
          You can use the shorthand notation y to refer to the OutputName property. For example, sys.y is
          equivalent to sys.OutputName.
OutputUnit
Use OutputUnit to keep track of output signal units. OutputUnit has no effect on system behavior.
OutputGroup
          Output channel groups. The OutputGroup property lets you assign the output channels of MIMO
          systems into groups and refer to each group by name. Specify output groups as a structure. In this
          structure, field names are the group names, and field values are the output channels belonging to
          each group. For example:
          sys.OutputGroup.temperature = [1];
          sys.InputGroup.measurement = [3 5];
          creates output groups named temperature and measurement that include output channels 1, and
          3, 5, respectively. You can then extract the subsystem from all inputs to the measurement outputs
          using:
sys('measurement',:)
Name
Default: ''
Notes
          Any text that you want to associate with the system, stored as a string or a cell array of character
          vectors. The property stores whichever data type you provide. For instance, if sys1 and sys2 are
          dynamic system models, you can set their Notes properties as follows:
1-624
                                                                                                     idtf
ans =
ans =
UserData
Any type of data you want to associate with system, specified as any MATLAB data type.
Default: []
SamplingGrid
For arrays of identified linear (IDLTI) models that are derived by sampling one or more independent
variables, this property tracks the variable values associated with each model. This information
appears when you display or plot the model array. Use this information to trace results back to the
independent variables.
Set the field names of the data structure to the names of the sampling variables. Set the field values
to the sampled variable values associated with each model in the array. All sampling variables should
be numeric and scalar valued, and all arrays of sampled values should match the dimensions of the
model array.
For example, if you collect data at various operating points of a system, you can identify a model for
each operating point separately and then stack the results together into a single system array. You
can tag the individual models in the array with information regarding the operating point:
where sys is an array containing three identified models obtained at rpms 1000, 5000 and 10000,
respectively.
For model arrays generated by linearizing a Simulink model at multiple parameter values or
operating points, the software populates SamplingGrid automatically with the variable values that
correspond to each entry in the array. For example, the Simulink Control Design commands
linearize and slLinearizer populate SamplingGrid in this way.
Default: []
                                                                                                 1-625
1   Functions
          See Also
          getcov | getpar | idfrd | idpoly | idproc | idss | oe | tfdata | tfest | translatecov
          Topics
          “Estimate Transfer Function Models With Prior Knowledge of Model Structure and Constraints”
          “Dynamic System Models”
Introduced in R2012a
1-626
                                                                                                  ifft
ifft
Transform iddata objects from frequency to time domain
Syntax
dat = ifft(Datf)
Description
ifft transforms a frequency-domain iddata object to the time domain. It requires the frequencies
on Datf to be equally spaced from frequency 0 to the Nyquist frequency. This means that if there are
N frequencies in Datf and the sample time is Ts, then
See Also
fft | iddata
Introduced in R2007a
                                                                                              1-627
1   Functions
          impulse
          Impulse response plot of dynamic system; impulse response data
          Syntax
          impulse(sys)
          impulse(sys,Tfinal)
          impulse(sys,t)
          impulse(sys1,sys2,...,sysN)
          impulse(sys1,sys2,...,sysN,Tfinal)
          impulse(sys1,sys2,...,sysN,t)
          [y,t] = impulse(sys)
          [y,t] = impulse(sys,Tfinal)
          y = impulse(sys,t)
          [y,t,x] = impulse(sys)
          [y,t,x,ysd] = impulse(sys)
          Description
          impulse calculates the unit impulse response of a dynamic system model. For continuous-time
          dynamic systems, the impulse response is the response to a Dirac input δ(t). For discrete-time
          systems, the impulse response is the response to a unit area pulse of length Ts and height 1/Ts,
          where Ts is the sample time of the system. (This pulse approaches δ(t) as Ts approaches zero.) For
          state-space models, impulse assumes initial state values are zero.
          impulse(sys) plots the impulse response of the dynamic system model sys. This model can be
          continuous or discrete, and SISO or MIMO. The impulse response of multi-input systems is the
          collection of impulse responses for each input channel. The duration of simulation is determined
          automatically to display the transient behavior of the response.
          impulse(sys,Tfinal) simulates the impulse response from t = 0 to the final time t = Tfinal.
          Express Tfinal in the system time units, specified in the TimeUnit property of sys. For discrete-
          time systems with unspecified sample time (Ts = -1), impulse interprets Tfinal as the number of
          sampling periods to simulate.
          impulse(sys,t) uses the user-supplied time vector t for simulation. Express t in the system time
          units, specified in the TimeUnit property of sys. For discrete-time models, t should be of the form
          Ti:Ts:Tf, where Ts is the sample time. For continuous-time models, t should be of the form
          Ti:dt:Tf, where dt becomes the sample time of a discrete approximation to the continuous system
          (see “Algorithms” on page 1-631). The impulse command always applies the impulse at t=0,
          regardless of Ti.
To plot the impulse responses of several models sys1,..., sysN on a single figure, use:
impulse(sys1,sys2,...,sysN)
impulse(sys1,sys2,...,sysN,Tfinal)
impulse(sys1,sys2,...,sysN,t)
1-628
                                                                                                impulse
As with bode or plot, you can specify a particular color, linestyle, and/or marker for each system, for
example,
impulse(sys1,'y:',sys2,'g--')
See "Plotting and Comparing Multiple Systems" and the bode entry in this section for more details.
[y,t] = impulse(sys)
[y,t] = impulse(sys,Tfinal)
y = impulse(sys,t)
impulse returns the output response y and the time vector t used for simulation (if not supplied as
an argument to impulse). No plot is drawn on the screen. For single-input systems, y has as many
rows as time samples (length of t), and as many columns as outputs. In the multi-input case, the
impulse responses of each input channel are stacked up along the third dimension of y. The
dimensions of y are then
[y,t,x] = impulse(sys)
and y(:,:,j) gives the response to an impulse disturbance entering the jth input channel.
Similarly, the dimensions of x are
Examples
Impulse Response Plot of Second-Order State-Space Model
     ẋ 1       −0.5572 −0.7814 x1   1 −1 u1
            =                      +
     ẋ 2        0.7814    0    x2   0 2 u2
                                          x1
                     y = 1.9691 6.4493
                                          x2
                                                                                                1-629
1   Functions
          The left plot shows the impulse response of the first input channel, and the right plot shows the
          impulse response of the second input channel.
[y,t] = impulse(sys);
Because this system has two inputs, y is a 3-D array with dimensions
size(y)
ans = 1×3
139 1 2
          (the first dimension is the length of t). The impulse response of the first input channel is then
          accessed by
          ch1 = y(:,:,1);
          size(ch1)
ans = 1×2
139 1
1-630
                                                                                               impulse
Fetch the impulse response and the corresponding 1 std uncertainty of an identified linear system .
load(fullfile(matlabroot, 'toolbox', 'ident', 'iddemos', 'data', 'dcmotordata'));
z = iddata(y, u, 0.1, 'Name', 'DC-motor');
set(z, 'InputName', 'Voltage', 'InputUnit', 'V');
set(z, 'OutputName', {'Angular position', 'Angular velocity'});
set(z, 'OutputUnit', {'rad', 'rad/s'});
set(z, 'Tstart', 0, 'TimeUnit', 's');
model = tfest(z,2);
[y,t,~,ysd] = impulse(model,2);
Limitations
The impulse response of a continuous system with nonzero D matrix is infinite at t = 0. impulse
ignores this discontinuity and returns the lower continuity value Cb at t = 0.
Tips
You can change the properties of your plot, for example the units. For information on the ways to
change properties of your plots, see “Ways to Customize Plots” (Control System Toolbox).
Algorithms
Continuous-time models are first converted to state space. The impulse response of a single-input
state-space model
     ẋ = Ax + bu
     y = Cx
     ẋ = Ax, x(0) = b
      y = Cx
To simulate this response, the system is discretized using zero-order hold on the inputs. The sample
time is chosen automatically based on the system dynamics, except when a time vector t = 0:dt:Tf
is supplied (dt is then used as sample time).
See Also
Linear System Analyzer | impulseest | lsim | step
                                                                                               1-631
1   Functions
          impulseest
          Nonparametric impulse response estimation
          Syntax
          sys    =   impulseest(data)
          sys    =   impulseest(data,N)
          sys    =   impulseest(data,N,NK)
          sys    =   impulseest( ___ ,options)
          Description
          sys = impulseest(data) estimates an impulse response model, sys, using time- or frequency-
          domain data, data. The model order (number of nonzero impulse response coefficients) is
          determined automatically using persistence of excitation analysis on the input data.
          sys = impulseest(data,N) estimates an Nth order impulse response model, corresponding to the
          time range 0 :Ts : (N –1)*Ts, where Ts is the data sample time.
sys = impulseest( ___ ,options) specifies estimation options using the options set options.
          Use nonparametric impulse response to analyze data for feedback effects, delays and significant
          time constants.
          Input Arguments
          data
Estimation data with at least one input signal and nonzero sample time.
For time domain estimation, data is an iddata object containing the input and output signal values.
• A positive integer.
1-632
                                                                                                impulseest
     For data containing Nu inputs and Ny outputs, you can also specify N as an Ny-by-Nu matrix of
     positive integers, such that N(i,j) represents the length of impulse response from input j to output
     i.
• [] — Determines the order automatically using persistence of excitation analysis on the input
  data.
NK
Transport delay in the estimated impulse response, specified as a scalar integer. For data containing
Nu inputs and Ny outputs, you can also specify a Ny-by-Nu matrix.
• To generate the impulse response coefficients for negative time values, which is useful for
  feedback analysis, use a negative integer. If you specify a negative value, the value must be the
  same across all output channels.
     You can also use NK = 'negative' to automatically pick negative lags for all input/output
     channels of the model.
• Specify NK = 0 if the delay is unknown. The true delay is then be indicated by insignificant
  impulse response values in the beginning of the response.
• Specify NK = 1 to create a system whose leading numerator coefficient is zero.
Positive values of NK greater than 1 are stored in the IODelay property of sys (sys.IODelay =
max(NK-1,0)). Negative values are stored in the InputDelay property.
The impulse response (input j to output i) coefficients correspond to the time span NK(i,j)*Ts :
Ts : (N(ij)+NK(i,j)-1)*Ts.
options
• Prefilter order
• Regularization algorithm
• Input and output data offsets
Output Arguments
sys
Estimated impulse response model, returned as an idtf model, which encapsulates an FIR model.
Information about the estimation results and options used is stored in the Report property of the
model. Report has the following fields:
                                                                                                   1-633
1   Functions
                          Field Description
                          FitP Normalized root mean squared error
                          erce (NRMSE) measure of how well the
                          nt   response of the model fits the estimation
                               data, expressed as the percentage fit =
                               100(1-NRMSE).
                          Loss Value of the loss function when the
                          Fcn estimation completes.
                          MSE    Mean squared error (MSE) measure of
                                 how well the response of the model fits
                                 the estimation data.
                          FPE    Final prediction error for the model.
                          AIC    Raw Akaike Information Criteria (AIC)
                                 measure of model quality.
                          AICc Small sample-size corrected AIC.
                          nAIC Normalized AIC.
                          BIC    Bayesian Information Criteria (BIC).
           Parameters     Estimated values of model parameters.
           OptionsUsed    Option set used for estimation. If no custom
                          options were configured, this is a set of default
                          options. See impulseestOptions for more
                          information.
           RandState      State of the random number stream at the start
                          of estimation. Empty, [], if randomization was
                          not used during estimation. For more
                          information, see rng in the MATLAB
                          documentation.
1-634
                                                                                             impulseest
                                                    Field Description
                                                    Name Name of the data set.
                                                    Type Data type.
                                                    Leng Number of data samples.
                                                    th
                                                    Ts     Sample time.
                                                    Inte Input intersample behavior, returned as
                                                    rSam one of the following values:
                                                    ple
                                                         • 'zoh' — Zero-order hold maintains a
                                                            piecewise-constant input signal
                                                            between samples.
                                                           • 'foh' — First-order hold maintains a
                                                             piecewise-linear input signal between
                                                             samples.
                                                           • 'bl' — Band-limited behavior
                                                             specifies that the continuous-time
                                                             input signal has zero power above the
                                                             Nyquist frequency.
                                                    Inpu Offset removed from time-domain input
                                                    tOff data during estimation. For nonlinear
                                                    set models, it is [].
                                                    Outp Offset removed from time-domain output
                                                    utOf data during estimation. For nonlinear
                                                    fset models, it is [].
Examples
Compute a nonparametric impulse response model using data from a hair dryer. The input is the
voltage applied to the heater and the output is the heater temperature. Use the first 500 samples for
estimation.
load dry2
ze = dry2(1:500);
sys = impulseest(ze);
ze is an iddata object that contains time-domain data. sys, the identified nonparametric impulse
response model, is an idtf model.
                                                                                                1-635
1   Functions
h = impulseplot(sys,1);
          Right-click the plot and select Characteristics > Confidence Region to view the statistically zero-
          response region. Alternatively, you can use the showConfidence command.
showConfidence(h);
1-636
                                                                                              impulseest
The first significantly nonzero response value occurs at 0.24 seconds, or, the third lag. This implies
that the transport delay is 3 samples. To generate a model where the 3-sample delay is imposed, set
the transport delay to 3:
sys = impulseest(ze,[],3)
If you know about the presence of delay in the input/output data in advance, use the value as a
transport delay for impulse response estimation.
                                                                                                  1-637
1   Functions
          Generate data with 3-sample input to output lag. Create a random input signal and use an idpoly
          model to simulate the output data.
          u = rand(100,1);
          sys = idpoly([1 .1 .4],[0 0 0 4 -2],[1 1 .1]);
          opt = simOptions('AddNoise',true);
          y = sim(sys,u,opt);
          data = iddata(y,u,1);
model = impulseest(data,20,3);
          Obtain regularized estimates of impulse response model using the regularizing kernel estimation
          option.
          opt = impulseestOptions('RegularizationKernel','none');
          sys2 = impulseest(z3,opt);
h = impulseplot(sys1,sys2,70);
1-638
                                                                       impulseest
showConfidence(h);
                                                                          1-639
1   Functions
          The uncertainty in the computed response is reduced at larger lags for the model using
          regularization. Regularization decreases variance at the price of some bias. The tuning of the
          regularization is such that the bias is dominated by the variance error though.
Load data.
Create a transfer function model used for generating the estimation data (true system).
          opt = impulseestOptions('RegularizationKernel','DC');
          m0 = impulseest(eData,70,opt);
Convert the model into a state-space model and reduce the model order.
m1 = balred(idss(m0),15);
1-640
                                                                                            impulseest
m2 = ssregest(eData,15);
Compare the impulse responses of the true system and the estimated models.
impulse(trueSys,m1,m2,50);
legend('trueSys','m1','m2');
Use the empirical impulse response of the measured data to verify whether there are feedback
effects. Significant amplitude of the impulse response for negative time values indicates feedback
effects in data.
Compute the noncausal impulse response using a fourth-order prewhitening filter, automatically
chosen order and negative lag using nonregularized estimation.
load iddata3 z3;
opt = impulseestOptions('pw',4,'RegularizationKernel','none');
sys = impulseest(z3,[],'negative',opt);
                                                                                                1-641
1   Functions
          View the statistically zero-response region by right-clicking on the plot and selecting Characteristics
          > Confidence Region. Alternatively, you can use the showConfidence command.
showConfidence(h);
1-642
                                                                                             impulseest
The large response value at t=0 (zero lag) suggests that the data comes from a process containing
feedthrough. That is, the input affects the output instantaneously. There could also be a direct
feedback effect (proportional control without some delay that u(t) is determined partly by y(t)).
Also, the response values are significant for some negative time lags, such as at -7 seconds and -9
seconds. Such significant negative values suggest the possibility of feedback in the data.
load demofr;
zfr = AMP.*exp(1i*PHA*pi/180);
Ts = 0.1;
data = idfrd(zfr,W,Ts);
sys = impulseest(data);
Identify parametric and nonparametric models for a data set, and compare their step response.
                                                                                                 1-643
1   Functions
          Identify the impulse response model (nonparametric) and state-space model (parametric), based on a
          data set.
          sys1 is a discrete-time identified transfer function model. sys2 is a continuous-time identified state-
          space model.
          step(sys1,'b',sys2,'r');
          legend('impulse response model','state-space model');
          Tips
          • To view the impulse or step response of sys, use either impulseplot or stepplot, respectively.
          • A significant value of the impulse response of sys for negative time values indicates the presence
            of feedback in the data.
          • To view the region of insignificant impulse response (statistically zero) in a plot, right-click on the
            plot and select Characteristics > Confidence Region. A patch depicting the zero-response
            region appears on the plot. The impulse response at any time value is significant only if it lies
            outside the zero response region. The level of significance depends on the number of standard
1-644
                                                                                             impulseest
Algorithms
Correlation analysis refers to methods that estimate the impulse response of a linear model, without
specific assumptions about model orders.
The impulse response, g, is the system's output when the input is an impulse signal. The output
response to a general input, u(t), is obtained as the convolution with the impulse response. In
continuous time:
                ∫
                    t
       y(t) =           g τ u t − τ dτ
                −∞
In discrete-time:
                 ∞
       yt =     ∑        g k u t−k
                k=1
The values of g(k) are the discrete time impulse response coefficients.
You can estimate the values from observed input-output data in several different ways. impulseest
estimates the first n coefficients using the least-squares method to obtain a finite impulse response
(FIR) model of order n.
         uf = Au, yf = Ay
   3     The filtered signals uf and yf are used for estimation.
   You can specify prewhitening using the PW name-value pair argument of impulseestOptions.
• Regularization — The least-squares estimate can be regularized. This means that a prior
  estimate of the decay and mutual correlation among g(k) is formed and used to merge with the
  information about g from the observed data. This gives an estimate with less variance, at the price
  of some bias. You can choose one of the several kernels to encode the prior estimate.
   This option is essential because, often, the model order n can be quite large. In cases where there
   is no regularization, n can be automatically decreased to secure a reasonable variance.
   You can specify the regularizing kernel using the RegularizationKernel Name-Value pair
   argument of impulseestOptions.
• Autoregressive Parameters — The basic underlying FIR model can be complemented by NA
  autoregressive parameters, making it an ARX model.
                                                                                                  1-645
1   Functions
                           n                   NA
                 yt =     ∑     g k u t−k −    ∑    ak y t − k
                          k=1                 k=1
                This gives both better results for small n and allows unbiased estimates when data are generated
                in closed loop. impulseest uses 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:
                           ∞
                 u(t) =   ∑     h(k)y t − k + r t
                          k=0
                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 impulseest with an indication of
                negative delays, mi  =  impulseest(data, nk, nb),  nk < 0, returns a model mi with an impulse
                response
                aligned so that it corresponds to lags nk, nk + 1, .., 0, 1, 2, ..., nb + nk . This is achieved because
                the input delay (InputDelay) of model mi is nk.
          For a multi-input multi-output system, the impulse response g(k) is an ny-by-nu matrix, where ny is
          the number of outputs and nu is the number of inputs. The i–j element of the matrix g(k) describes the
          behavior of the ith output after an impulse in the jth input.
          See Also
          cra | impulse | impulseestOptions | spa | step
          Topics
          “What Is Time-Domain Correlation Analysis?”
Introduced in R2012a
1-646
                                                                                      impulseestOptions
impulseestOptions
Options set for impulseest
Syntax
options = impulseestOptions
options = impulseestOptions(Name,Value)
Description
options = impulseestOptions creates a default options set for impulseest.
Input Arguments
Name-Value Pair Arguments
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
RegularizationKernel
Regularizing kernel, used for regularized estimates of impulse response for all input-output channels.
Regularization reduces variance of estimated model coefficients and produces a smoother response
by trading variance for bias. For more information, see [1].
Default: 'TC'
PW
                                                                                                1-647
1   Functions
• Nonnegative integer
Default: 'auto'
InputOffset
Input signal offset level of time-domain estimation data. Must be one of the following:
          • An Nu-element column vector, where Nu is the number of inputs. For multi-experiment data,
            specify a Nu-by-Ne matrix, where Ne is the number of experiments. The offset value
            InputOffset(i,j) is subtracted from the ith input signal of the jth experiment.
          • [] — No offsets.
Default: []
OutputOffset
Output signal offset level of time-domain estimation data. Must be one of the following:
          • An Ny-element column vector, where Ny is the number of outputs. For multi-experiment data,
            specify a Ny-by-Ne matrix, where Ne is the number of experiments. The offset value
            OputOffset(i,j) is subtracted from the ith output signal of the jth experiment.
          • [] — No offsets.
Default: []
Advanced
          • MaxSize — Maximum allowable size of Jacobian matrices formed during estimation. Specify a
            large positive number.
                Default: 250e3
          • SearchMethod — Search method for estimating regularization parameters, specified as one of
            the following values:
                Default: 'fmincon'
          • AROrder — Order of the AR-part in the model from input to output. Specify as a positive integer.
                An order>0 allows more accurate models of the impulse response in case of feedback and non-
                white output disturbances.
Default: 5
1-648
                                                                                    impulseestOptions
• FeedthroughInSys — Specify whether the impulse response value at zero lag must be attributed
  to feedthrough in the system (true) or to feedback effects (false). Applies only when you
  compute the response values for negative lags.
Default: false
Output Arguments
options
Examples
options = impulseestOptions;
Specify Regularizing Kernel and Prewhitening Options for Impulse Response Estimation
Specify 'HF' regularizing kernel and order of prewhitening filter for impulseest.
options = impulseestOptions('RegularizationKernel','HF','PW',5);
options = impulseestOptions;
options.RegularizationKernel = 'HF';
options.PW = 5;
Tips
• A linear model cannot describe arbitrary input-output offsets. Therefore, before using the data,
  you must either detrend it or remove the levels using InputOffset and OutputOffset. You can
  reintroduce the removed data during simulations by using the InputOffset and OutputOffset
  simulation options. For more information, see simOptions.
• Estimating the impulse response by specifying either InputOffset, OutputOffset or both is
  equivalent to detrending the data using getTrend and detrend. For example:
   opt = impulseestOptions('InputOffset',in_off,'OutputOffset',out_off);
   impulseest(data,opt);
   Tr = getTrend(data),
   Tr.InputOffset = in_off
   TR.OutputOffset = out_off
                                                                                              1-649
1   Functions
                dataT = detrend(data,Tr)
                impulseest(dataT)
          Compatibility Considerations
          Renaming of Estimation and Analysis Options
          The names of some estimation and analysis options were changed in R2018a. Prior names still work.
          For details, see the R2018a release note “Renaming of Estimation and Analysis Options”.
References
          [1] T. Chen, H. Ohlsson, and L. Ljung. “On the Estimation of Transfer Functions, Regularizations and
                   Gaussian Processes - Revisited”, Automatica, Volume 48, August 2012.
          See Also
          impulseest
Introduced in R2012b
1-650
                                                                                            impulseplot
impulseplot
Plot impulse response and return plot handle
Syntax
impulseplot(sys)
impulseplot(sys,Tfinal)
impulseplot(sys,t)
impulseplot(sys1,sys2,...,sysN)
impulseplot(sys1,sys2,...,sysN,Tfinal)
impulseplot(sys1,sys2,...,sysN,t)
impulseplot(AX,...)
impulseplot(..., plotoptions)
h = impulseplot(...)
Description
impulseplot plots the impulse response of the dynamic system model sys. For multi-input models,
independent impulse commands are applied to each input channel. The time range and number of
points are chosen automatically. For continuous systems with direct feedthrough, the infinite pulse at
t=0 is disregarded. impulseplot can also return the plot handle, h. You can use this handle to
customize the plot with the getoptions and setoptions commands. Type
help timeoptions
impulseplot(sys) plots the impulse response of the LTI model without returning the plot handle.
impulseplot(sys,t) uses the user-supplied time vector t for simulation. Express t in the system
time units, specified in the TimeUnit property of sys. For discrete-time models, t should be of the
form Ti:Ts:Tf, where Ts is the sample time. For continuous-time models, t should be of the form
Ti:dt:Tf, where dt becomes the sample time of a discrete approximation to the continuous system
(see impulse). The impulseplot command always applies the impulse at t=0, regardless of Ti.
To plot the impulse response of multiple LTI models sys1,sys2,... on a single plot, use:
impulseplot(sys1,sys2,...,sysN)
impulseplot(sys1,sys2,...,sysN,Tfinal)
impulseplot(sys1,sys2,...,sysN,t)
You can also specify a color, line style, and marker for each system, as in
impulseplot(sys1,'r',sys2,'y--',sys3,'gx')
                                                                                                1-651
1   Functions
          impulseplot(..., plotoptions) plots the impulse response with the options specified in
          plotoptions. Type
help timeoptions
h = impulseplot(...) plots the impulse response and returns the plot handle h.
          Examples
          Example 1
          sys = rss(3);
          h = impulseplot(sys);
          % Normalize responses
          setoptions(h,'Normalize','on');
Example 2
          Plot the impulse response and the corresponding 1 std "zero interval" of an identified linear system.
          load(fullfile(matlabroot, 'toolbox', 'ident', 'iddemos', 'data', 'dcmotordata'));
          z = iddata(y, u, 0.1, 'Name', 'DC-motor');
          set(z, 'InputName', 'Voltage', 'InputUnit', 'V');
          set(z, 'OutputName', {'Angular position', 'Angular velocity'});
          set(z, 'OutputUnit', {'rad', 'rad/s'});
          set(z, 'Tstart', 0, 'TimeUnit', 's');
          model = n4sid(z,4,n4sidOptions('Focus', 'simulation'));
          h = impulseplot(model,2);
          showConfidence(h);
          Tips
          You can change the properties of your plot, for example the units. For information on the ways to
          change properties of your plots, see “Ways to Customize Plots” (Control System Toolbox).
          See Also
          getoptions | impulse | setoptions | showConfidence
Introduced in R2012a
1-652
                                                                                                       init
init
Set or randomize initial parameter values
Syntax
m = init(m0)
m = init(m0,R,pars,sp)
Description
m = init(m0) randomizes initial parameter estimates for model structures m0 for any linear or
nonlinear identified model. It does not support idnlgrey models. m is the same model structure as
m0, but with a different nominal parameter vector. This vector is used as the initial estimate by pem.
m = init(m0,R,pars,sp) randomizes parameters around pars with variances given by the row
vector R. Parameter number k is randomized as pars(k) + e*sqrt(R(k)), where e is a normal
random variable with zero mean and a variance of 1. The default value of R is all ones, and the default
value of pars is the nominal parameter vector in m0.
Only models that give stable predictors are accepted. If sp = 'b', only models that are both stable
and have stable predictors are accepted.
sp = 's' requires stability only of the model, and sp = 'p' requires stability only of the predictor.
sp = 'p' is the default.
Sufficiently free parameterizations can be stabilized by direct means without any random search. To
just stabilize such an initial model, set R = 0. With R > 0, randomization is also done.
For model structures where a random search is necessary to find a stable model/predictor, a
maximum of 100 trials is made by init. It can be difficult to find a stable predictor for high-order
systems by trial and error.
See Also
idnlarx | idnlhw | rsample | simsd
                                                                                                 1-653
1   Functions
          initialize
          Initialize the state of the particle filter
          Syntax
          initialize(pf,numParticles,mean,covariance)
          initialize(pf,numParticles,stateBounds)
          initialize( ___ ,Name,Value)
          Description
          initialize(pf,numParticles,mean,covariance) initializes a particle filter object with a
          specified number of particles. The initial states of the particles in the state space are determined by
          sampling from the multivariate normal distribution with the specified mean and covariance. The
          number of state variables (NumStateVariables) is retrieved automatically based on the length of
          the mean vector.
          initialize( ___ ,Name,Value) initializes the particles with additional options specified by one or
          more Name,Value pair arguments.
Examples
          To create a particle filter object for estimating the states of your system, create appropriate state
          transition function and measurement function for the system.
          Create the particle filter object. Use function handles to provide the state transition and
          measurement likelihood functions to the object.
myPF = particleFilter(@vdpParticleFilterStateFcn,@vdpMeasurementLikelihoodFcn);
Initialize the particle filter at state [2; 0] with unit covariance, and use 1000 particles.
          myPF =
            particleFilter with properties:
                        NumStateVariables: 2
                             NumParticles: 1000
                       StateTransitionFcn: @vdpParticleFilterStateFcn
1-654
                                                                                              initialize
    MeasurementLikelihoodFcn:        @vdpMeasurementLikelihoodFcn
     IsStateVariableCircular:        [0 0]
            ResamplingPolicy:        [1x1 particleResamplingPolicy]
            ResamplingMethod:        'multinomial'
       StateEstimationMethod:        'mean'
            StateOrientation:        'column'
                   Particles:        [2x1000 double]
                     Weights:        [1x1000 double]
                       State:        'Use the getStateEstimate function to see the value.'
             StateCovariance:        'Use the getStateEstimate function to see the value.'
To estimate the states and state estimation error covariance from the constructed object, use the
predict and correct commands.
Input Arguments
pf — Particle filter
particleFilter object
Unless performance is an issue, do not use fewer than 1000 particles. A higher number of particles
can improve the estimate but sacrifices performance speed, because the algorithm has to process
more particles. Tuning the number of particles is the best way to improve the tracking of your
particle filter.
                                                                                               1-655
1   Functions
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside single quotes (' '). You can specify
          several name and value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
          Example: ...'StateOrientation','row'
          See Also
          clone | correct | extendedKalmanFilter | particleFilter | predict |
          unscentedKalmanFilter
          Topics
          “Nonlinear State Estimation Using Unscented Kalman Filter and Particle Filter”
          “What Is Online Estimation?”
          “Generate Code for Online State Estimation in MATLAB”
Introduced in R2017b
1-656
                                                                                              interp
interp
Interpolate FRD model
Syntax
isys = interp(sys,freqs)
Description
isys = interp(sys,freqs) interpolates the frequency response data contained in the FRD model
sys at the frequencies freqs. interp, which is an overloaded version of the MATLAB function
interp, uses linear interpolation and returns an FRD model isys containing the interpolated data at
the new frequencies freqs. If sys is an IDFRD model, the noise spectrum, if non-empty, is also
interpolated. The response and noise covariance data, if available, are also interpolated.
You should express the frequency values freqs in the same units as sys.frequency. The frequency
values must lie between the smallest and largest frequency points in sys (extrapolation is not
supported).
See Also
frd | freqresp | idfrd
Introduced in R2012a
                                                                                             1-657
1   Functions
          iopzmap
          Plot pole-zero map for I/O pairs of model
          Syntax
          iopzmap(sys)
          iopzmap(sys1,sys2,...)
          Description
          iopzmap(sys) computes and plots the poles and zeros of each input/output pair of the dynamic
          system model sys. The poles are plotted as x's and the zeros are plotted as o's.
          iopzmap(sys1,sys2,...) shows the poles and zeros of multiple models sys1,sys2,... on a single
          plot. You can specify distinctive colors for each model, as in
          iopzmap(sys1,'r',sys2,'y',sys3,'g').
          The functions sgrid or zgrid can be used to plot lines of constant damping ratio and natural
          frequency in the s or z plane.
For model arrays, iopzmap plots the poles and zeros of each model in the array on the same diagram.
Examples
iopzmap(H)
1-658
                                                                                           iopzmap
iopzmap generates a separate map for each I/O pair in the system.
View the poles and zeros of an over-parameterized state-space model estimated from input-output
data. (Requires System Identification Toolbox™).
load iddata1
sys = ssest(z1,6,ssestOptions('focus','simulation'));
iopzmap(sys)
                                                                                            1-659
1   Functions
          The plot shows that there are two pole-zero pairs that almost overlap, which hints are their potential
          redundancy.
          Tips
          For additional options for customizing the appearance of the pole-zero plot, use iopzplot.
          See Also
          iopzplot | pole | pzmap | sgrid | zero | zgrid
Introduced in R2012a
1-660
                                                                                                 iopzplot
iopzplot
Plot pole-zero map for I/O pairs and return plot handle
Syntax
h = iopzplot(sys)
iopzplot(sys1,sys2,...)
iopzplot(AX,...)
iopzplot(..., plotoptions)
Description
h = iopzplot(sys) computes and plots the poles and zeros of each input/output pair of the
dynamic system model sys. The poles are plotted as x's and the zeros are plotted as o's. It also
returns the plot handle h. You can use this handle to customize the plot with the getoptions and
setoptions commands. Type
help pzoptions
for a list of available plot options. For more information on the ways to change properties of your
plots, see “Ways to Customize Plots” (Control System Toolbox).
iopzplot(sys1,sys2,...) shows the poles and zeros of multiple dynamic system models
sys1,sys2,... on a single plot. You can specify distinctive colors for each model, as in
iopzplot(sys1,'r',sys2,'y',sys3,'g')
iopzplot(..., plotoptions) plots the poles and zeros with the options specified in
plotoptions. Type
help pzoptions
The function sgrid or zgrid can be used to plot lines of constant damping ratio and natural
frequency in the s or z plane.
For arrays sys of LTI models, iopzplot plots the poles and zeros of each model in the array on the
same diagram.
Examples
sys = rss(3,2,2);
h = iopzplot(sys);
                                                                                                 1-661
1   Functions
          By default, the plot displays the poles and zeros of each I/O pair on its own axis. Use the plot handle
          to view all I/Os on a single axis.
setoptions(h,'IOGrouping','all')
1-662
                                                                                              iopzplot
View the poles and zeros of a sixth-order state-space model estimated from input-output data. Use the
plot handle to display the confidence intervals of the identified model's pole and zero locations.
load iddata1
sys = ssest(z1,6,ssestOptions('focus','simulation'));
h = iopzplot(sys);
showConfidence(h)
                                                                                              1-663
1   Functions
          There is at least one pair of complex-conjugate poles whose locations overlap with those of a complex
          zero, within the 1-σ confidence region. This suggests their redundancy. Hence, a lower (4th) order
          model might be more robust for the given data.
          sys2 = ssest(z1,4,ssestOptions('focus','simulation'));
          h = iopzplot(sys,sys2);
          showConfidence(h)
          legend('6th-order','4th-order')
          axis([-20, 10 -30 30])
1-664
                                                                                 iopzplot
The fourth-order model sys2 shows less variability in the pole-zero locations.
See Also
getoptions | iopzmap | setoptions | showConfidence
Introduced in R2012a
                                                                                 1-665
1   Functions
          isct
          Determine if dynamic system model is in continuous time
          Syntax
          bool = isct(sys)
          Description
          bool = isct(sys) returns a logical value of 1 (true) if the dynamic system model sys is a
          continuous-time model. The function returns a logical value of 0 (false) otherwise.
          Input Arguments
          sys
          Output Arguments
          bool
          bool = 1 (true) if sys is a continuous-time model (sys.Ts = 0). If sys is a discrete-time model,
          bool = 0 (false).
          For a static gain, both isct and isdt return true unless you explicitly set the sample time to a
          nonzero value. If you do so, isdt returns true and isct returns false.
For arrays of models, bool is true if the models in the array are continuous.
          See Also
          isdt | isstable
Introduced in R2012a
1-666
                                                                                                   isdt
isdt
Determine if dynamic system model is in discrete time
Syntax
bool = isdt(sys)
Description
bool = isdt(sys) returns a logical value of 1 (true) if the dynamic system model sys is a
discrete-time model. The function returns a logical value of 0 (false) otherwise.
Input Arguments
sys
Output Arguments
bool
bool = 1 (true) if sys is a discrete-time model (sys.Ts ≠ 0). If sys is a continuous-time model,
bool = 0 (false).
For a static gain, both isct and isdt return true unless you explicitly set the sample time to a
nonzero value. If you do so, isdt returns true and isct returns false.
For arrays of models, bool is true if the models in the array are discrete.
See Also
isct | isstable
Introduced in R2012a
                                                                                               1-667
1   Functions
          isempty
          Determine whether dynamic system model is empty
          Syntax
          isempty(sys)
          Description
          isempty(sys) returns a logical value of 1 (true) if the dynamic system model sys has no input or
          no output, and a logical value of 0 (false) otherwise. Where sys is a frd model, isempty(sys)
          returns 1 when the frequency vector is empty. Where sys is a model array, isempty(sys) returns 1
          when the array has empty dimensions or when the LTI models in the array are empty.
Examples
          Create a continuous-time state-space model with 1 input and no outputs. In this example, specify the
          A and B matrices as 1 and 2, respectively.
sys1 = ss(1,2,[],[]);
isempty(sys1)
          ans = logical
             1
The isempty command returns 1 because the system does not have any outputs.
isempty(tf)
          ans = logical
             1
          Now create a state-space model with 1 input and 1 output. In this example, specify the A, B, C, and D
          matrices as 1, 2, 3, and 4, respectively.
sys2 = ss(1,2,3,4);
isempty(sys2)
1-668
                                                                   isempty
ans = logical
   0
The command returns 0 because the system has inputs and outputs.
See Also
issiso | size
                                                                   1-669
1   Functions
          isLocked
          Locked status of online parameter estimation System object
          Syntax
          L = isLocked(obj)
          Description
          L = isLocked(obj) returns the locked status of online parameter estimation System object, obj.
Examples
Create a System object™ for online estimation of an ARMAX model with default properties.
obj = recursiveARMAX;
L = isLocked(obj)
          L = logical
             0
[A,B,C,EstimatedOutput] = step(obj,1,1);
L = isLocked(obj)
          L = logical
             1
          Input Arguments
          obj — System object for online parameter estimation
          recursiveAR object | recursiveARMA object | recursiveARX object | recursiveARMAX object |
          recursiveOE object | recursiveBJ object | recursiveLS object
System object for online parameter estimation, created using one of the following commands:
1-670
                                                                                                isLocked
• recursiveAR
• recursiveARMA
• recursiveARX
• recursiveARMAX
• recursiveOE
• recursiveBJ
• recursiveLS
Output Arguments
L — Locked status of online estimation System object
logical
Locked status of online estimation System object, returned as a logical value. L is true if obj is
locked.
See Also
clone | recursiveAR | recursiveARMA | recursiveARMAX | recursiveARX | recursiveBJ |
recursiveLS | recursiveOE | release | reset | step
Topics
“What Is Online Estimation?”
Introduced in R2015b
                                                                                                 1-671
1   Functions
          isnlarx
          Detect nonlinearity in estimation data
          Syntax
          isnlarx(Data,Orders)
          isnlarx(Data,Orders,Ky)
          isnlarx( ___ ,Name,Value)
          Description
          isnlarx(Data,Orders) detects nonlinearity in Data by testing whether a nonlinear ARX model
          with the indicated Orders produces a better estimate of Data than a linear ARX model. The
          nonlinear model uses a default treepartition nonlinearity estimator.
          The result of the test is printed to the Command Window and indicates whether a nonlinearity is
          detected. Use the printed detection ratio to assess the reliability of the nonlinearity detection test:
          isnlarx( ___ ,Name,Value) specifies additional nonlinear ARX model options using one or more
          Name,Value pair arguments.
          NLHyp = isnlarx( ___ ) returns the result of the nonlinearity test and suppresses the command
          window output.
Examples
load(fullfile(matlabroot,'toolbox','ident','iddemos','data','frictiondata'))
1-672
                                                                                                  isnlarx
z = iddata(f1,v,1);
The large detection ratio indicates that the test was robust and a significant nonlinearity was
detected. Additionally, the estimated discrepancy of the linear model that was found, that is the data
explained by the nonlinearity, is significantly greater than the noise error, which can indicate a
significant nonlinearity.
Construct an iddata object from the estimation data using a sample time of 0.1 seconds.
z = iddata(y1,u1,0.1);
A detection ratio less than 1 indicates that no nonlinearity was detected. However, since this value is
near 0.5, there may be a weak nonlinearity that was not detected by the test.
                                                                                                 1-673
1   Functions
load(fullfile(matlabroot,'toolbox','ident','iddemos','data','signaltransmissiondata'))
Construct an iddata object from the estimation data using a sample time of 0.1 seconds.
z = iddata(vout,vin,0.1);
orders = [3 0 2];
Display the model regressors for an idnlarx model with the given orders.
getreg(idnlarx(orders));
          Regressors:
              y1(t-1)
              y1(t-2)
              y1(t-3)
Detect nonlinearities in the data, and search for the best nonlinear regressor combination.
isnlarx(z,orders,'NonlinearRegressors','search');
          The regressor search found that using the first two regressors produces the best nonlinear estimation
          of the given data.
          A detection ratio greater than 1 but less than 2 means that a nonlinearity was detected, but the test
          was not robust. This result may indicate that the detected nonlinearity is not significant. Additionally,
          the data explained by the nonlinearity is smaller than the noise error, which can be an indication of a
          weak nonlinearity.
load(fullfile(matlabroot,'toolbox','ident','iddemos','data','cstrdata'))
z = iddata(y1,u1,0.1);
orders = [3*ones(2,2),ones(2,3),2*ones(2,3)];
Detect nonlinearities in the data, and determine the test quantities behind the evaluation.
NLHyp = isnlarx(z,orders);
1-674
                                                                                                 isnlarx
load(fullfile(matlabroot,'toolbox','ident','iddemos','data','narendralidata'))
z = iddata(u,y1,1);
orders = [1 1 2];
Detect nonlinearities in the data, and determine the test quantities behind the evaluation.
[NLHyp,NLValue,NLRegs,NoiseSigma,DetectRatio] = isnlarx(z,orders);
Input Arguments
Data — Time-domain estimation data
iddata object
Time-domain estimation data, specified as an iddata object. Data can have one or more output
channels and zero or more input channels. Data must be uniformly sampled and cannot contain
missing (NaN) samples.
Model orders and delays for defining the regressor configuration, specified as a 1-by-3 vector, [na
nb nk].
• na is an ny-by-ny matrix, where na(i,j) specifies the number of regressors from the jth output
  used to predict the ith output.
• nb is an ny-by-nu matrix, where nb(i,j) specifies the number of regressors from the jth input
  used to predict the ith output.
• nk is an ny-by-nu matrix, where nk(i,j) specifies the lag in the jth input used to predict the ith
  output.
na = [1 2; 2 3]
nb = [1 2 3; 2 3 1];
nk = [2 0 3; 1 0 5];
The estimation data for this system has three inputs (u1, u2, u3) and two outputs (y1, y2). Consider
the regressors used to predict output, y2(t):
• Since na(2,:) is [2 3], the contributing regressors from the outputs are:
                                                                                                1-675
1   Functions
          Note The minimum lag for regressors based on output variables is always 1, while the minimum lag
          for regressors based on input variables is dictated by nk. Use getreg to view the complete set of
          regressors used by the nonlinear ARX model.
          Output channel number in estimation data, specified as a positive integer in the range [1,ny], where
          ny is the number of output channels.
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
          Example: 'NonlinearRegressors','output' specifies that only the regressors containing output
          variables are used as inputs to the nonlinear block of the model.
          Regressors constructed from combinations of inputs and outputs, specified as the comma-separated
          pair consisting of 'CustomRegressors' and one of the following for single-output systems:
• {'y1(t-3)^3','y2(t-1)*u1(t-3)','sin(u3(t-2))'}
                Each character vector must represent a valid formula for a regressor contributing towards the
                prediction of the model output. The formula must be written using the input and output names
                and the time variable name as variables.
          • Array of custom regressor objects, created using customreg or polyreg.
          For a model with ny outputs, specify an ny-by-1 cell array of customreg object arrays or character
          arrays.
1-676
                                                                                                  isnlarx
Example: 'CustomRegressors',{'y1(t-3)^3','y2(t-1)*u1(t-3)'}
Example: 'CustomRegressors',{'sin(u3(t-2))'}
Subset of regressors that enter as inputs to the nonlinear block of the model, specified as the comma-
separated pair consisting of 'NonlinearRegressors' and one of the following values:
For a model with multiple outputs, specify a cell array of ny elements, where ny is the number of
output channels. For each output, specify one of the preceding options. Alternatively, to apply the
same regressor subset to all model outputs, specify [] or any of the character vector options alone,
for example 'standard'.
Example: 'NonlinearRegressors','search' performs a best regressor search for the only
output of a single output model, or all of the outputs of a multiple output model.
Example: 'NonlinearReg','input' applies only input regressors to the inputs of the nonlinear
function.
Example: 'NonlinearRegressors',{'input','output'} applies input regressors to the first
output, and output regressors to the second output of a model with two outputs.
Output Arguments
NLHyp — Result of the nonlinearity test
0 | 1 | logical vector
Result of the nonlinearity test, returned as a logical vector with length equal to the number of output
channels. The elements of NLHyp are 1 if nonlinearities were detected for the corresponding output.
A value of 0 indicates that nonlinearities were not detected.
Estimated standard deviation of the data explained by the nonlinearity, returned as a vector of
nonnegative scalars with length equal to the number of output channels. The elements of NLValue
are 0 if nonlinearities are not detected for the corresponding output.
                                                                                                 1-677
1   Functions
          Regressors that should enter nonlinearly in the model, returned as a vector of indices for single
          output models. For multi-output models, NLRegs is returned as a cell array, with elements
          corresponding to each output channel. NLRegs is empty, [], if nonlinearities are not detected.
          Estimated standard deviation of the unexplained error, returned as a vector of nonnegative scalars
          with length equal to the number of output channels. The elements of NoiseSigma are 0 if
          nonlinearities are not detected for the corresponding output.
          Ratio of the test statistic and the detection threshold, returned as a vector with length equal to the
          number of output channels. Use the elements of DetectRatio to assess the reliability of the
          nonlinearity detection test for the corresponding output:
          Algorithms
          isnlarx estimates a nonlinear ARX model using the given data and a treepartition nonlinearity
          estimator.
The estimation data can be described as Y(t) = L(t) + Fn(t) + E(t), where:
          • L(t) is the portion of the data explained by the linear function of the nonlinear ARX model.
          • Fn(t) is the portion of the data explained by the nonlinear function of the nonlinear ARX model.
            The output argument NLValue is an estimate of the standard deviation of Fn(t). If the nonlinear
            function explains a significant portion of the data beyond the data explained by the linear function,
            a nonlinearity is detected.
          • E(t) is the remaining error that is unexplained by the nonlinear ARX model and is typically white
            noise. The output argument NoiseSigma is an estimate of the standard deviation of E(t).
          See Also
          getreg | idnlarx | nlarx | treepartition
          Topics
          “Structure of Nonlinear ARX Models”
Introduced in R2007a
1-678
                                                                                               isproper
isproper
Determine if dynamic system model is proper
Syntax
B = isproper(sys)
B = isproper(sys,'elem')
[B,sysr] = isproper(sys)
Description
B = isproper(sys) returns a logical value of 1 (true) if the dynamic system model sys is proper
and a logical value of 0 (false) otherwise.
A proper model has relative degree ≤ 0 and is causal. SISO transfer functions and zero-pole-gain
models are proper if the degree of their numerator is less than or equal to the degree of their
denominator (in other words, if they have at least as many poles as zeroes). MIMO transfer functions
are proper if all their SISO entries are proper. Regular state-space models (state-space models having
no E matrix) are always proper. A descriptor state-space model that has an invertible E matrix is
always proper. A descriptor state-space model having a singular (non-invertible) E matrix is proper if
the model has at least as many poles as zeroes.
If sys is a model array, then B is 1 if all models in the array are proper.
B = isproper(sys,'elem') checks each model in a model array sys and returns a logical array
of the same size as sys. The logical array indicates which models in sys are proper.
[B,sysr] = isproper(sys) also returns an equivalent model sysr with fewer states (reduced
order) and a non-singular E matrix, if sys is a proper descriptor state-space model with a non-
invertible E matrix. If sys is not proper, sysr = sys.
Examples
H1 = tf([1 0],1);
B1 = logical
   0
SISO transfer functions are proper if the degree of their numerator is less than or equal to the degree
of their denominator That is, if the transfer function has at least as many poles as zeroes. Since H1
has one zero and no poles, the isproper command returns 0.
                                                                                                1-679
1   Functions
Now create a transfer function with one pole and one zero, H2 = s/(s + 1)
B2 = isproper(H2)
          B2 = logical
             1
          Combining state-space models sometimes yields results that include more states than necessary. Use
          isproper to compute an equivalent lower-order model.
          [isprop,Hr] = isproper(H);
          size(Hr)
          bodeplot(H,Hr,'r--')
          legend('original','reduced')
1-680
                                                                                              isproper
References
[1] Varga, Andràs. "Computation of irreducible generalized state-space realizations." Kybernetika
        26.2 (1990): 89-106.
See Also
dss | ss
                                                                                               1-681
1   Functions
          isreal
          Determine whether model parameters or data values are real
          Syntax
          isreal(Data)
          isreal(Model)
          Description
          isreal(Data) returns 1 if all signals of the data set are real. Data is an iddata object.
          isreal(Model) returns 1 if all parameters of the model are real. Model is any linear identified
          model.
          See Also
          realdata
1-682
                                                                                            issiso
issiso
Determine if dynamic system model is single-input/single-output (SISO)
Syntax
issiso(sys)
Description
issiso(sys) returns a logical value of 1 (true) if the dynamic system model sys is SISO and a
logical value of 0 (false) otherwise.
See Also
isempty | size
Introduced in R2012a
                                                                                           1-683
1   Functions
          isstable
          Determine if dynamic system model is stable
          Syntax
          B = isstable(sys)
          B = isstable(sys,'elem')
          Description
          B = isstable(sys) returns a logical value of 1 (true) if the dynamic system model (Control
          System Toolbox) sys has stable dynamics, and a logical value of 0 (false) otherwise. If sys is a
          model array, then the function returns 1 only if all the models in sys are stable.
isstable returns a logical value of 1 (true) for stability of a dynamic system if:
          • In continuous-time systems, all the poles lie in the open left half of the complex plane.
          • In discrete-time systems, all the poles lie inside the open unit disk.
isstable is supported only for analytical models with a finite number of poles.
          B = isstable(sys,'elem') returns a logical array of the same dimensions as the model array
          sys. The logical array indicates which models in sys are stable.
Examples
          Determine the stability of this discrete-time SISO transfer function model with a sample time of 0.1
          seconds.
                              2z
                sys z =     3
                          4z + 3z − 1
sys = tf([2,0],[4,0,3,-1],0.1);
P = abs(pole(sys))
P = 3×1
                0.9159
                0.9159
                0.2980
1-684
                                                                                                  isstable
All the poles of the transfer function model have a magnitude less than 1, so all the poles lie within
the open unit disk and the system is stable.
B = isstable(sys)
B = logical
   1
                             2
    sys s =
               s + 2 + 3j s + 2 − 3j s − 0.5
Create the model as a zpk model object by specifying the zeros, poles, and gain.
sys = zpk([],[-2-3*j,-2+3*j,0.5],2);
Because one pole of the model lies in the right half of the complex plane, the system is unstable.
B = isstable(sys)
B = logical
   0
Determine the stability of an array of SISO transfer function models with poles varying from -2 to 2.
      1   1  1  1   1
        ,   , ,   ,
     s+2 s+1 s s−1 s−2
To create the array, first initialize an array of dimension [length(a),1] with zero-valued SISO
transfer functions.
a = [-2:2];
sys = tf(zeros(1,1,length(a)));
                                                                                                  1-685
1   Functions
          for j = 1:length(a)
              sys(1,1,j) = tf(1,[1 -a(j)]);
          end
          isstable can tell you whether all the models in model array are stable or each individual model is
          stable.
          B_all = logical
             0
          By default, isstable returns a single logical value that is 1 (true) only if all models in the array are
          stable. sys contains some models with nonnegative poles, which are not stable. Therefore, isstable
          returns 0 (false) for the entire array.
          Examine the stability of each model in the array by using 'elem' flag.
          B_elem = isstable(sys,'elem')
                1
                1
                0
                0
                0
          The function returns an array of logical values that indicate the stability of the corresponding entry in
          the model array. For example, B_elem(2) is 1, which indicates that the second model in the array,
          sys(1,1,2) is stable. This is because sys(1,1,2) has a pole at -1.
          Input Arguments
          sys — Dynamic system
          dynamic system model | model array
          Dynamic system, specified as a SISO or MIMO dynamic system model or an array of SISO or MIMO
          dynamic system models. Dynamic systems that you can use include continuous-time or discrete-time
          numeric LTI models such as tf, zpk, or ss models.
          If sys is a generalized state-space model genss or an uncertain state-space model uss, isstable
          checks the stability of the current or nominal value of sys.
If sys is an array of models, isstable checks the stability of every model in the array.
          • If you use B = isstable(sys), the output is 1 (true) only if all the models in the array are
            stable.
          • If you use B = isstable(sys,'elem'), the output is a logical array, the entries of which
            indicate the stability of the corresponding entry in the model array.
For more information on model arrays, see “Model Arrays” (Control System Toolbox).
1-686
                                                                                              isstable
Output Arguments
B — True or false result
1 | 0 | logical array
True or false result, returned as 1 for a stable model or 0 for an unstable model.
The 'elem' flag causes isstable to return an array of logical values with same dimensions as the
model array. The values in the array indicate the stability of the corresponding entry in the model
array.
See Also
isproper | issiso | pole
Introduced in R2012a
                                                                                               1-687
1   Functions
          ivar
          AR model estimation using instrumental variable method
          Syntax
          sys = ivar(data,na)
          sys = ivar(data,na,nc)
          sys = ivar(data,na,nc,max_size)
          Description
          sys = ivar(data,na) estimates an AR polynomial model, sys, using the instrumental variable
          method and the time series data data. na specifies the order of the A polynomial.
A(q)y(t) = e(t)
          In the above model, e(t) is an arbitrary process, assumed to be a moving average process of order nc,
          possibly time varying. nc is assumed to be equal to na. Instruments are chosen as appropriately
          filtered outputs, delayed nc steps.
sys = ivar(data,na,nc) specifies the value of the moving average process order, nc, separately.
          Input Arguments
          data
na
nc
max_size
max_size specifies the maximum size of any matrix formed by the algorithm for estimation.
1-688
                                                                                                   ivar
Default: 250000
Output Arguments
sys
Examples
Compare spectra for sinusoids in noise, estimated by the IV method and by the forward-backward
least squares method.
References
[1] Stoica, P., et al. Optimal Instrumental Variable Estimates of the AR-parameters of an ARMA
        Process, IEEE Trans. Autom. Control, Volume AC-30, 1985, pp. 1066–1074.
See Also
ar | arx | etfe | idpoly | polyest | spa | spectrum | step
                                                                                                 1-689
1   Functions
          ivstruc
          Compute loss functions for sets of ARX model structures using instrumental variable method
          Syntax
          v = ivstruc(ze,zv,NN)
          v = ivstruc(ze,zv,NN,p,maxsize)
          Description
          v = ivstruc(ze,zv,NN) computes the loss functions for sets of single-output ARX model
          structures. NN is a matrix that defines a number of different structures of the ARX type. Each row of
          NN is of the form
nn = [na nb nk]
          with the same interpretation as described for arx. See struc for easy generation of typical NN
          matrices.
          ze and zv are iddata objects containing input-output data. Only time-domain data is supported.
          Models for each model structure defined in NN are estimated using the instrumental variable (IV)
          method on data set ze. The estimated models are simulated using the inputs from data set zv. The
          normalized quadratic fit between the simulated output and the measured output in zv is formed and
          returned in v. The rows below the first row in v are the transpose of NN, and the last row contains the
          logarithms of the condition numbers of the IV matrix
                ∑ ς(t)φT (t)
          A large condition number indicates that the structure is of unnecessarily high order (see Ljung, L.
          System Identification: Theory for the User, Upper Saddle River, NJ, Prentice-Hall PTR, 1999, p. 498).
          Note The IV method used does not guarantee that the models obtained are stable. The output-error
          fit calculated in v can then be misleading.
Examples
1-690
                                                                                                 ivstruc
load iddata1;
ze = z1(1:150);
zv = z1(151:300);
Generate model-order combinations for estimation, specifying ranges for model orders and delays.
NN = struc(1:3,1:2,2:4);
Estimate ARX models using the instrumental variable method, and compute the loss function for each
model order combination.
V = ivstruc(ze,zv,NN);
Select the model order with the best fit to the validation data.
order = selstruc(V,0);
M = iv4(ze,order);
load iddata1;
ze = z1(1:150);
zv = z1(151:300);
Generate model-order combinations for estimation, specifying ranges for model orders and a delay of
2 for all model configurations.
NN = struc(2:3,1:2,2);
Compute the loss function for each model order combination. Suppress the computation of condition
numbers.
V = ivstruc(ze,zv,NN,0);
Algorithms
A maximum-order ARX model is computed using the least squares method. Instruments are
generated by filtering the input(s) through this model. The models are subsequently obtained by
operating on submatrices in the corresponding large IV matrix.
References
[1] Ljung, L. System Identification: Theory for the User, Upper Saddle River, NJ, Prentice-Hall PTR,
        1999.
See Also
arxstruc | iv4 | selstruc | struc
                                                                                                1-691
1   Functions
1-692
                                                                                                    ivx
ivx
ARX model estimation using instrumental variable method with arbitrary instruments
Syntax
sys = ivx(data,[na nb nk],x)
sys = ivx(data,[na nb nk],x,max_size)
Description
sys = ivx(data,[na nb nk],x) estimates an ARX polynomial model, sys, using the
instrumental variable method with arbitrary instruments. The model is estimated for the time series
data data. [na nb nk] specifies the ARX structure orders of the A and B polynomials and the input
to output delay, expressed in the number of samples.
Input Arguments
data
[na nb nk]
x is a matrix containing the arbitrary instruments for use in the instrumental variable method.
x must be of the same size as the output data, data.y. For multi-experiment data, specify x as a cell
array with one entry for each experiment.
                                                                                                  1-693
1   Functions
The instruments used are analogous to the regression vector, with y replaced by x.
max_size
max_size specifies the maximum size of any matrix formed by the algorithm for estimation.
Default: 250000
          Output Arguments
          sys
          ARX model that fits the estimation data, returned as a discrete-time idpoly object. This model is
          created using the specified model orders, delays, and estimation options. ivx does not return any
          estimated covariance information for sys.
          Information about the estimation results and options used is stored in the Report property of the
          model. Report has the following fields:
           Report      Description
           Field
           Status      Summary of the model status, which indicates whether the model was created by
                       construction or obtained by estimation.
           Method      Estimation command used.
           InitialCo Handling of initial conditions during model estimation, returned as one of the following
           ndition   values:
                       This field is especially useful to view how the initial conditions were handled when the
                       InitialCondition option in the estimation option set is 'auto'.
1-694
                                                                                                   ivx
Report       Description
Field
Fit          Quantitative assessment of the estimation, returned as a structure. See “Loss Function
             and Model Quality Metrics” for more information on these quality metrics. The
             structure has the following fields:
             Field         Description
             FitPerce Normalized root mean squared error (NRMSE) measure of how well the
             nt       response of the model fits the estimation data, expressed as the
                      percentage fit = 100(1-NRMSE).
             LossFcn       Value of the loss function when the estimation completes.
             MSE           Mean squared error (MSE) measure of how well the response of the
                           model fits the estimation data.
             FPE           Final prediction error for the model.
             AIC           Raw Akaike Information Criteria (AIC) measure of model quality.
             AICc          Small sample-size corrected AIC.
             nAIC          Normalized AIC.
             BIC           Bayesian Information Criteria (BIC).
Parameter Estimated values of model parameters.
s
OptionsUs Option set used for estimation. If no custom options were configured, this is a set of
ed        default options. See arxOptions for more information.
RandState State of the random number stream at the start of estimation. Empty, [], if
          randomization was not used during estimation. For more information, see rng in the
          MATLAB documentation.
                                                                                              1-695
1   Functions
           Report      Description
           Field
           DataUsed    Attributes of the data used for estimation, returned as a structure with the following
                       fields:
                        Field        Description
                        Name         Name of the data set.
                        Type         Data type.
                        Length       Number of data samples.
                        Ts           Sample time.
                        InterSam Input intersample behavior, returned as one of the following values:
                        ple
                                 • 'zoh' — Zero-order hold maintains a piecewise-constant input signal
                                    between samples.
                                     • 'foh' — First-order hold maintains a piecewise-linear input signal
                                       between samples.
                                     • 'bl' — Band-limited behavior specifies that the continuous-time input
                                       signal has zero power above the Nyquist frequency.
                        InputOff Offset removed from time-domain input data during estimation. For
                        set      nonlinear models, it is [].
                        OutputOf Offset removed from time-domain output data during estimation. For
                        fset     nonlinear models, it is [].
          Tips
          • Use iv4 first for IV estimation to identify ARX polynomial models where the instruments x are
            chosen automatically. Use ivx for nonstandard situations. For example, when there is feedback
            present in the data, or, when other instruments need to be tried. You can also use iv to
            automatically generate instruments from certain custom defined filters.
          References
          [1] Ljung, L. System Identification: Theory for the User, page 222, Upper Saddle River, NJ, Prentice-
                  Hall PTR, 1999.
          See Also
          arx | arxstruc | idpoly | iv4 | ivar | polyest
1-696
                                                                                                  iv4
iv4
ARX model estimation using four-stage instrumental variable method
Syntax
sys    =   iv4(data,[na nb nk])
sys    =   iv4(data,'na',na,'nb',nb,'nk',nk)
sys    =   iv4( ___ ,Name,Value)
sys    =   iv4( ___ ,opt)
Description
sys = iv4(data,[na nb nk]) estimates an ARX polynomial model, sys, using the four-stage
instrumental variable method, for the data object data. [na nb nk] specifies the ARX structure
orders of the A and B polynomials and the input to output delay. The estimation algorithm is
insensitive to the color of the noise term.
sys = iv4( ___ ,Name,Value) estimates an ARX polynomial with additional options specified by
one or more Name,Value pair arguments.
sys = iv4( ___ ,opt) uses the option set, opt, to configure the estimation behavior.
Input Arguments
data
[na nb nk]
For multi-output model, [na nb nk] contains one row for every output. In particular, specify na as
an Ny-by-Ny matrix, where each entry is the polynomial order relating the corresponding output pair.
                                                                                              1-697
1   Functions
          Here, Ny is the number of outputs. Specify nb and nk as Ny-by-Nu matrices, where Nu is the number
          of inputs. For more details on the ARX model structure, see arx.
opt
Estimation options.
opt is an options set that configures the estimation options. These options include:
          • estimation focus
          • handling of initial conditions
          • handling of data offsets
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
InputDelay
          Input delay for each input channel, specified as a scalar value or numeric vector. For continuous-time
          systems, specify input delays in the time unit stored in the TimeUnit property. For discrete-time
          systems, specify input delays in integer multiples of the sample time Ts. For example, InputDelay =
          3 means a delay of three sample times.
          For a system with Nu inputs, set InputDelay to an Nu-by-1 vector. Each entry of this vector is a
          numerical value that represents the input delay for the corresponding input channel.
You can also set InputDelay to a scalar value to apply the same delay to all channels.
Default: 0
IODelay
          Transport delays. IODelay is a numeric array specifying a separate transport delay for each input/
          output pair.
          For continuous-time systems, specify transport delays in the time unit stored in the TimeUnit
          property. For discrete-time systems, specify transport delays in integer multiples of the sample time,
          Ts.
          For a MIMO system with Ny outputs and Nu inputs, set IODelay to a Ny-by-Nu array. Each entry of
          this array is a numerical value that represents the transport delay for the corresponding input/output
          pair. You can also set IODelay to a scalar value to apply the same delay to all input/output pairs.
IntegrateNoise
1-698
                                                                                                       iv4
                                      1
      A(q)y(t) = B(q)u(t − nk) +           e(t)
                                   1 − q−1
            1
where,           is the integrator in the noise channel, e(t).
         1 − q−1
Output Arguments
sys
ARX model that fits the estimation data, returned as a discrete-time idpoly object. This model is
created using the specified model orders, delays, and estimation options.
Information about the estimation results and options used is stored in the Report property of the
model. Report has the following fields:
Report          Description
Field
Status          Summary of the model status, which indicates whether the model was created by
                construction or obtained by estimation.
Method          Estimation command used.
InitialCo Handling of initial conditions during model estimation, returned as one of the following
ndition   values:
                This field is especially useful to view how the initial conditions were handled when the
                InitialCondition option in the estimation option set is 'auto'.
                                                                                                   1-699
1   Functions
           Report       Description
           Field
           Fit          Quantitative assessment of the estimation, returned as a structure. See “Loss Function
                        and Model Quality Metrics” for more information on these quality metrics. The
                        structure has the following fields:
                        Field         Description
                        FitPerce Normalized root mean squared error (NRMSE) measure of how well the
                        nt       response of the model fits the estimation data, expressed as the
                                 percentage fit = 100(1-NRMSE).
                        LossFcn       Value of the loss function when the estimation completes.
                        MSE           Mean squared error (MSE) measure of how well the response of the
                                      model fits the estimation data.
                        FPE           Final prediction error for the model.
                        AIC           Raw Akaike Information Criteria (AIC) measure of model quality.
                        AICc          Small sample-size corrected AIC.
                        nAIC          Normalized AIC.
                        BIC           Bayesian Information Criteria (BIC).
           Parameter Estimated values of model parameters.
           s
           OptionsUs Option set used for estimation. If no custom options were configured, this is a set of
           ed        default options. See iv4Options for more information.
           RandState State of the random number stream at the start of estimation. Empty, [], if
                     randomization was not used during estimation. For more information, see rng in the
                     MATLAB documentation.
1-700
                                                                                                       iv4
Report        Description
Field
DataUsed      Attributes of the data used for estimation, returned as a structure with the following
              fields:
              Field         Description
              Name          Name of the data set.
              Type          Data type.
              Length        Number of data samples.
              Ts            Sample time.
              InterSam Input intersample behavior, returned as one of the following values:
              ple
                       • 'zoh' — Zero-order hold maintains a piecewise-constant input signal
                          between samples.
                            • 'foh' — First-order hold maintains a piecewise-linear input signal
                              between samples.
                            • 'bl' — Band-limited behavior specifies that the continuous-time input
                              signal has zero power above the Nyquist frequency.
              InputOff Offset removed from time-domain input data during estimation. For
              set      nonlinear models, it is [].
              OutputOf Offset removed from time-domain output data during estimation. For
              fset     nonlinear models, it is [].
Examples
load iddata7;
This data has two inputs, u1 and u2, and one output, y1.
Specify the ARX model orders, using the same orders for both inputs.
na = 2;
nb = [2 2];
Specify a delay of 2 samples for input u2 and no delay for input u1.
nk = [0 2];
m = iv4(z7,[na nb nk]);
                                                                                                 1-701
1   Functions
          Algorithms
          Estimation is performed in 4 stages. The first stage uses the arx function. The resulting model
          generates the instruments for a second-stage IV estimate. The residuals obtained from this model are
          modeled as a high-order AR model. At the fourth stage, the input-output data is filtered through this
          AR model and then subjected to the IV function with the same instrument filters as in the second
          stage.
          For the multiple-output case, optimal instruments are obtained only if the noise sources at the
          different outputs have the same color. The estimates obtained with the routine are reasonably
          accurate, however, even in other cases.
          References
          [1] Ljung, L. System Identification: Theory for the User, equations (15.21) through (15.26), Upper
                  Saddle River, NJ, Prentice-Hall PTR, 1999.
          See Also
          armax | arx | bj | idpoly | iv4Options | ivx | n4sid | oe | polyest
1-702
                                                                                              iv4Options
iv4Options
Option set for iv4
Syntax
opt = iv4Options
opt = iv4Options(Name,Value)
Description
opt = iv4Options creates the default options set for iv4.
opt = iv4Options(Name,Value) creates an option set with the options specified by one or more
Name,Value pair arguments.
Input Arguments
Name-Value Pair Arguments
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Handling of initial conditions during estimation, specified as one of the following values:
Error to be minimized in the loss function during estimation, specified as the comma-separated pair
consisting of 'Focus' and one of the following values:
• 'prediction' — The one-step ahead prediction error between measured and predicted outputs
  is minimized during estimation. As a result, the estimation focuses on producing a good predictor
  model.
• 'simulation' — The simulation error between measured and simulated outputs is minimized
  during estimation. As a result, the estimation focuses on making a good fit for simulation of model
  response with the current inputs.
The Focus option can be interpreted as a weighting filter in the loss function. For more information,
see “Loss Function and Model Quality Metrics”.
                                                                                                 1-703
1   Functions
          Weighting prefilter applied to the loss function to be minimized during estimation. To understand the
          effect of WeightingFilter on the loss function, see “Loss Function and Model Quality Metrics”.
                Passbands are expressed in rad/TimeUnit for time-domain data and in FrequencyUnit for
                frequency-domain data, where TimeUnit and FrequencyUnit are the time and frequency units
                of the estimation data.
          • SISO filter — Specify a single-input-single-output (SISO) linear filter in one of the following ways:
                   This option calculates the weighting function as a product of the filter and the input spectrum
                   to estimate the transfer function.
          • Weighting vector — Applicable for frequency-domain data only. Specify a column vector of
            weights. This vector must have the same length as the frequency vector of the data set,
            Data.Frequency. Each input and output response in the data is multiplied by the corresponding
            weight at that frequency.
          Control whether to enforce stability of estimated model, specified as the comma-separated pair
          consisting of 'EnforceStability' and either true or false.
          Data Types: logical
          If EstimateCovariance is true, then use getcov to fetch the covariance matrix from the
          estimated model.
Specify whether to display the estimation progress, specified as one of the following values:
1-704
                                                                                             iv4Options
• 'on' — Information on model structure and estimation results are displayed in a progress-viewer
  window.
• 'off' — No progress or results information is displayed.
Removal of offset from time-domain input data during estimation, specified as the comma-separated
pair consisting of 'InputOffset' and one of the following:
• A column vector of positive integers of length Nu, where Nu is the number of inputs.
• [] — Indicates no offset.
• Nu-by-Ne matrix — For multi-experiment data, specify InputOffset as an Nu-by-Ne matrix. Nu
  is the number of inputs, and Ne is the number of experiments.
Each entry specified by InputOffset is subtracted from the corresponding input data.
Removal of offset from time-domain output data during estimation, specified as the comma-separated
pair consisting of 'OutputOffset' and one of the following:
Each entry specified by OutputOffset is subtracted from the corresponding output data.
• MaxSize — Specifies the maximum number of elements in a segment when input-output data is
  split into segments.
   Default: 250000
• StabilityThreshold — Specifies thresholds for stability tests.
   • s — Specifies the location of the right-most pole to test the stability of continuous-time models.
     A model is considered stable when its right-most pole is to the left of s.
      Default: 0
   • z — Specifies the maximum distance of all poles from the origin to test stability of discrete-
     time models. A model is considered stable if all poles are within the distance z from the origin.
Default: 1+sqrt(eps)
                                                                                                 1-705
1   Functions
          Output Arguments
          opt — Options set for iv4
          iv4Options option set
Examples
          Create Default Options Set for ARX Model Estimation Using 4-Stage Instrument Variable
          Method
opt = iv4Options;
Specify Options for ARX Model Estimation Using 4-Stage Instrument Variable Method
          Create an options set for iv4 using the 'backcast' algorithm to initialize the state. Set Display to
          'on'.
opt = iv4Options('InitialCondition','backcast','Display','on');
          opt = iv4Options;
          opt.InitialCondition = 'backcast';
          opt.Display = 'on';
          Compatibility Considerations
          Renaming of Estimation and Analysis Options
          The names of some estimation and analysis options were changed in R2018a. Prior names still work.
          For details, see the R2018a release note “Renaming of Estimation and Analysis Options”.
          See Also
          iv4
          Topics
          “Loss Function and Model Quality Metrics”
Introduced in R2012a
1-706
                                                                                               linapp
linapp
Linear approximation of nonlinear ARX and Hammerstein-Wiener models for given input
Syntax
lm = linapp(nlmodel,u)
lm = linapp(nlmodel,umin,umax,nsample)
Description
lm = linapp(nlmodel,u) computes a linear approximation of a nonlinear ARX or Hammerstein-
Wiener model by simulating the model output for the input signal u, and estimating a linear model lm
from u and the simulated output signal. lm is an idpoly model.
Input Arguments
nlmodel
    Name of the idnlarx or idnlhw model object you want to linearize.
u
    Input signal as an iddata object or a real matrix.
Default: 1024.
See Also
idnlarx | idnlarx/findop | idnlarx/linearize | idnlhw | idnlhw/findop | idnlhw/
linearize
Topics
“Linear Approximation of Nonlinear Black-Box Models”
Introduced in R2007a
                                                                                              1-707
1   Functions
          linear
          Class representing linear nonlinearity estimator for nonlinear ARX models
          Syntax
          lin=linear
          lin=linear('Parameters',Par)
          Description
          linear is an object that stores the linear nonlinearity estimator for estimating nonlinear ARX
          models.
          linear Properties
          You can include property-value pairs in the constructor to specify the object.
          After creating the object, you can use get or dot notation to access the object property values. For
          example:
          Examples
          Estimate a nonlinear ARX model using the linear estimator with custom regressors for the following
          system:
1-708
                                                                                                   linear
        'CustomRegressors', {'y(t-1)*u(t-2)','abs(u(t))*u(t-3)'})
% Estimate the model parameters a1, a2, ... a6.
EstimatedModel = nlarx(data, model)
Tutorials
“Estimate Nonlinear ARX Models at the Command Line”
Tips
• linear is a linear (affine) function y = F(x), defined as follows:
F(x) = xL + d
m=idnlarx(orders,[]);
Algorithms
When the Focus option in nlarxOptions is 'prediction', linear uses a fast, noniterative
initialization and iterative search technique for estimating parameters. In most cases, iterative search
requires only a few iterations.
When the idnlarx property Focus='Simulation', linear uses an iterative technique for
estimating parameters.
See Also
customreg | nlarx
Introduced in R2007a
                                                                                                 1-709
1   Functions
          idnlarx/linearize
          Linearize nonlinear ARX model
          Syntax
          SYS = linearize(NLSYS,U0,X0)
          Description
          SYS = linearize(NLSYS,U0,X0) linearizes a nonlinear ARX model about the specified operating
          point U0 and X0. The linearization is based on tangent linearization. For more information about the
          definition of states for idnlarx models, see “Definition of idnlarx States” on page 1-527.
          Input Arguments
          • NLSYS: idnlarx model.
          • U0: Matrix containing the constant input values for the model.
          • X0: Model state values. The states of a nonlinear ARX model are defined by the time-delayed
            samples of input and output variables. For more information about the states of nonlinear ARX
            models, see the getDelayInfo reference page.
Note To estimate U0 and X0 from operating point specifications, use the findop command.
          Output Arguments
          • SYS is an idss model.
When the Control System Toolbox product is installed, SYS is an LTI object.
Examples
          Linearize a nonlinear ARX model around an operating point corresponding to a simulation snapshot
          at a specific time.
1-710
                                                                                      idnlarx/linearize
step(nlsys, 20)
stepinput = iddata([],[zeros(10,1);ones(200,1)],nlsys.Ts);
[x,u] = findop(nlsys,'snapshot',20,stepinput);
Linearize the model about the operating point corresponding to the model snapshot at T = 20.
sys = linearize(nlsys,u,x);
Apply a small perturbation delta_u to the steady-state input of the nonlinear model nlsys. If the
linear approximation is accurate, the following should match:
• The response of the nonlinear model y_nl to an input that is the sum of the equilibrium level and
  the perturbation delta_u .
• The sum of the response of the linear model to a perturbation input delta_u and the output
  equilibrium level.
                                                                                               1-711
1   Functions
          For a nonlinear system with a steady-state input of 1 and a steady-state output of 0.8383, compute
          the steady-state response y_nl to the perturbed input u_nl . Use equilibrium state values x
          computed previously as initial conditions.
          u_nl = 1 + delta_u;
          y_nl = sim(nlsys,u_nl,x);
Compute response of linear model to perturbation input and add it to the output equilibrium level.
          time = [0:0.1:19.9]';
          plot(time,y_nl,time,y_lin)
          legend('Nonlinear response','Linear response about op. pt.')
          title(['Nonlinear and linear model response for small step input'])
          Algorithms
          The following equations govern the dynamics of an idnlarx model:
1-712
                                                                                             idnlarx/linearize
where X(t) is a state vector, u(t) is the input, and y(t) is the output. A and B are constant matrices. u(t)
is [y(t), u(t)]T.
y* = f(X*, u*)
where X* and u* are the state vector and input at the operating point.
where
Note For linear approximations over larger input ranges, use linapp.
See Also
getDelayInfo | idnlarx | idnlarx/findop | linapp
Topics
“Linear Approximation of Nonlinear Black-Box Models”
Introduced in R2014b
                                                                                                      1-713
1   Functions
          idnlhw/linearize
          Linearize Hammerstein-Wiener model
          Syntax
          SYS = linearize(NLSYS,U0)
          SYS = linearize(NLSYS,U0,X0)
          Description
          SYS = linearize(NLSYS,U0) linearizes a Hammerstein-Wiener model around the equilibrium
          operating point. When using this syntax, equilibrium state values for the linearization are calculated
          automatically using U0.
          SYS = linearize(NLSYS,U0,X0) linearizes the idnlhw model NLSYS around the operating point
          specified by the input U0 and state values X0. In this usage, X0 need not contain equilibrium state
          values. For more information about the definition of states for idnlhw models, see “Definition of
          idnlhw States” on page 1-557.
          The output is a linear model that is the best linear approximation for inputs that vary in a small
          neighborhood of a constant input u(t) = U. The linearization is based on tangent linearization.
          Input Arguments
          • NLSYS: idnlhw model.
          • U0: Matrix containing the constant input values for the model.
          • X0: Operating point state values for the model.
Note To estimate U0 and X0 from operating point specifications, use the findop command.
          Output Arguments
          • SYS is an idss model.
When the Control System Toolbox product is installed, SYS is an LTI object.
          Algorithms
          The idnlhw model structure represents a nonlinear system using a linear system connected in series
          with one or two static nonlinear systems. For example, you can use a static nonlinearity to simulate
          saturation or dead-zone behavior. The following figure shows the nonlinear system as a linear system
          that is modified by static input and output nonlinearities, where function f represents the input
          nonlinearity, g represents the output nonlinearity, and [A,B,C,D] represents a state-space
          parameterization of the linear model.
1-714
                                                                                        idnlhw/linearize
v(t) = f(u(t))
X(t+1) = AX(t)+Bv(t)
w(t) = CX(t)+Dv(t)
y(t) = g(w(t))
where
The linear approximation of the Hammerstein-Wiener model around an operating point (X*, u*) is as
follows:
where
where y* is the output of the model corresponding to input u* and state vector X*, v* = f(u*), and w*
is the response of the linear model for input v* and state X*.
Note For linear approximations over larger input ranges, use linapp. For more information, see the
linapp reference page.
See Also
idnlhw | idnlhw/findop | linapp
Topics
“Linear Approximation of Nonlinear Black-Box Models”
Introduced in R2014b
                                                                                                1-715
1   Functions
          lsim
          Simulate time response of dynamic system to arbitrary inputs
          Syntax
          lsim(sys,u,t)
          lsim(sys,u,t,x0)
          lsim(sys,u,t,x0,method)
          lsim(sys1,...,sysn,u,t)
          lsim(sys1,LineSpec1,...,sysN,LineSpecN,u,t)
          y = lsim( ___ )
          [y,t,x] = lsim( ___ )
          lsim(sys)
          Description
          lsim simulates the (time) response of continuous or discrete linear systems to arbitrary inputs. When
          invoked without left-hand arguments, lsim plots the response on the screen.
          lsim(sys,u,t) produces a plot of the time response of the dynamic system model sys to the input
          history, t,u. The vector t specifies the time samples for the simulation (in system time units, specified
          in the TimeUnit property of sys), and consists of regularly spaced time samples:
t = 0:dt:Tfinal
          The input u is an array having as many rows as time samples (length(t)) and as many columns as
          system inputs. For instance, if sys is a SISO system, then u is a t-by-1 vector. If sys has three inputs,
          then u is a t-by-3 array. Each row u(i,:) specifies the input value(s) at the time sample t(i). The
          signal u also appears on the plot.
          The model sys can be continuous or discrete, SISO or MIMO. In discrete time, u must be sampled at
          the same rate as the system. In this case, the input t is redundant and can be omitted or set to an
          empty matrix. In continuous time, the time sampling dt = t(2)-t(1) is used to discretize the
          continuous model. If dt is too large (undersampling), lsim issues a warning suggesting that you use
          a more appropriate sample time, but will use the specified sample time. See “Algorithms” on page 1-
          719 for a discussion of sample times.
          lsim(sys,u,t,x0) further specifies an initial condition x0 for the system states. This syntax
          applies only when sys is a state-space model. x0 is a vector whose entries are the initial values of the
          corresponding states of sys.
          If you do not specify a method, lsim selects the interpolation method automatically based on the
          smoothness of the signal u.
1-716
                                                                                                 lsim
lsim(sys1,...,sysn,u,t) simulates the responses of several dynamic system models to the same
input history t,u and plots these responses on a single figure. You can also use the x0 and method
input arguments when computing the responses of multiple models.
lsim(sys1,'y:',sys2,'g--',u,t,x0)
For more information about configuring this argument, see the LineSpec input argument of the
plot function.
y = lsim( ___ ) returns the system response y, sampled at the same times as the input (t). The
output y is an array having as many rows as time samples (length(t)) and as many columns as
system outputs. No plot is drawn on the screen. You can use this syntax with any of the input
arguments described in previous syntaxes except the LineSpec arguments.
[y,t,x] = lsim( ___ ) also returns the time vector t used for simulation and the state trajectories
x (for state-space models only). The output x has as many rows as time samples (length(t)) and as
many columns as system states. You can use this syntax with any of the input arguments described in
previous syntaxes except the LineSpec arguments.
lsim(sys) opens the Linear Simulation Tool GUI. For more information about working with this
GUI, see Working with the Linear Simulation Tool (Control System Toolbox).
Examples
Simulate and plot the response of the following system to a square wave with period of four seconds:
           2s2 + 5s + 1
            s2 + 2s + 3
    H(s) =              .
                s−1
             s2 + s + 5
Create the transfer function, and generate the square wave with gensig. Sample every 0.1 second
during 10 seconds.
lsim(H,u,t)
                                                                                              1-717
1   Functions
The plot displays both the applied signal and the response.
z is an iddata object that stores the 1-input 2-output estimation data with sample time 0.1 seconds.
sys is the estimated model and x0 are the estimated initial states.
          Simulate the response of sys using the same input data as the one used for estimation and the initial
          states returned by the estimation command.
          [y,t,x] = lsim(sys,z.InputData,[],x0);
Here, y is the system response, t is the time vector used for simulation, and x is the state trajectory.
Compare the simulated response y to measured response z.OutputData for both outputs.
1-718
                                                                                                       lsim
subplot(211), plot(t,z.OutputData(:,1),'k',t,y(:,1),'r')
legend('Measured','Simulated')
subplot(212), plot(t,z.OutputData(:,2),'k',t,y(:,2),'r')
legend('Measured','Simulated')
Algorithms
Discrete-time systems are simulated with ltitr (state space) or filter (transfer function and zero-
pole-gain).
Continuous-time systems are discretized with c2d using either the 'zoh' or 'foh' method ('foh' is
used for smooth input signals and 'zoh' for discontinuous signals such as pulses or square waves).
The sample time is set to the spacing dt between the user-supplied time samples t.
The choice of sample time can drastically affect simulation results. To illustrate why, consider the
second-order model
                  ω2
    H(s) =                , ω = 62.83
             s2 + 2s + ω2
To simulate its response to a square wave with period 1 second, you can proceed as follows:
w2 = 62.83^2;
h = tf(w2,[1 2 w2]);
t = 0:0.1:5;                      % vector of time samples
                                                                                                  1-719
1   Functions
To improve on this response, discretize H(s) using the recommended sample time:
          dt = 0.016;
          ts = 0:dt:5;
          us = (rem(ts,1) >= 0.5);
          hd = c2d(h,dt);
          lsim(hd,us,ts)
1-720
                                                                                                   lsim
This response exhibits strong oscillatory behavior that is hidden in the undersampled version.
See Also
Linear System Analyzer | gensig | impulse | initial | lsiminfo | sim | step
Introduced in R2012a
                                                                                                 1-721
1   Functions
          lsiminfo
          Compute linear response characteristics
          Syntax
          S = lsiminfo(y,t,yfinal)
          S = lsiminfo(y,t)
          S = lsiminfo(...,'SettlingTimeThreshold',ST)
          Description
          S = lsiminfo(y,t,yfinal) takes the response data (t,y) and a steady-state value yfinal and
          returns a structure S containing the following performance indicators:
          For SISO responses, t and y are vectors with the same length NS. For responses with NY outputs,
          you can specify y as an NS-by-NY array and yfinal as a NY-by-1 array. lsiminfo then returns an
          NY-by-1 structure array S of performance metrics for each output channel.
Examples
                               s−1
                H(s) =
                         s3 + 2s2 + 3s + 4
[y,t] = impulse(sys);
impulse returns the output response y and the time vector t used for simulation.
1-722
                                                                                              lsiminfo
s = lsiminfo(y,t,0)
You can plot the impulse response and verify these response characteristics. For example, the time at
which the minimum response value (MinTime) is reached is approximately 2 seconds.
impulse(sys)
See Also
impulse | initial | lsim | stepinfo
Introduced in R2012a
                                                                                               1-723
1   Functions
          lsimplot
          Simulate response of dynamic system to arbitrary inputs and return plot handle
          Syntax
          h = lsimplot(sys)
          lsimplot(sys1,sys2,...)
          lsimplot(sys,u,t)
          lsimplot(sys,u,t,x0)
          lsimplot(sys1,sys2,...,u,t,x0)
          lsimplot(AX,...)
          lsimplot(..., plotoptions)
          lsimplot(sys,u,t,x0,'zoh')
          lsimplot(sys,u,t,x0,'foh')
          Description
          h = lsimplot(sys) opens the Linear Simulation Tool for the dynamic system model sys, which
          enables interactive specification of driving input(s), the time vector, and initial state. It also returns
          the plot handle h. You can use this handle to customize the plot with the getoptions and
          setoptions commands. Type
          help timeoptions
          lsimplot(sys1,sys2,...) opens the Linear Simulation Tool for multiple models sys1,sys2,....
          Driving inputs are common to all specified systems but initial conditions can be specified separately
          for each.
          lsimplot(sys,u,t) plots the time response of the model sys to the input signal described by u
          and t. The time vector t consists of regularly spaced time samples (in system time units, specified in
          the TimeUnit property of sys). For MIMO systems, u is a matrix with as many columns as inputs and
          whose ith row specifies the input value at time t(i). For SISO systems u can be specified either as a
          row or column vector. For example,
          t = 0:0.01:5;
          u = sin(t);
          lsimplot(sys,u,t)
simulates the response of a single-input model sys to the input u(t)=sin(t) during 5 seconds.
          For discrete-time models, u should be sampled at the same rate as sys (t is then redundant and can
          be omitted or set to the empty matrix).
          For continuous-time models, choose the sampling period t(2)-t(1) small enough to accurately
          describe the input u. lsim issues a warning when u is undersampled, and hidden oscillations can
          occur.
          lsimplot(sys,u,t,x0) specifies the initial state vector x0 at time t(1) (for state-space models
          only). x0 is set to zero when omitted.
1-724
                                                                                              lsimplot
lsimplot(sys1,'r',sys2,'y--',sys3,'gx',u,t)
lsimplot(..., plotoptions) plots the initial condition response with the options specified in
plotoptions. Type
help timeoptions
See Also
getoptions | lsim | setoptions
Introduced in R2012a
                                                                                               1-725
1   Functions
          mag2db
          Convert magnitude to decibels (dB)
          Syntax
          ydb = mag2db(y)
          Description
          ydb = mag2db(y) returns the corresponding decibel (dB) value ydb for a given magnitude y. The
          relationship between magnitude and decibels is ydb = 20 log10(y).
          See Also
          db2mag
Introduced in R2008a
1-726
                                                                                        merge (iddata)
merge (iddata)
Merge data sets into iddata object
Syntax
dat = merge(dat1,dat2,....,datN)
Description
dat collects the data sets in dat1, ...,datN into one iddata object, with several experiments.
The number of experiments in dat will be the sum of the number of experiments in datk. For the
merging to be allowed, a number of conditions must be satisfied:
• All of datk must have the same number of input channels, and the InputNames must be the
  same.
• All of datk must have the same number of output channels, and the OutputNames must be the
  same. If some input or output channel is lacking in one experiment, it can be replaced by a vector
  of NaNs to conform with these rules.
• If the ExperimentNames of datk have been specified as something other than the default
  'Exp1', 'Exp2', etc., they must all be unique. If default names overlap, they are modified so that
  dat will have a list of unique ExperimentNames.
The sampling intervals, the number of observations, and the input properties (Period,
InterSample) might be different in the different experiments.
You can retrieve the individual experiments by using the command getexp. You can also retrieve
them by subreferencing with a fourth index.
dat1 = dat(:,:,:,ExperimentNumber)
or
dat1 = dat(:,:,:,ExperimentName)
Storing multiple experiments as one iddata object can be very useful for handling experimental data
that has been collected on different occasions, or when a data set has been split up to remove “bad”
portions of the data. All the toolbox routines accept multiple-experiment data.
Examples
Remove bad portions of data to estimate models without the bad data destroying the estimate.
load iddemo8;
plot(dat);
                                                                                               1-727
1   Functions
          Bad portions of data are detected around sample 250 to 280 and between samples 600 to 650. Cut
          out these bad portions to form a multiple-experiment data set and merge the data.
dat = merge(dat(1:250),dat(281:600),dat(651:1000));
          You can use the first two experiments to estimate a model and the third experiment to validate the
          model.
          dat_est = getexp(dat,[1,2]);
          m = ssest(dat_est,2);
          dat_val = getexp(dat,3);
          See Also
          getexp | iddata | merge
          Topics
          “Dealing with Multi-Experiment Data and Merging Models”
          “Create Multiexperiment Data at the Command Line”
1-728
                                                                                               merge
merge
Merge estimated models
Syntax
m = merge(m1,m2,....,mN)
[m,tv] = merge(m1,m2)
Description
m = merge(m1,m2,....,mN) merges estimated models. The models m1,m2,...,mN must all be of
the same structure, just differing in parameter values and covariance matrices. Then m is the merged
model, where the parameter vector is a statistically weighted mean (using the covariance matrices to
determine the weights) of the parameters of mk.
[m,tv] = merge(m1,m2) returns a test variable tv. When two models are merged,
tv is χ2 distributed with n degrees of freedom, if the parameters of m1 and m2 have the same means.
Here n is the length of the parameter vector. A large value of tv thus indicates that it might be
questionable to merge the models.
For idfrd models, merge is a statistical average of two responses in the individual models, weighted
using inverse variances. You can only merge two idfrd models with responses at the same
frequencies and nonzero covariances.
Merging models is an alternative to merging data sets and estimating a model for the merged data.
and
mb = arx(merge(z1,z2),[2 3 4]);
result in models ma and mb that are related and should be close. The difference is that merging the
data sets assumes that the signal-to-noise ratios are about the same in the two experiments. Merging
the models allows one model to be much more uncertain, for example, due to more disturbances in
that experiment. If the conditions are about the same, we recommend that you merge data rather
than models, since this is more efficient and typically involves better conditioned calculations.
See Also
append
Introduced in R2007a
                                                                                              1-729
1   Functions
          midprefs
          Specify location for file containing System Identification app startup information
          Syntax
          midprefs
          midprefs(path)
          Description
          The System Identification app allows a large number of variables for customized choices. These
          include the window layout, the default choices of plot options, and names and directories of the four
          most recent sessions with the System Identification app. This information is stored in the file
          idprefs.mat, which should be placed on the user's MATLABPATH. The default, automatic location
          for this file is in the same folder as the user's startup.m file.
          midprefs is used to select or change the folder where you store idprefs.mat. Either type
          midprefs and follow the instructions, or give the folder name as the argument. Include all folder
          delimiters, as in the PC case:
midprefs('c:\matlab\toolbox\local\')
midprefs('/home/ljung/matlab/')
          See Also
          Apps
          System Identification
1-730
                                                                                              misdata
misdata
Reconstruct missing input and output data
Syntax
Datae = misdata(Data)
Datae = misdata(Data,Model)
Datae = misdata(Data,MaxIterations,Tol)
Description
Datae = misdata(Data) reconstructs missing input and output data. Data is time-domain input-
output data in the iddata object format. Missing data samples (both in inputs and in outputs) are
entered as NaNs. Datae is an iddata object where the missing data has been replaced by reasonable
estimates.
Datae = misdata(Data,Model) specifies a model used for the reconstruction of missing data.
Model is any linear identified model (idtf, idproc, idgrey, idpoly, idss). If no suitable model is
known, it is estimated in an iterative fashion using default order state-space models.
Examples
load('missing_data.mat')
plot(missing_data)
                                                                                              1-731
1   Functions
The output data contains missing data between indices 10 and 100.
          To reconstruct missing data using a specified model, estimate the model using measured data that
          has no missing samples. In this example, estimate a transfer function model with 2 poles.
          data2 = missing_data(101:end);
          model = tfest(data2,2);
datae = misdata(missing_data,model);
plot(missing_data,'b',datae,'--r')
1-732
                                                                                                misdata
If you do not specify a model for reconstructing the data, the software alternates between estimating
missing data and estimating models, based on the current data reconstruction.
Algorithms
For a given model, the missing data is estimated as parameters so as to minimize the output
prediction errors obtained from the reconstructed data. See Section 14.2 in Ljung (1999). Treating
missing outputs as parameters is not the best approach from a statistical point of view, but is a good
approximation in many cases.
When no model is given, the algorithm alternates between estimating missing data and estimating
models, based on the current reconstruction.
See Also
advice | arx | pexcit | tfest
                                                                                                 1-733
1   Functions
          n4sid
          Estimate state-space model using subspace method with time-domain or frequency-domain data
          Syntax
          sys = n4sid(data,nx)
          sys = n4sid(data,nx,Name,Value)
          sys = n4sid( ___ ,opt)
          [sys,x0] = n4sid( ___ )
          Description
          sys = n4sid(data,nx) estimates a discrete-time state-space model sys of order nx using data,
          which can be time-domain or frequency-domain data. sys is a model of the following form:
          A, B, C, D, and K are state-space matrices. u(t) is the input, y(t) is the output, e(t) is the disturbance,
          and x(t) is the vector of nx states.
          All entries of A, B, C, and K are free estimable parameters by default. For dynamic systems, D is fixed
          to zero by default, meaning that the system has no feedthrough. For static systems (nx = 0), D is an
          estimable parameter by default.
          sys = n4sid( ___ ,opt) specifies the estimation options opt. These options can include the initial
          states, estimation objective, and subspace algorithm related choices to be used for estimation.
          Specify opt after any of the previous input-argument combinations.
          [sys,x0] = n4sid( ___ ) returns the value of initial states computed during estimation. You can
          use this syntax with any of the previous input-argument combinations.
Examples
State-Space Model
Estimate a state-space model and compare its response with the measured output.
load iddata1 z1
1-734
                                                                                  n4sid
nx = 4;
sys = n4sid(z1,nx)
sys =
  Discrete-time identified state-space model:
    x(t+Ts) = A x(t) + B u(t) + K e(t)
       y(t) = C x(t) + D u(t) + e(t)
  A =
               x1           x2         x3          x4
   x1      0.8392      -0.3129    0.02105     0.03743
   x2      0.4768       0.6671     0.1428    0.003757
   x3    -0.01951      0.08374   -0.09761       1.046
   x4   -0.003885     -0.02914    -0.8796    -0.03171
  B =
               u1
   x1     0.02635
   x2    -0.03301
   x3   7.256e-05
   x4   0.0005861
  C =
             x1         x2       x3        x4
   y1     69.08      26.64   -2.237   -0.5601
  D =
        u1
   y1    0
  K =
               y1
   x1    0.003282
   x2    0.009339
   x3   -0.003232
   x4    0.003809
Parameterization:
   FREE form (all coefficients in A, B, C free).
   Feedthrough: none
   Disturbance component: estimate
   Number of free coefficients: 28
   Use "idssdata", "getpvec", "getcov" for parameters and their uncertainties.
Status:
Estimated using N4SID on time domain data "z1".
Fit to estimation data: 76.33% (prediction focus)
FPE: 1.21, MSE: 1.087
compare(z1,sys)
                                                                                 1-735
1   Functions
          The plot shows that the fit percentage between the simulated model and the estimation data is
          greater than 70%.
          You can view more information about the estimation by exploring the idss property sys.Report.
          sys.Report
          ans =
                       Status:   'Estimated using N4SID with prediction focus'
                       Method:   'N4SID'
                 InitialState:   'estimate'
                     N4Weight:   'CVA'
                    N4Horizon:   [6 10 10]
                          Fit:   [1x1 struct]
                   Parameters:   [1x1 struct]
                  OptionsUsed:   [1x1 idoptions.n4sid]
                    RandState:   [1x1 struct]
                     DataUsed:   [1x1 struct]
          For example, find out more information about the estimated initial state.
          sys.Report.Parameters.X0
ans = 4×1
                -0.0085
                 0.0052
1-736
                                                                                                 n4sid
   -0.0193
    0.0282
Determine the optimal model order by specifying argument nx as a range from 1 to 10.
nx = 1:10;
sys = n4sid(z1,nx);
An automatically generated plot shows the Hankel singular values for models of the orders specified
by nx.
States with relatively small Hankel singular values can be safely discarded. The suggested default
order choice is 2.
Select the model order in the Chosen Order list and click Apply.
Specify estimation options. Set the weighting scheme 'N4Weight' to 'SSARX' and estimation-status
display option 'Display' to 'on'.
                                                                                               1-737
1   Functions
opt = n4sidOptions('N4Weight','SSARX','Display','on')
                       InitialState:   'estimate'
                           N4Weight:   'SSARX'
                          N4Horizon:   'auto'
                            Display:   'on'
                        InputOffset:   []
                       OutputOffset:   []
                 EstimateCovariance:   1
                       OutputWeight:   []
                              Focus:   'prediction'
                    WeightingFilter:   []
                   EnforceStability:   0
                           Advanced:   [1x1 struct]
          nx = 3;
          sys = n4sid(z2,nx,opt);
          Modify the canonical form of the A, B, and C matrices, include a feedthrough term in the D matrix,
          and eliminate disturbance-model estimation in the K matrix.
Load input-output data and estimate a fourth-order system using the n4sid default options.
          load iddata1 z1
          sys1 = n4sid(z1,4);
Specify the modal form and compare the A matrix with the default A matrix.
          sys2 = n4sid(z1,4,'Form','modal');
          A1 = sys1.A
A1 = 4×4
A2 = sys2.A
A2 = 4×4
                 0.7554    0.3779          0          0
                -0.3779    0.7554          0          0
                      0         0    -0.0669     0.9542
                      0         0    -0.9542    -0.0669
1-738
                                                                                               n4sid
sys3 = n4sid(z1,4,'Feedthrough',1);
D1 = sys1.D
D1 = 0
D3 = sys3.D
D3 = 0.0487
sys4 = n4sid(z1,4,'DisturbanceModel','none');
K1 = sys1.K
K1 = 4×1
    0.0033
    0.0093
   -0.0032
    0.0038
K4 = sys4.K
K4 = 4×1
     0
     0
     0
     0
load iddata1 z1
nx = 2;
sys = n4sid(z1,nx,'Ts',0,'Form','canonical');
Estimate a state-space model from closed-loop data using the subspace algorithm SSARX. This
algorithm is better at capturing feedback effects than other weighting algorithms.
Generate closed-loop estimation data for a second-order system corrupted by white noise.
                                                                                              1-739
1   Functions
          N = 1000;
          K = 0.5;
          rng('default');
          w = randn(N,1);
          z = zeros(N,1);
          u = zeros(N,1);
          y = zeros(N,1);
          e = randn(N,1);
          v = filter([1 0.5],[1 1.5 0.7],e);
          for k = 3:N
             u(k-1) = -K*y(k-2) + w(k);
             u(k-1) = -K*y(k-1) + w(k);
             z(k) = 1.5*z(k-1) - 0.7*z(k-2) + u(k-1) + 0.5*u(k-2);
             y(k) = z(k) + 0.8*v(k);
          end
          dat = iddata(y, u, 1);
          Specify the weighting scheme 'N4weight' used by the N4SID algorithm. Create two option sets. For
          one option set, set 'N4weight' to 'CVA'. For the other option set, set the 'N4weight' to 'SSARX'.
          optCVA = n4sidOptions('N4weight','CVA');
          optSSARX = n4sidOptions('N4weight','SSARX');
          sysCVA = n4sid(dat,2,optCVA);
          sysSSARX = n4sid(dat,2,optSSARX);
Compare the fit of the two models with the estimation data.
compare(dat,sysCVA,sysSSARX);
1-740
                                                                                                  n4sid
As the plot shows, the model estimated using the SSARX algorithm produces a better fit than the
model estimated using the CVA algorithm.
Input Arguments
data — Estimation data
iddata object | frd object | idfrd object
For time-domain estimation, data must be an iddata object containing the input and output signal
values.
Estimation data must be uniformly sampled. By default, the software sets the sample time of the
model to the sample time of the estimation data.
                                                                                              1-741
1   Functions
          For multiexperiment data, the sample times and intersample behavior of all the experiments must
          match.
The domain of your data determines the type of model you can estimate.
          Order of the estimated model, specified as a nonnegative integer or as a vector containing a range of
          positive integers.
          • If you already know what order you want your estimated model to have, specify nx as a scalar.
          • If you want to compare a range of potential orders to choose the most effective order for your
            estimated model, specify that range for nx. n4sid creates a Hankel singular-value plot that shows
            the relative energy contributions of each state in the system. States with relatively small Hankel
            singular values contribute little to the accuracy of the model and can be discarded with little
            impact. The index of the highest state you retain is the model order. The plot window includes a
            suggestion for the order to use. You can accept this suggestion or enter a different order. For an
            example, see “Determine Optimal Estimated Model Order” on page 1-737.
                If you do not specify nx, or if you specify nx as best, the software automatically chooses nx from
                the range 1:10.
          • If you are identifying a static system, set nx to 0.
Estimation options, specified as an n4sidOptions option set. Options specified by opt include:
          • Estimation objective
          • Handling of initial conditions
          • Subspace algorithm-related choices
          For examples showing how to specify options, see “Specify Estimation Options” on page 1-737 and
          “Continuous-Time Canonical-Form Model” on page 1-739.
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
          Example: sys = n4sid(data,nx,'Form','modal')
          Sample time of the estimated model, specified as the comma-separated pair consisting of 'Ts' and
          either 0 or a positive scalar.
1-742
                                                                                                   n4sid
• For continuous-time models, specify 'Ts' as 0. In the frequency domain, using continuous-time
  frequency-domain data results in a continuous-time model.
• For discrete-time models, the software sets 'Ts' to the sample time of the data in the units stored
  in the TimeUnit property.
Input delay for each input channel, specified as the comma-separated pair consisting of
'InputDelay' and a numeric vector.
• For continuous-time models, specify 'InputDelay' in the time units stored in the TimeUnit
  property.
• For discrete-time models, specify 'InputDelay' in integer multiples of the sample time Ts. For
  example, setting 'InputDelay' to 3 specifies a delay of three sampling periods.
For a system with Nu inputs, set InputDelay to an Nu-by-1 vector. Each entry of this vector is a
numerical value that represents the input delay for the corresponding input channel.
Type of canonical form of sys, specified as the comma-separated pair consisting of 'Form' and one
of the following values:
For more information about using these forms for identification, see “Estimate State-Space Models
with Canonical Parameterization”.
For an example, see “Modify Form, Feedthrough, and Disturbance-Model Matrices” on page 1-738.
Direct feedthrough from input to output, specified as the comma-separated pair consisting of
'Feedthrough' and a logical vector of length Nu, where Nu is the number of inputs. If you specify
'Feedthrough' as a logical scalar, that value is applied to all the inputs. For static systems, the
software always assumes 'Feedthrough' is 1.
For an example, see “Modify Form, Feedthrough, and Disturbance-Model Matrices” on page 1-738.
Option to estimate time-domain noise component parameters in the K matrix, specified as the comma-
separated pair consisting of 'DisturbanceModel' and one of the following values:
                                                                                               1-743
1   Functions
          • 'estimate' — Estimate the noise component. The K matrix is treated as a free parameter. For
            time-domain data, 'estimate' is the default.
          • 'none' — Do not estimate the noise component. The elements of the K matrix are fixed at zero.
            For frequency-domain data, 'none' is the default and the only acceptable value.
For an example, see “Modify Form, Feedthrough, and Disturbance-Model Matrices” on page 1-738.
          Output Arguments
          sys — Identified state-space model
          idss model
          Identified state-space model, returned as an idss model. This model is created using the specified
          model orders, delays, and estimation options.
          Information about the estimation results and options used is stored in the Report property of the
          model. Report has the following fields.
           Report      Description
           Field
           Status      Summary of the model status, which indicates whether the model was created by
                       construction or obtained by estimation.
           Method      Estimation command used.
           InitialSt How initial states were handled during estimation, returned as one of the following
           ate       values:
                       This field is especially useful when the 'InitialState' option in the estimation
                       option set is 'auto'.
           N4Weight    Weighting scheme used for singular-value decomposition by the N4SID algorithm,
                       returned as one of the following values:
                       This option is especially useful when the N4Weight option in the estimation option set
                       is 'auto'.
           N4Horizon Forward and backward prediction horizons used by the N4SID algorithm, returned as a
                     row vector with three elements [r sy su], where r is the maximum forward
                     prediction horizon, sy is the number of past outputs, and su is the number of past
                     inputs that are used for the predictions.
1-744
                                                                                              n4sid
Report      Description
Field
Fit         Quantitative assessment of the estimation, returned as a structure. See “Loss Function
            and Model Quality Metrics” for more information on these quality metrics. The
            structure has the following fields:
            Field         Description
            FitPerce Normalized root mean squared error (NRMSE) measure of how well the
            nt       response of the model fits the estimation data, expressed as the
                     percentage fit = 100(1-NRMSE).
            LossFcn       Value of the loss function when the estimation completes.
            MSE           Mean squared error (MSE) measure of how well the response of the
                          model fits the estimation data.
            FPE           Final prediction error for the model.
            AIC           Raw Akaike Information Criteria (AIC) measure of model quality.
            AICc          Small sample-size corrected AIC.
            nAIC          Normalized AIC.
            BIC           Bayesian Information Criteria (BIC).
Parameter Estimated values of model parameters.
s
OptionsUs Option set used for estimation. If you did not configure any custom options,
ed        OptionsUsed is the set of default options. See n4sidOptions for more information.
RandState State of the random number stream at the start of estimation. Empty, [], if
          randomization was not used during estimation. For more information, see rng in the
          MATLAB documentation.
                                                                                             1-745
1   Functions
           Report       Description
           Field
           DataUsed     Attributes of the data used for estimation, returned as a structure with the following
                        fields:
                        Field         Description
                        Name          Name of the data set.
                        Type          Data type.
                        Length        Number of data samples.
                        Ts            Sample time.
                        InterSam Input intersample behavior, returned as one of the following values:
                        ple
                                 • 'zoh' — Zero-order hold maintains a piecewise-constant input signal
                                    between samples.
                                      • 'foh' — First-order hold maintains a piecewise-linear input signal
                                        between samples.
                                      • 'bl' — Band-limited behavior specifies that the continuous-time input
                                        signal has zero power above the Nyquist frequency.
                        InputOff Offset removed from time-domain input data during estimation. For
                        set      nonlinear models, it is [].
                        OutputOf Offset removed from time-domain output data during estimation. For
                        fset     nonlinear models, it is [].
          Initial states computed during the estimation, returned as an array containing a column vector
          corresponding to each experiment.
This array is also stored in the Parameters field of the model Report property.
          References
          [1] Ljung, L. System Identification: Theory for the User, Appendix 4A, Second Edition, pp. 132–134.
                  Upper Saddle River, NJ: Prentice Hall PTR, 1999.
          [2] van Overschee, P., and B. De Moor. Subspace Identification of Linear Systems: Theory,
                  Implementation, Applications. Springer Publishing: 1996.
          [3] Verhaegen, M. "Identification of the deterministic part of MIMO state space models." Automatica,
                  1994, Vol. 30, pp. 61–74.
          [4] Larimore, W.E. "Canonical variate analysis in identification, filtering and adaptive control."
                  Proceedings of the 29th IEEE Conference on Decision and Control, 1990, pp. 596–604.
          [5] McKelvey, T., H. Akcay, and L. Ljung. "Subspace-based multivariable system identification from
                 frequency response data." IEEE Transactions on Automatic Control, 1996, Vol. 41, pp. 960–
                 979.
1-746
                                                                                            n4sid
See Also
canon | iddata | idfrd | idgrey | idss | n4sidOptions | pem | polyest | procest | ssest |
tfest
Topics
“What Are State-Space Models?”
“Estimate State-Space Models at the Command Line”
“State-Space Model Estimation Methods”
“Estimate State-Space Models with Canonical Parameterization”
                                                                                       1-747
1   Functions
          n4sidOptions
          Option set for n4sid
          Syntax
          opt = n4sidOptions
          opt = n4sidOptions(Name,Value)
          Description
          opt = n4sidOptions creates the default options set for n4sid.
          opt = n4sidOptions(Name,Value) creates an option set with the options specified by one or
          more Name,Value pair arguments.
          Input Arguments
          Name-Value Pair Arguments
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Handling of initial states during estimation, specified as one of the following values:
          Weighting scheme used for singular-value decomposition by the N4SID algorithm, specified as one of
          the following values:
                Specifying this option allows unbiased estimates when using data that is collected in closed-loop
                operation. For more information about the algorithm, see [4].
          • 'auto' — The estimating function chooses between the MOESP, CVA and SSARX algorithms.
1-748
                                                                                            n4sidOptions
Forward- and backward-prediction horizons used by the N4SID algorithm, specified as one of the
following values:
• A row vector with three elements — [r sy su], where r is the maximum forward prediction
  horizon, using up to r step-ahead predictors. sy is the number of past outputs, and su is the
  number of past inputs that are used for the predictions. See pages 209 and 210 in [3] for more
  information. These numbers can have a substantial influence on the quality of the resulting model,
  and there are no simple rules for choosing them. Making 'N4Horizon' a k-by-3 matrix means
  that each row of 'N4Horizon' is tried, and the value that gives the best (prediction) fit to data is
  selected. k is the number of guesses of [r sy su] combinations. If you specify N4Horizon as a
  single column, r = sy = su is used.
• 'auto' — The software uses an Akaike Information Criterion (AIC) for the selection of sy and su.
Error to be minimized in the loss function during estimation, specified as the comma-separated pair
consisting of 'Focus' and one of the following values:
• 'prediction' — The one-step ahead prediction error between measured and predicted outputs
  is minimized during estimation. As a result, the estimation focuses on producing a good predictor
  model.
• 'simulation' — The simulation error between measured and simulated outputs is minimized
  during estimation. As a result, the estimation focuses on making a good fit for simulation of model
  response with the current inputs.
The Focus option can be interpreted as a weighting filter in the loss function. For more information,
see “Loss Function and Model Quality Metrics”.
Weighting prefilter applied to the loss function to be minimized during estimation. To understand the
effect of WeightingFilter on the loss function, see “Loss Function and Model Quality Metrics”.
   Passbands are expressed in rad/TimeUnit for time-domain data and in FrequencyUnit for
   frequency-domain data, where TimeUnit and FrequencyUnit are the time and frequency units
   of the estimation data.
• SISO filter — Specify a single-input-single-output (SISO) linear filter in one of the following ways:
                                                                                                  1-749
1   Functions
                   This option calculates the weighting function as a product of the filter and the input spectrum
                   to estimate the transfer function.
          • Weighting vector — Applicable for frequency-domain data only. Specify a column vector of
            weights. This vector must have the same length as the frequency vector of the data set,
            Data.Frequency. Each input and output response in the data is multiplied by the corresponding
            weight at that frequency.
          Control whether to enforce stability of estimated model, specified as the comma-separated pair
          consisting of 'EnforceStability' and either true or false.
          Data Types: logical
          If EstimateCovariance is true, then use getcov to fetch the covariance matrix from the
          estimated model.
Specify whether to display the estimation progress, specified as one of the following values:
          • 'on' — Information on model structure and estimation results are displayed in a progress-viewer
            window.
          • 'off' — No progress or results information is displayed.
          Removal of offset from time-domain input data during estimation, specified as the comma-separated
          pair consisting of 'InputOffset' and one of the following:
          • A column vector of positive integers of length Nu, where Nu is the number of inputs.
          • [] — Indicates no offset.
          • Nu-by-Ne matrix — For multi-experiment data, specify InputOffset as an Nu-by-Ne matrix. Nu
            is the number of inputs, and Ne is the number of experiments.
Each entry specified by InputOffset is subtracted from the corresponding input data.
1-750
                                                                                            n4sidOptions
Removal of offset from time-domain output data during estimation, specified as the comma-separated
pair consisting of 'OutputOffset' and one of the following:
Each entry specified by OutputOffset is subtracted from the corresponding output data.
Weighting of prediction errors in multi-output estimations, specified as one of the following values:
• 'noise' — Minimize det(E′ * E/N), where E represents the prediction error and N is the number
  of data samples. This choice is optimal in a statistical sense and leads to the maximum likelihood
  estimates in case no data is available about the variance of the noise. This option uses the inverse
  of the estimated noise variance as the weighting function.
• Positive semidefinite symmetric matrix (W) — Minimize the trace of the weighted prediction error
  matrix trace(E'*E*W/N) where:
   • E is the matrix of prediction errors, with one column for each output. W is the positive
     semidefinite symmetric matrix of size equal to the number of outputs. Use W to specify the
     relative importance of outputs in multiple-output models, or the reliability of corresponding
     data.
   • N is the number of data samples.
• [] — The software chooses between the 'noise' or using the identity matrix for W.
Additional advanced options, specified as a structure with the field MaxSize. MaxSize specifies the
maximum number of elements in a segment when input-output data is split into segments.
Default: 250000
Output Arguments
opt — Option set for n4sid
n4sidOptions option set
Examples
                                                                                                 1-751
1   Functions
Create Default Options Set for State-Space Estimation Using Subspace Method
opt = n4sidOptions;
          Create an options set for n4sid using the 'zero' option to initialize the state. Set the Display to
          'on'.
opt = n4sidOptions('InitialState','zero','Display','on');
          opt = n4sidOptions;
          opt.InitialState = 'zero';
          opt.Display = 'on';
          Compatibility Considerations
          Renaming of Estimation and Analysis Options
          The names of some estimation and analysis options were changed in R2018a. Prior names still work.
          For details, see the R2018a release note “Renaming of Estimation and Analysis Options”.
          References
          [1] Larimore, W.E. “Canonical variate analysis in identification, filtering and adaptive control.”
                  Proceedings of the 29th IEEE Conference on Decision and Control, pp. 596–604, 1990.
          [2] Verhaegen, M. “Identification of the deterministic part of MIMO state space models.” Automatica,
                  Vol. 30, 1994, pp. 61–74.
          [3] Ljung, L. System Identification: Theory for the User. Upper Saddle River, NJ: Prentice-Hall PTR,
                  1999.
          [4] Jansson, M. “Subspace identification and ARX modeling.” 13th IFAC Symposium on System
                  Identification, Rotterdam, The Netherlands, 2003.
          See Also
          idfilt | idpar | n4sid
          Topics
          “Loss Function and Model Quality Metrics”
Introduced in R2012a
1-752
                                                                                                 ndims
ndims
Query number of dimensions of dynamic system model or model array
Syntax
n = ndims(sys)
Description
n = ndims(sys) is the number of dimensions of a dynamic system model or a model array sys. A
single model has two dimensions (one for outputs, and one for inputs). A model array has 2 + p
dimensions, where p ≥ 2 is the number of array dimensions. For example, a 2-by-3-by-4 array of
models has 2 + 3 = 5 dimensions.
ndims(sys) = length(size(sys))
Examples
Create a 3-by-1 array of random state-space models, each with 4 states, 1 input, and 1 output.
sys = rss(4,1,1,3);
ndims(sys)
ans = 4
The number of dimensions is 2+p, where p is the number of array dimensions. In this example, p is 2
because sys is 3-by-1.
See Also
size
Introduced in R2012a
                                                                                                 1-753
1   Functions
          neuralnet
          Class representing neural network nonlinearity estimator for nonlinear ARX models
          Syntax
          net_estimator = neuralnet(Network)
          Description
          neuralnet is the class that encapsulates the neural network nonlinearity estimator. A neuralnet
          object lets you use networks, created using Deep Learning Toolbox software, in nonlinear ARX
          models.
          The neural network nonlinearity estimator defines a nonlinear function y = F(x), where F is a
          multilayer feed-forward (static) neural network, as defined in the Deep Learning Toolbox software. y
          is a scalar and x is an m-dimensional row vector.
          You create multi-layer feed-forward neural networks using Deep Learning Toolbox commands such as
          feedforwardnet, cascadeforwardnet and linearlayer. When you create the network:
          • Designate the input and output sizes to be unknown by leaving them at the default value of zero
            (recommended method). When estimating a nonlinear ARX model using the nlarx command, the
            software automatically determines the input-output sizes of the network.
          • Initialize the sizes manually by setting input and output ranges to m-by-2 and 1-by-2 matrices,
            respectively, where m is the number of nonlinear ARX model regressors and the range values are
            minimum and maximum values of regressors and output data, respectively.
          Use evaluate(net_estimator,x) to compute the value of the function defined by the neuralnet
          object net_estimator at input value x. When used for nonlinear ARX model estimation, x
          represents the model regressors for the output for which the neuralnet object is assigned as the
          nonlinearity estimator.
          You cannot use neuralnet when the Focus option in nlarxOptions is 'simulation' because this
          nonlinearity estimator is considered to be nondifferentiable for estimation. Minimization of simulation
          error requires differentiable nonlinear functions.
          Construction
          net_estimator = neuralnet(Network) creates a neural network nonlinearity estimator based
          on the feed-forward (static) network object Network created using Deep Learning Toolbox commands
          feedforwardnet, cascadeforwardnet, and linearlayer. Network must represent a static
          mapping between the inputs and output without I/O delays or feedback. The number of outputs of the
          network, if assigned, must be one. For a multiple-output nonlinear ARX models, create a separate
          neuralnet object for each output—that is, each estimator must represent a single-output network
          object.
1-754
                                                                                                        neuralnet
          Properties
Network                           Neural network object, typically created using the Deep Learning Toolbox
                                  commands feedforwardnet, cascadeforwardnet, and linearlayer.
          After creating the object, you can use get or dot notation to access the object property values. For
          example:
          % List Network property value
          get(n)
          n.Network
          You can also use the set function to set the value of particular properties. For example:
          set(d, 'Network', net_obj)
Examples
          Create a neural network nonlinearity estimator using a feed-forward neural network with three
          hidden layers; transfer functions of types logsig, radbas,and purelin; and unknown input and
          output sizes.
          Create a single-layer, cascade-forward network with unknown input and output sizes and use this
          network for nonlinear ARX model estimation.
                                                                                                           1-755
1   Functions
Create a cascade-forward neural network with 20 neurons and unknown input-output sizes.
net = cascadeforwardnet(20);
net_estimator = neuralnet(net);
          load twotankdata
          Data = iddata(y,u,0.2);
compare(Data,Model)
          Initialize the input-output sizes of a two-layer feed-forward neural network based on estimation data,
          and use this network for nonlinear ARX estimation.
1-756
                                                                                              neuralnet
load iddata7 z7
z7 = z7(1:200);
This model has six regressors and is used to define the regressors. The range of regressor values for
input-output data in z7 is then used to set the input ranges in the neural network object, as shown in
the next steps.
R = getreg(model,'all',z7);
Create a two-layer, feed-forward neural network and initialize the network input and output
dimensions to 2 and 1, respectively. Use 5 neurons for first layer and 7 for second layer.
InputRange = [min(R);max(R)].';
net.inputs{1}.range = InputRange;
OutputRange = [min(z7.OutputData),max(z7.OutputData)];
net.outputs{net.outputConnect}.range = OutputRange;
net_estimator = neuralnet(net);
model.Nonlinearity = net_estimator;
Estimate the parameters of the network to minimize the prediction error between data and model.
Estimate model.
model = nlarx(z7,model);
compare(z7(1:100),model,1)
                                                                                                1-757
1   Functions
          Algorithms
          The nlarx command uses the train method of the network object, defined in the Deep Learning
          Toolbox software, to compute the network parameter values.
          See Also
          cascadeforwardnet | customnet | feedforwardnet | linearlayer | nlarx | sigmoidnet |
          treepartition | wavenet
          Topics
          “Identifying Nonlinear ARX Models”
Introduced in R2007a
1-758
                                                                                                 nkshift
nkshift
Shift data sequences
Syntax
Datas = nkshift(Data,nk)
Description
Data contains input-output data in the iddata format.
nk is a row vector with the same length as the number of input channels in Data.
Datas is an iddata object where the input channels in Data have been shifted according to nk. A
positive value of nk(ku) means that input channel number ku is delayed nk(ku) samples.
nkshift supports both frequency- and time-domain data. For frequency-domain data it multiplies
with einkωT to obtain the same effect as shifting in the time domain. For continuous-time frequency-
domain data (Ts = 0), nk should be interpreted as the shift in seconds.
nkshift lives in symbiosis with the InputDelay property of linear identified models:
m1 = ssest(dat,4,'InputDelay',nk)
is related to
m2 = ssest(nkshift(dat,nk),4);
such that m1 and m2 are the same models, but m1 stores the delay information and uses this
information when computing the frequency response, for example. When using m2, the delay value
must be accounted for separately when computing time and frequency responses.
See Also
absorbDelay | delayest | idpoly | idss
                                                                                                 1-759
1   Functions
          nlarx
          Estimate parameters of nonlinear ARX model
          Syntax
          sys = nlarx(Data,Orders)
          sys = nlarx(Data,Orders,Nonlinearity)
          sys = nlarx(Data,Orders,Nonlinearity,Name,Value)
          sys = nlarx(Data,LinModel)
          sys = nlarx(Data,LinModel,Nonlinearity)
          sys = nlarx(Data,LinModel,Nonlinearity,Name,Value)
sys = nlarx(Data,sys0)
          Description
          sys = nlarx(Data,Orders) estimates a nonlinear ARX model to fit the given estimation data
          using the specified orders and a default wavelet network nonlinearity estimator.
          sys = nlarx(Data,LinModel) uses a linear ARX model, LinModel, to specify the model orders
          and the initial values of the linear coefficients of the model.
sys = nlarx(Data,sys0) refines the parameters of the nonlinear ARX model, sys0.
          • Update the parameters of a previously estimated model to improve the fit to the estimation data.
            In this case, the estimation algorithm uses the parameters of sys0 as initial guesses.
          • Estimate the parameters of a model previously created using the idnlarx constructor. Prior to
            estimation, you can configure the model properties using dot notation.
          sys = nlarx( ___ ,Options) specifies additional configuration options for the model estimation.
          Use Options with any of the previous syntaxes.
1-760
                                                                                   nlarx
Examples
Create an iddata object from the estimation data with a sample time of 0.2 min.
Ts = 0.2;
z = iddata(y,u,Ts);
                                                                                  1-761
1   Functions
Generating a custom network nonlinearity requires the definition of a user-defined unit function.
          H = @gaussunit;
          CNet = customnet(H);
load iddata1;
load motorizedcamera;
z = iddata(y,u,0.02,'Name','Motorized Camera','TimeUnit','s');
Orders = [ones(2,2),2*ones(2,6),ones(2,6)];
NL = [wavenet('NumberOfUnits',2),linear];
sys = nlarx(z,Orders,NL);
1-762
                                                                                                nlarx
Estimate MIMO Nonlinear ARX Model with Same Nonlinearity for All Outputs
load motorizedcamera;
z = iddata(y,u,0.02);
Orders = [ones(2,2),2*ones(2,6),ones(2,6)];
Estimate a nonlinear ARX model using a sigmoidnet nonlinearity with 4 units for all output channels.
m = nlarx(z,Orders,sigmoidnet('numberOfUnits',4));
load iddata1;
C = {'y1(t-1)^2','y1(t-2)*u1(t-3)'};
Estimate a nonlinear ARX model with custom regressors and no standard regressors.
load iddata1;
C1 = customreg(@(x)x^2,{'y1'},[1]);
C2 = customreg(@(x,y)x*y,{'y1','u1'},[2 3]);
C = [C1,C2];
getreg(sys);
                                                                                               1-763
1   Functions
          Regressors:
              y1(t-1)^2
              y1(t-2)*u1(t-3)
ans = 1×4
3 5 6 7
          Regressors:
              y1(t-1)
              y1(t-2)
              y1(t-3)
              y1(t-4)
              u1(t-1)
              u1(t-2)
              u1(t-3)
              u1(t-4)
          The optimum set of nonlinear regressors for this model includes y1(t-3), u1(t-1), u1(t-2), and
          u1(t-3).
1-764
                                                                                                 nlarx
Specify Nonlinear ARX Orders and Linear Parameters Using Linear ARX Model
load throttledata;
Tr = getTrend(ThrottleData);
Tr.OutputOffset = 15;
DetrendedData = detrend(ThrottleData,Tr);
Estimate the nonlinear ARX model using the linear model. The model orders, delays, and linear
parameters of NonlinearModel are derived from LinearModel.
NonlinearModel = nlarx(ThrottleData,LinearModel);
load iddata1;
Configure the model using dot notation to set the following parameters:
sys.Nonlinearity = 'sigmoidnet';
sys.NonlinearRegressors = 'search';
Estimate a nonlinear ARX model with the structure and properties specified in the idnlarx object.
sys = nlarx(z1,sys);
If an estimation stops at a local minimum, you can perturb the model using init and reestimate the
model.
load iddata1;
                                                                                                1-765
1   Functions
sys2 = init(sys1);
sys2 = nlarx(z1,sys2);
load twotankdata;
z = iddata(y,u,0.2);
          Create an nlarxOptions option set specifying a simulation error minimization objective and a
          maximum of 50 estimation iterations.
          opt = nlarxOptions;
          opt.Focus = 'simulation';
          opt.SearchOptions.MaxIterations = 50;
Create a sigmoidnet nonlinearity with 30 units, and specify the model orders.
          NL = sigmoidnet('NumberOfUnits',30);
          Orders = [1 2 1];
Create an estimation option set and set the estimation search method to lm.
opt = nlarxOptions('SearchMethod','lm');
sys = nlarx(nldata,Orders,NL,opt);
1-766
                                                                                                    nlarx
opt.Regularization.Lambda = 1e-8;
sysR = nlarx(nldata,Orders,NL,opt);
compare(nldata,sys,sysR)
The large negative fit result for the unregularized model indicates a poor fit to the data. Estimating a
regularized model produces a significantly better result.
Input Arguments
Data — Time-domain estimation data
iddata object
Time-domain estimation data, specified as an iddata object. Data can have one or more output
channels and zero or more input channels. Data must be uniformly sampled and cannot contain
missing (NaN) samples.
                                                                                                  1-767
1   Functions
          Model orders and delays for defining the regressor configuration, specified as a 1-by-3 vector, [na
          nb nk].
          • na is an ny-by-ny matrix, where na(i,j) specifies the number of regressors from the jth output
            used to predict the ith output.
          • nb is an ny-by-nu matrix, where nb(i,j) specifies the number of regressors from the jth input
            used to predict the ith output.
          • nk is an ny-by-nu matrix, where nk(i,j) specifies the lag in the jth input used to predict the ith
            output.
          na = [1 2; 2 3]
          nb = [1 2 3; 2 3 1];
          nk = [2 0 3; 1 0 5];
          The estimation data for this system has three inputs (u1, u2, u3) and two outputs (y1, y2). Consider
          the regressors used to predict output, y2(t):
• Since na(2,:) is [2 3], the contributing regressors from the outputs are:
          Note The minimum lag for regressors based on output variables is always 1, while the minimum lag
          for regressors based on input variables is dictated by nk. Use getreg to view the complete set of
          regressors used by the nonlinear ARX model.
1-768
                                                                                                 nlarx
For more information, see “Available Nonlinearity Estimators for Nonlinear ARX Models”.
Specifying a character vector, for example 'sigmoidnet', creates a nonlinearity estimator object
with default settings. Alternatively, you can specify nonlinearity estimator settings in two ways:
• Use the associated nonlinearity estimator function with Name-Value pair arguments.
   NL = sigmoidnet('NumberOfUnits',10);
• Create and modify a default nonlinearity estimator object.
   NL = sigmoidnet;
   NL.NumberOfUnits = 10;
For ny output channels, you can specify nonlinear estimators individually for each channel by setting
Nonlinearity to an ny-by-1 array of nonlinearity estimator objects. To specify the same nonlinearity
for all outputs, specify Nonlinearity as a character vector or a single nonlinearity estimator object.
Example: 'sigmoidnet' specifies a sigmoid network nonlinearity with a default configuration.
Example: treepartition('NumberOfUnits',5) specifies a binary-tree nonlinearity with 5 terms
in the binary tree expansion.
Example: [wavenet('NumberOfUnits',10);sigmoidnet] specifies different nonlinearity
estimators for two output channels.
Discrete time input-output polynomial model of ARX structure, specified as an idpoly model. Create
this object using the idpoly constructor or estimate it using the arx command.
• A model previously estimated using nlarx. The estimation algorithm uses the parameters of sys0
  as initial guesses. In this case, use init to slightly perturb the model properties to avoid being
  trapped in local minima.
   sys = init(sys);
   sys = nlarx(data,sys);
• A model previously created using idnlarx and with properties set using dot notation. Use this
  method to avoid complicated Name-Value pair syntax when configuring multiple model properties.
  For example, use
   sys2 = nlarx(data,[4,3,1],'treepartition','CustomRegressors',...
       {'sin(u1(t-1))'},'NonlinearRegressors','search');
                                                                                               1-769
1   Functions
Estimation options for nonlinear ARX model identification, specified as an nlarxOptions option set.
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
          Example: 'NonlinearRegressors','output' specifies that only the regressors containing output
          variables are used as inputs to the nonlinear block of the model.
          Regressors constructed from combinations of inputs and outputs, specified as the comma-separated
          pair consisting of 'CustomRegressors' and one of the following for single-output systems:
• {'y1(t-3)^3','y2(t-1)*u1(t-3)','sin(u3(t-2))'}
                Each character vector must represent a valid formula for a regressor contributing towards the
                prediction of the model output. The formula must be written using the input and output names
                and the time variable name as variables.
          • Array of custom regressor objects, created using customreg or polyreg.
          For a model with ny outputs, specify an ny-by-1 cell array of customreg object arrays or character
          arrays.
          Subset of regressors that enter as inputs to the nonlinear block of the model, specified as the comma-
          separated pair consisting of 'NonlinearRegressors' and one of the following values:
1-770
                                                                                                    nlarx
For a model with multiple outputs, specify a cell array of ny elements, where ny is the number of
output channels. For each output, specify one of the preceding options. Alternatively, to apply the
same regressor subset to all model outputs, specify [] or any of the character vector options alone,
for example 'standard'.
Example: 'NonlinearRegressors','search' performs a best regressor search for the only
output of a single output model, or all of the outputs of a multiple output model.
Example: 'NonlinearReg','input' applies only input regressors to the inputs of the nonlinear
function.
Example: 'NonlinearRegressors',{'input','output'} applies input regressors to the first
output, and output regressors to the second output of a model with two outputs.
Output Arguments
sys — Nonlinear ARX model
idnlarx object
Nonlinear ARX model that fits the given estimation data, returned as an idnlarx object. This model
is created using the specified model orders, nonlinearity estimator, and estimation options.
Information about the estimation results and options used is stored in the Report property of the
model. The contents of Report depend upon the choice of nonlinearity and estimation focus you
specified for nlarx. Report has the following fields:
Report       Description
Field
Status       Summary of the model status, which indicates whether the model was created by
             construction or obtained by estimation.
Method       Estimation command used.
                                                                                                1-771
1   Functions
           Report       Description
           Field
           Fit          Quantitative assessment of the estimation, returned as a structure. See “Loss Function
                        and Model Quality Metrics” for more information on these quality metrics. The
                        structure has the following fields:
                        Field         Description
                        FitPerce Normalized root mean squared error (NRMSE) measure of how well the
                        nt       response of the model fits the estimation data, expressed as the
                                 percentage fit = 100(1-NRMSE).
                        LossFcn       Value of the loss function when the estimation completes.
                        MSE           Mean squared error (MSE) measure of how well the response of the
                                      model fits the estimation data.
                        FPE           Final prediction error for the model.
                        AIC           Raw Akaike Information Criteria (AIC) measure of model quality.
                        AICc          Small sample-size corrected AIC.
                        nAIC          Normalized AIC.
                        BIC           Bayesian Information Criteria (BIC).
           Parameter Estimated values of model parameters.
           s
           OptionsUs Option set used for estimation. If no custom options were configured, this is a set of
           ed        default options. See nlarxOptions for more information.
           RandState State of the random number stream at the start of estimation. Empty, [], if
                     randomization was not used during estimation. For more information, see rng in the
                     MATLAB documentation.
1-772
                                                                                                  nlarx
Report       Description
Field
DataUsed     Attributes of the data used for estimation, returned as a structure with the following
             fields:
             Field         Description
             Name          Name of the data set.
             Type          Data type.
             Length        Number of data samples.
             Ts            Sample time.
             InterSam Input intersample behavior, returned as one of the following values:
             ple
                      • 'zoh' — Zero-order hold maintains a piecewise-constant input signal
                         between samples.
                           • 'foh' — First-order hold maintains a piecewise-linear input signal
                             between samples.
                           • 'bl' — Band-limited behavior specifies that the continuous-time input
                             signal has zero power above the Nyquist frequency.
             InputOff Offset removed from time-domain input data during estimation. For
             set      nonlinear models, it is [].
             OutputOf Offset removed from time-domain output data during estimation. For
             fset     nonlinear models, it is [].
Terminati Termination conditions for the iterative search used for prediction error minimization.
on        Structure with the following fields:
             Field         Description
             WhyStop       Reason for terminating the numerical search.
             Iteratio Number of search iterations performed by the estimation algorithm.
             ns
             FirstOrd ∞-norm of the gradient search vector when the search algorithm
             erOptima terminates.
             lity
             FcnCount Number of times the objective function was called.
             UpdateNo Norm of the gradient search vector in the last iteration. Omitted when the
             rm       search method is 'lsqnonlin' or 'fmincon'.
             LastImpr Criterion improvement in the last iteration, expressed as a percentage.
             ovement Omitted when the search method is 'lsqnonlin' or 'fmincon'.
             Algorith Algorithm used by 'lsqnonlin' or 'fmincon' search method. Omitted
             m        when other search methods are used.
             For estimation methods that do not require numerical search optimization, the
             Termination field is omitted.
                                                                                                1-773
1   Functions
          Algorithms
          Nonlinear ARX Model Structure
          A nonlinear ARX model consists of model regressors and a nonlinearity estimator. The nonlinearity
          estimator comprises both linear and nonlinear functions that act on the model regressors to give the
          model output. This block diagram represents the structure of a nonlinear ARX model in a simulation
          scenario.
The software computes the nonlinear ARX model output y in two stages:
1 It computes regressor values from the current and past input values and past output data.
                In the simplest case, regressors are delayed inputs and outputs, such as u(t-1) and y(t-3). These
                kind of regressors are called standard regressors. You specify the standard regressors using the
                model orders and delay. For more information, see “Nonlinear ARX Model Orders and Delay”. You
                can also specify custom regressors, which are nonlinear functions of delayed inputs and outputs.
                For example, u(t-1)*y(t-3). To create a set of polynomial type regressors, use polyreg.
                By default, all regressors are inputs to both the linear and the nonlinear function blocks of the
                nonlinearity estimator. You can choose a subset of regressors as inputs to the nonlinear function
                block.
          2     It maps the regressors to the model output using the nonlinearity estimator block. The
                nonlinearity estimator block can include linear and nonlinear blocks in parallel. For example:
F(x) = LT (x − r) + d + g Q(x − r)
                Here, x is a vector of the regressors, and r is the mean of the regressors x. LT (x) + d is the output
                of the linear function block and is affine when d ≠ 0. d is a scalar offset. g Q(x − r) represents
                the output of the nonlinear function block. Q is a projection matrix that makes the calculations
                well conditioned. The exact form of F(x) depends on your choice of the nonlinearity estimator.
                You can select from available nonlinearity estimators, such as tree-partition networks, wavelet
                networks, and multilayer neural networks. You can also exclude either the linear or the nonlinear
                function block from the nonlinearity estimator.
                When estimating a nonlinear ARX model, the software computes the model parameter values,
                such as L, r, d, Q, and other parameters specifying g.
          Resulting nonlinear ARX models are idnlarx objects that store all model data, including model
          regressors and parameters of the nonlinearity estimator. For more information about these objects,
          see “Nonlinear Model Structures”.
1-774
                                                                                              nlarx
Extended Capabilities
Automatic Parallel Support
Accelerate code by automatically running computation in parallel using Parallel Computing Toolbox™.
Parallel computing support is available for estimation using the lsqnonlin search method (requires
Optimization Toolbox). To enable parallel computing, use nlarxOptions, set SearchMethod to
'lsqnonlin', and set SearchOptions.Advanced.UseParallel to true.
For example:
opt = nlarxOptions;
opt.SearchMethod = 'lsqnonlin';
opt.SearchOptions.Advanced.UseParallel = true;
See Also
aic | fpe | goodnessOfFit | idnlarx | isnlarx | nlarxOptions
Topics
“Estimate Nonlinear ARX Models at the Command Line”
“Estimate Nonlinear ARX Models Initialized Using Linear ARX Models”
“Identifying Nonlinear ARX Models”
“Validate Nonlinear ARX Models”
“Using Nonlinear ARX Models”
“Loss Function and Model Quality Metrics”
“Regularized Estimates of Model Parameters”
“Estimation Report”
Introduced in R2007a
                                                                                             1-775
1   Functions
          nlarxOptions
          Option set for nlarx
          Syntax
          opt = nlarxOptions
          opt = nlarxOptions(Name,Value)
          Description
          opt = nlarxOptions creates the default option set for nlarx. Use dot notation to modify this
          option set for your specific application. Any options that you do not modify retain their default values.
          opt = nlarxOptions(Name,Value) creates an option set with options specified by one or more
          Name,Value pair arguments.
Examples
opt = nlarxOptions;
Create a default option set for nlarx, and use dot notation to modify specific options.
opt = nlarxOptions;
opt.Display = 'on';
opt.Focus = 'simulation';
          opt.SearchMethod = 'gn';
          opt.SearchOptions.MaxIterations = 25;
1-776
                                                                                          nlarxOptions
• Turn off iterative estimation for the default wavelet network estimation.
• Turn on the estimation progress-viewer display.
opt = nlarxOptions('IterativeWavenet','off','Display','on');
Input Arguments
Name-Value Pair Arguments
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Example: 'Focus','simulation','SearchMethod','grad' specifies that the norm of the
simulation error is minimized using a steepest descent least squares search.
Minimization objective, specified as the comma-separated pair consisting of 'Focus' and one of the
following:
• 'prediction' — Minimize the norm of the prediction error, which is defined as the difference
  between the measured output and the one-step ahead predicted response of the model.
• 'simulation' — Minimize the norm of the simulation error, which is defined as the difference
  between the measured output and simulated response of the model.
Estimation progress display setting, specified as the comma-separated pair consisting of 'Display'
and one of the following:
• 'noise' — Optimal weighting is automatically computed as the inverse of the estimated noise
  variance. This weighting minimizes det(E'*E), where E is the matrix of prediction errors. This
  option is not available when using 'lsqnonlin' as a 'SearchMethod'.
• A positive semidefinite matrix, W, of size equal to the number of outputs. This weighting minimizes
  trace(E'*E*W/N), where E is the matrix of prediction errors and N is the number of data
  samples.
                                                                                               1-777
1   Functions
          Options for regularized estimation of model parameters, specified as the comma-separated pair
          consisting of 'Regularization' and a structure with fields:
          To specify field values in Regularization, create a default nlarxOptions set and modify the fields
          using dot notation. Any fields that you do not modify retain their default values.
          opt = nlarxOptions;
          opt.Regularization.Lambda = 1.2;
          opt.Regularization.R = 0.5*eye(np);
          Regularization is a technique for specifying model flexibility constraints, which reduce uncertainty in
          the estimated parameter values. For more information, see “Regularized Estimates of Model
          Parameters”.
          Numerical search method used for iterative parameter estimation, specified as the comma-separated
          pair consisting of 'SearchMethod' and one of the following:
          • 'auto' — A combination of the line search algorithms, 'gn', 'lm', 'gna', and 'grad' methods
            is tried in sequence at each iteration. The first descent direction leading to a reduction in
            estimation cost is used.
1-778
                                                                                            nlarxOptions
• 'gn' — Subspace Gauss-Newton least squares search. Singular values of the Jacobian matrix less
  than GnPinvConstant*eps*max(size(J))*norm(J) are discarded when computing the
  search direction. J is the Jacobian matrix. The Hessian matrix is approximated as JTJ. If there is no
  improvement in this direction, the function tries the gradient direction.
• 'gna' — Adaptive subspace Gauss-Newton search. Eigenvalues less than gamma*max(sv) of the
  Hessian are ignored, where sv contains the singular values of the Hessian. The Gauss-Newton
  direction is computed in the remaining subspace. gamma has the initial value
  InitialGnaTolerance (see Advanced in 'SearchOptions' for more information). This value
  is increased by the factor LMStep each time the search fails to find a lower value of the criterion
  in fewer than five bisections. This value is decreased by the factor 2*LMStep each time a search is
  successful without any bisections.
• 'lm' — Levenberg-Marquardt least squares search, where the next parameter value is -pinv(H
  +d*I)*grad from the previous one. H is the Hessian, I is the identity matrix, and grad is the
  gradient. d is a number that is increased until a lower value of the criterion is found.
• 'grad' — Steepest descent least squares search.
• 'lsqnonlin' — Trust-region-reflective algorithm of lsqnonlin. Requires Optimization Toolbox
  software.
• 'fmincon' — Constrained nonlinear solvers. You can use the sequential quadratic programming
  (SQP) and trust-region-reflective algorithms of the fmincon solver. If you have Optimization
  Toolbox software, you can also use the interior-point and active-set algorithms of the fmincon
  solver. Specify the algorithm in the SearchOptions.Algorithm option. The fmincon algorithms
  may result in improved estimation results in the following scenarios:
   • Constrained minimization problems when there are bounds imposed on the model parameters.
   • Model structures where the loss function is a nonlinear or non smooth function of the
     parameters.
   • Multi-output model estimation. A determinant loss function is minimized by default for multi-
     output model estimation. fmincon algorithms are able to minimize such loss functions directly.
     The other search methods such as 'lm' and 'gn' minimize the determinant loss function by
     alternately estimating the noise variance and reducing the loss value for a given noise variance
     value. Hence, the fmincon algorithms can offer better efficiency and accuracy for multi-output
     model estimations.
Options set for the search algorithm, specified as the comma-separated pair consisting of
'SearchOptions' and a search option set with fields that depend on the value of SearchMethod:
                                                                                                 1-779
1   Functions
1-780
                                                                                           nlarxOptions
                                                                                                1-781
1   Functions
1-782
                                                                         nlarxOptions
                            • 'sqp' — Sequential
                              quadratic programming
                              algorithm. The algorithm
                              satisfies bounds at all
                              iterations, and it can recover
                              from NaN or Inf results. It is
                              not a large-scale algorithm.
                              For more information, see
                              “Large-Scale vs. Medium-
                              Scale Algorithms”
                              (Optimization Toolbox).
                            • 'trust-region-
                              reflective' — Subspace
                              trust-region method based
                              on the interior-reflective
                              Newton method. It is a large-
                              scale algorithm.
                            • 'interior-point' —
                              Large-scale algorithm that
                              requires Optimization
                              Toolbox software. The
                              algorithm satisfies bounds at
                              all iterations, and it can
                              recover from NaN or Inf
                              results.
                            • 'active-set' — Requires
                              Optimization Toolbox
                              software. The algorithm can
                              take large steps, which adds
                              speed. It is not a large-scale
                              algorithm.
                                                                              1-783
1   Functions
          To specify field values in SearchOptions, create a default nlarxOptions set and modify the fields
          using dot notation. Any fields that you do not modify retain their default values.
          opt = nlarxOptions;
          opt.SearchOptions.MaxIter = 15;
          opt.SearchOptions.Advanced.RelImprovement = 0.5;
          Additional advanced options, specified as the comma-separated pair consisting of 'Advanced' and a
          structure with fields:
          To specify field values in Advanced, create a default nlarxOptions set and modify the fields using
          dot notation. Any fields that you do not modify retain their default values.
          opt = nlarxOptions;
          opt.Advanced.ErrorThreshold = 1.2;
1-784
                                                                                       nlarxOptions
Output Arguments
opt — Option set for nlarx command
nlarxOptions option set
Compatibility Considerations
Renaming of Estimation and Analysis Options
The names of some estimation and analysis options were changed in R2018a. Prior names still work.
For details, see the R2018a release note “Renaming of Estimation and Analysis Options”.
See Also
nlarx
Introduced in R2015a
                                                                                            1-785
1   Functions
          nlgreyest
          Estimate nonlinear grey-box model parameters
          Syntax
          sys= nlgreyest(data,init_sys)
          sys= nlgreyest(data,init_sys,options)
          Description
          sys= nlgreyest(data,init_sys) estimates the parameters of a nonlinear grey-box model,
          init_sys, using time-domain data, data.
Examples
Load data.
          load(fullfile(matlabroot,'toolbox','ident','iddemos','data','twotankdata'));
          z = iddata(y,u,0.2,'Name','Two tanks');
          The data contains 3000 input-output data samples of a two tank system. The input is the voltage
          applied to a pump, and the output is the liquid level of the lower tank.
          Specify file describing the model structure for a two-tank system. The file specifies the state
          derivatives and model outputs as a function of time, states, inputs, and model parameters.
FileName = 'twotanks_c';
Order = [1 1 2];
InitialStates = [0;0.1];
Ts = 0;
1-786
                                                                                             nlgreyest
Create estimation option set for nlgreyest to view estimation progress, and to set the maximum
iteration steps to 50.
opt = nlgreyestOptions;
opt.Display = 'on';
opt.SearchOptions.MaxIterations = 50;
Load data.
load(fullfile(matlabroot,'toolbox','ident','iddemos','data','dcmotordata'));
z = iddata(y,u,0.1,'Name','DC-motor');
The data is from a linear DC motor with one input (voltage), and two outputs (angular position and
angular velocity). The structure of the model is specified by dcmotor_m.m file.
Input Arguments
data — Time domain data
iddata object
Time-domain estimation data, specified as an iddata object. data has the same input and output
dimensions as init_sys.
If you specify the InterSample property of data as 'bl'(band-limited) and the model is continuous-
time, the software treats data as first-order-hold (foh) interpolated for estimation.
                                                                                               1-787
1   Functions
          Constructed nonlinear grey-box model that configures the initial parameterization of sys, specified as
          an idnlgrey object. init_sys has the same input and output dimensions as data. Create
          init_sys using idnlgrey.
          Output Arguments
          sys — Estimated nonlinear grey-box model
          idnlgrey object
          Nonlinear grey-box model with the same structure as init_sys, returned as an idnlgrey object.
          The parameters of sys are estimated such that the response of sys matches the output signal in the
          estimation data.
          Information about the estimation results and options used is stored in the Report property of the
          model. Report has the following fields:
           Report      Description
           Field
           Status      Summary of the model status, which indicates whether the model was created by
                       construction or obtained by estimation.
           Method      Name of the simulation solver and the search method used during estimation.
           Fit         Quantitative assessment of the estimation, returned as a structure. See “Loss Function
                       and Model Quality Metrics” for more information on these quality metrics. The
                       structure has the following fields:
                        Field        Description
                        FitPerce Normalized root mean squared error (NRMSE) measure of how well the
                        nt       response of the model fits the estimation data, expressed as the
                                 percentage fit = 100(1-NRMSE).
                        LossFcn      Value of the loss function when the estimation completes.
                        MSE          Mean squared error (MSE) measure of how well the response of the
                                     model fits the estimation data.
                        FPE          Final prediction error for the model.
                        AIC          Raw Akaike Information Criteria (AIC) measure of model quality.
                        AICc         Small sample-size corrected AIC.
                        nAIC         Normalized AIC.
                        BIC          Bayesian Information Criteria (BIC).
1-788
                                                                                                 nlgreyest
Report       Description
Field
Parameter Estimated values of the model parameters. Structure with the following fields:
s
          Field                   Description
             InitialValues            Structure with values of parameters and initial states before
                                      estimation.
             ParVector                Value of parameters after estimation.
             Free                     Logical vector specifying the fixed or free status of parameters
                                      during estimation
             FreeParCovariance Covariance of the free parameters.
             X0                       Value of initial states after estimation.
             X0Covariance             Covariance of the initial states.
OptionsUs Option set used for estimation. If no custom options were configured, this is a set of
ed        default options. See nlgreyestOptions for more information.
RandState State of the random number stream at the start of estimation. Empty, [], if
          randomization was not used during estimation. For more information, see rng in the
          MATLAB documentation.
DataUsed     Attributes of the data used for estimation — Structure with the following fields:
             Field         Description
             Name          Name of the data set.
             Type          Data type — For idnlgrey models, this is set to 'Time domain data'.
             Length        Number of data samples.
             Ts            Sample time. This is equivalent to data.Ts.
             InterSam Input intersample behavior. One of the following values:
             ple
                      • 'zoh' — Zero-order hold maintains a piecewise-constant input signal
                         between samples.
                           • 'foh' — First-order hold maintains a piecewise-linear input signal
                             between samples.
                           • 'bl' — Band-limited behavior specifies that the continuous-time input
                             signal has zero power above the Nyquist frequency.
                                                                                                   1-789
1   Functions
           Report        Description
           Field
           Terminati Termination conditions for the iterative search used for prediction error minimization.
           on        Structure with the following fields:
                         Field         Description
                         WhyStop       Reason for terminating the numerical search.
                         Iteratio Number of search iterations performed by the estimation algorithm.
                         ns
                         FirstOrd ∞-norm of the gradient search vector when the search algorithm
                         erOptima terminates.
                         lity
                         FcnCount Number of times the objective function was called.
                         UpdateNo Norm of the gradient search vector in the last iteration. Omitted when the
                         rm       search method is 'lsqnonlin' or 'fmincon'.
                         LastImpr Criterion improvement in the last iteration, expressed as a percentage.
                         ovement Omitted when the search method is 'lsqnonlin' or 'fmincon'.
                         Algorith Algorithm used by 'lsqnonlin' or 'fmincon' search method. Omitted
                         m        when other search methods are used.
                         For estimation methods that do not require numerical search optimization, the
                         Termination field is omitted.
          Extended Capabilities
          Automatic Parallel Support
          Accelerate code by automatically running computation in parallel using Parallel Computing Toolbox™.
          Parallel computing support is available for estimation using the lsqnonlin search method (requires
          Optimization Toolbox). To enable parallel computing, use nlgreyestOptions, set SearchMethod to
          'lsqnonlin', and set SearchOptions.Advanced.UseParallel to true.
For example:
          opt = nlgreyestOptions;
          opt.SearchMethod = 'lsqnonlin';
          opt.SearchOptions.Advanced.UseParallel = true;
          See Also
          aic | fpe | goodnessOfFit | idnlgrey | nlgreyestOptions | pem
          Topics
          “Creating IDNLGREY Model Files”
          “Represent Nonlinear Dynamics Using MATLAB File for Grey-Box Estimation”
          “Estimate Nonlinear Grey-Box Models”
          “Loss Function and Model Quality Metrics”
          “Regularized Estimates of Model Parameters”
1-790
                       nlgreyest
“Estimation Report”
Introduced in R2015a
                         1-791
1   Functions
          nlgreyestOptions
          Option set for nlgreyest
          Syntax
          opt = nlgreyestOptions
          opt = nlgreyestOptions(Name,Value)
          Description
          opt = nlgreyestOptions creates the default option set for nlgreyest. Use dot notation to
          customize the option set, if needed.
Examples
opt = nlgreyestOptions;
          Create estimation option set for nlgreyest to view estimation progress, and to set the maximum
          iteration steps to 50.
          opt = nlgreyestOptions;
          opt.Display = 'on';
          opt.SearchOptions.MaxIterations = 50;
Load data.
          load(fullfile(matlabroot,'toolbox','ident','iddemos','data','dcmotordata'));
          z = iddata(y,u,0.1,'Name','DC-motor');
          The data is from a linear DC motor with one input (voltage), and two outputs (angular position and
          angular velocity). The structure of the model is specified by dcmotor_m.m file.
          file_name = 'dcmotor_m';
          Order = [2 1 2];
          Parameters = [1;0.28];
          InitialStates = [0;0];
1-792
                                                                                             nlgreyestOptions
sys = nlgreyest(z,init_sys,opt);
opt = nlgreyestOptions('EstimateCovariance',false,'SearchMethod','gn');
        Input Arguments
        Name-Value Pair Arguments
        Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
        Value is the corresponding value. Name must appear inside quotes. You can specify several name and
        value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
        Example: nlgreyestOptions('Display','on')
        Options for computing Jacobians and gradients, specified as the comma-separated pair consisting of
        'GradientOptions' and a structure with fields:
                                                                                                      1-793
1   Functions
          To specify field values in GradientOptions, create a default nlgreyestOptions set and modify
          the fields using dot notation. Any fields that you do not modify retain their default values.
          opt = nlgreyestOptions;
          opt.GradientOptions.Type = 'Basic';
Controls whether parameter covariance data is generated, specified as true (1) or false (0).
          Estimation progress display setting, specified as the comma-separated pair consisting of 'Display'
          and one of the following:
          Options for regularized estimation of model parameters, specified as the comma-separated pair
          consisting of 'Regularization' and a structure with fields:
1-794
                                                                                        nlgreyestOptions
To specify field values in Regularization, create a default nlgreyestOptions set and modify the
fields using dot notation. Any fields that you do not modify retain their default values.
opt = nlgreyestOptions;
opt.Regularization.Lambda = 1.2;
opt.Regularization.R = 0.5*eye(np);
Regularization is a technique for specifying model flexibility constraints, which reduce uncertainty in
the estimated parameter values. For more information, see “Regularized Estimates of Model
Parameters”.
Numerical search method used for iterative parameter estimation, specified as the comma-separated
pair consisting of 'SearchMethod' and one of the following:
                                                                                                 1-795
1   Functions
                • Constrained minimization problems when there are bounds imposed on the model parameters.
                • Model structures where the loss function is a nonlinear or non smooth function of the
                  parameters.
                • Multi-output model estimation. A determinant loss function is minimized by default for MIMO
                  model estimation. fmincon algorithms are able to minimize such loss functions directly. The
                  other available search methods such as 'lm' and 'gn' minimize the determinant loss function
                  by alternately estimating the noise variance and reducing the loss value for a given noise
                  variance value. Hence, the fmincon algorithms can offer better efficiency and accuracy for
                  multi-output model estimations.
          Option set for the search algorithm, specified as the comma-separated pair consisting of
          'SearchOptions' and a search option set with fields that depend on the value of SearchMethod.
1-796
                                                                                     nlgreyestOptions
                                                                                              1-797
1   Functions
1-798
                                                                                      nlgreyestOptions
                                                                                               1-799
1   Functions
                                      • 'sqp' — Sequential
                                        quadratic programming
                                        algorithm. The algorithm
                                        satisfies bounds at all
                                        iterations, and it can recover
                                        from NaN or Inf results. It is
                                        not a large-scale algorithm.
                                        For more information, see
                                        “Large-Scale vs. Medium-
                                        Scale Algorithms”
                                        (Optimization Toolbox).
                                      • 'trust-region-
                                        reflective' — Subspace
                                        trust-region method based
                                        on the interior-reflective
                                        Newton method. It is a large-
                                        scale algorithm.
                                      • 'interior-point' —
                                        Large-scale algorithm that
                                        requires Optimization
                                        Toolbox software. The
                                        algorithm satisfies bounds at
                                        all iterations, and it can
                                        recover from NaN or Inf
                                        results.
                                      • 'active-set' — Requires
                                        Optimization Toolbox
                                        software. The algorithm can
                                        take large steps, which adds
                                        speed. It is not a large-scale
                                        algorithm.
1-800
                                                                                      nlgreyestOptions
To specify field values in SearchOptions, create a default nlgreyestOptions set and modify the
fields using dot notation. Any fields that you do not modify retain their default values.
opt = nlgreyestOptions('SearchMethod','gna');
opt.SearchOptions.MaxIterations = 50;
opt.SearchOptions.Advanced.RelImprovement = 0.5;
Additional advanced options, specified as the comma-separated pair consisting of 'Advanced' and a
structure with field:
                                                                                               1-801
1   Functions
          To specify field values in Advanced, create a default nlgreyestOptions set and modify the fields
          using dot notation. Any fields that you do not modify retain their default values.
          opt = nlgreyestOptions;
          opt.Advanced.ErrorThreshold = 1.2;
          Output Arguments
          opt — Option set for nlgreyest
          nlgreyestOptions option set
          Compatibility Considerations
          Renaming of Estimation and Analysis Options
          The names of some estimation and analysis options were changed in R2018a. Prior names still work.
          For details, see the R2018a release note “Renaming of Estimation and Analysis Options”.
          See Also
          nlgreyest
Introduced in R2015a
1-802
                                                                                                 nlhw
nlhw
Estimate Hammerstein-Wiener model
Syntax
sys = nlhw(Data,Orders)
sys = nlhw(Data,Orders,InputNL,OutputNL)
sys = nlhw(Data,LinModel)
sys = nlhw(Data,LinModel,InputNL,OutputNL)
sys = nlhw(Data,sys0)
Description
sys = nlhw(Data,Orders) creates and estimates a Hammerstein-Wiener model using the
estimation data, model orders and delays, and default piecewise linear functions as input and output
nonlinearity estimators.
sys = nlhw(Data,LinModel) uses a linear model to specify the model orders and delays, and
default piecewise linear functions for the input and output nonlinearity estimators.
• Update the parameters of a previously estimated model to improve the fit to the estimation data.
  In this case, the estimation algorithm uses the parameters of sys0 as initial guesses.
• Estimate the parameters of a model previously created using the idnlhw constructor. Prior to
  estimation, you can configure the model properties using dot notation.
sys = nlhw( ___ ,Options) specifies additional model estimation options. Use Options with any
of the previous syntaxes.
Examples
load iddata3
m1 = nlhw(z3,[4 2 1]);
                                                                                               1-803
1   Functions
Load data.
          load twotankdata;
          z = iddata(y,u,0.2,'Name','Two tank system');
          z1 = z(1:1000);
m = nlhw(z1,[2 3 0],InputNL,[]);
Generating a custom network nonlinearity requires the definition of a user-defined unit function.
          H = @gaussunit;
          CNet = customnet(H);
          load twotankdata;
          z = iddata(y,u,0.2,'Name','Two tank system');
          z1 = z(1:1000);
m = nlhw(z1,[5 1 3],CNet,[]);
1-804
                                                                                             nlhw
load throttledata.mat
Tr = getTrend(ThrottleData);
Tr.OutputOffset = 15;
DetrendedData = detrend(ThrottleData, Tr);
opt = oeOptions('Focus','simulation');
LinearModel = oe(DetrendedData,[1 2 1],opt);
Estimate Hammerstein-Wiener model using OE model as its linear component and saturation as its
output nonlinearity.
sys = nlhw(ThrottleData,LinearModel,[],'saturation');
Estimate a Hammerstein-Wiener Model Using idnlhw to first Define the Model Properties
load iddata1
Construct a Hammerstein-Wiener model using idnlhw to define the model properties B and F.
sys0 = idnlhw([2,2,0],[],'wavenet');
sys0.B{1} = [0.8,1];
sys0.F{1} = [1,-1.2,0.5];
sys = nlhw(z1,sys0);
Estimate a Hammerstein-Wiener model using nlhw to define the model properties B and F.
sys2 = nlhw(z1,[2,2,0],[],'wavenet','B',{[0.8,1]},'F',{[1,-1.2,0.5]});
Compare the two estimated models to see that they are equivalent.
compare(z1,sys,'g',sys2,'r--');
                                                                                            1-805
1   Functions
          load iddata3
          sys = nlhw(z3,[4 2 1],'sigmoidnet','wavenet');
sys = nlhw(z3,sys);
          Create estimation option set for nlhw to view estimation progress and to set the maximum iteration
          steps to 50.
          opt = nlhwOptions;
          opt.Display = 'on';
          opt.SearchOptions.MaxIterations = 50;
1-806
                                                                                                           nlhw
        load iddata3
        sys = nlhw(z3,[4 2 1],'sigmoidnet','deadzone',opt);
        Input Arguments
        Data — Time domain data
        iddata object
Order and delays of the linear subsystem transfer function, specified as a [nb nf nk] vector.
Dimensions of Orders:
           nb is the number of zeros plus 1, nf is the number of poles, and nk is the input delay.
        • For a MIMO transfer function with nu inputs and ny outputs, Orders is a vector of matrices.
           nb, nf, and nk are ny-by-nu matrices whose i-jth entry specifies the orders and delay of the
           transfer function from the jth input to the ith output.
        Specifying a character vector, for example 'sigmoidnet', creates a nonlinearity estimator object
        with default settings. Use object representation instead to configure the properties of a nonlinearity
        estimator.
        InputNL = wavenet;
        InputNL.NumberOfUnits = 10;
                                                                                                          1-807
1   Functions
          Alternatively, use the associated input nonlinearity estimator function with Name-Value pair
          arguments.
InputNL = wavenet('NumberOfUnits',10);
          For nu input channels, you can specify nonlinear estimators individually for each input channel by
          setting InputNL to an nu-by-1 array of nonlinearity estimators.
To specify the same nonlinearity for all inputs, specify a single input nonlinearity estimator.
          Specifying a character vector creates a nonlinearity estimator object with default settings. Use object
          representation instead to configure the properties of a nonlinearity estimator.
          OutputNL = sigmoidnet;
          OutputNL.NumberOfUnits = 10;
          Alternatively, use the associated input nonlinearity estimator function with Name-Value pair
          arguments.
OutputNL = sigmoidnet('NumberOfUnits',10);
          For ny output channels, you can specify nonlinear estimators individually for each output channel by
          setting OutputNL to an ny-by-1 array of nonlinearity estimators. To specify the same nonlinearity for
          all outputs, specify a single output nonlinearity estimator.
Discrete-time linear model used to specify the linear subsystem, specified as one of the following:
1-808
                                                                                                    nlhw
   You can also refine sys0 using the original estimation data set. If the previous estimation stopped
   when the numerical search was stuck at a local minima of the cost function, use init to first
   randomize the parameters of sys0. See sys0.Report.Termination for search stopping
   conditions. Using init does not guarantee a better solution on further refinement.
Output Arguments
sys — Estimated Hammerstein-Wiener model
idnlhw object
Estimated Hammerstein-Wiener model, returned as an idnlhw object. The model is estimated using
the specified model orders and delays, input and output nonlinearity estimators, and estimation
options.
Information about the estimation results and options used is stored in the Report property of the
model. Report has the following fields:
Report       Description
Field
Status       Summary of the model status, which indicates whether the model was created by
             construction or obtained by estimation.
Method       Estimation command used.
                                                                                                1-809
1   Functions
           Report       Description
           Field
           Fit          Quantitative assessment of the estimation, returned as a structure. See “Loss Function
                        and Model Quality Metrics” for more information on these quality metrics. The
                        structure has the following fields:
                        Field         Description
                        FitPerce Normalized root mean squared error (NRMSE) measure of how well the
                        nt       response of the model fits the estimation data, expressed as the
                                 percentage fit = 100(1-NRMSE).
                        LossFcn       Value of the loss function when the estimation completes.
                        MSE           Mean squared error (MSE) measure of how well the response of the
                                      model fits the estimation data.
                        FPE           Final prediction error for the model.
                        AIC           Raw Akaike Information Criteria (AIC) measure of model quality.
                        AICc          Small sample-size corrected AIC.
                        nAIC          Normalized AIC.
                        BIC           Bayesian Information Criteria (BIC).
           Parameter Estimated values of model parameters.
           s
           OptionsUs Option set used for estimation. If no custom options were configured, this is a set of
           ed        default options. See nlhwOptions for more information.
           RandState State of the random number stream at the start of estimation. Empty, [], if
                     randomization was not used during estimation. For more information, see rng in the
                     MATLAB documentation.
1-810
                                                                                                  nlhw
Report       Description
Field
DataUsed     Attributes of the data used for estimation, returned as a structure with the following
             fields:
             Field         Description
             Name          Name of the data set.
             Type          Data type.
             Length        Number of data samples.
             Ts            Sample time.
             InterSam Input intersample behavior, returned as one of the following values:
             ple
                      • 'zoh' — Zero-order hold maintains a piecewise-constant input signal
                         between samples.
                           • 'foh' — First-order hold maintains a piecewise-linear input signal
                             between samples.
                           • 'bl' — Band-limited behavior specifies that the continuous-time input
                             signal has zero power above the Nyquist frequency.
             InputOff Offset removed from time-domain input data during estimation. For
             set      nonlinear models, it is [].
             OutputOf Offset removed from time-domain output data during estimation. For
             fset     nonlinear models, it is [].
Terminati Termination conditions for the iterative search used for prediction error minimization.
on        Structure with the following fields:
             Field         Description
             WhyStop       Reason for terminating the numerical search.
             Iteratio Number of search iterations performed by the estimation algorithm.
             ns
             FirstOrd ∞-norm of the gradient search vector when the search algorithm
             erOptima terminates.
             lity
             FcnCount Number of times the objective function was called.
             UpdateNo Norm of the gradient search vector in the last iteration. Omitted when the
             rm       search method is 'lsqnonlin' or 'fmincon'.
             LastImpr Criterion improvement in the last iteration, expressed as a percentage.
             ovement Omitted when the search method is 'lsqnonlin' or 'fmincon'.
             Algorith Algorithm used by 'lsqnonlin' or 'fmincon' search method. Omitted
             m        when other search methods are used.
             For estimation methods that do not require numerical search optimization, the
             Termination field is omitted.
                                                                                                1-811
1   Functions
          Extended Capabilities
          Automatic Parallel Support
          Accelerate code by automatically running computation in parallel using Parallel Computing Toolbox™.
          Parallel computing support is available for estimation using the lsqnonlin search method (requires
          Optimization Toolbox). To enable parallel computing, use nlhwOptions, set SearchMethod to
          'lsqnonlin', and set SearchOptions.Advanced.UseParallel to true.
For example:
          opt = nlhwOptions;
          opt.SearchMethod = 'lsqnonlin';
          opt.SearchOptions.Advanced.UseParallel = true;
          See Also
          aic | customnet | deadzone | fpe | goodnessOfFit | idnlhw | idnlhw/findop | init | linapp |
          linearize | n4sid | nlhwOptions | oe | pem | poly1d | pwlinear | saturation | sigmoidnet |
          tfest | unitgain | wavenet
          Topics
          “Estimate Multiple Hammerstein-Wiener Models”
          “Estimate Hammerstein-Wiener Models Initialized Using Linear OE Models”
          “Identifying Hammerstein-Wiener Models”
          “Initialize Hammerstein-Wiener Estimation Using Linear Model”
          “Loss Function and Model Quality Metrics”
          “Regularized Estimates of Model Parameters”
          “Estimation Report”
Introduced in R2007a
1-812
                                                                                         nlhwOptions
nlhwOptions
Option set for nlhw
Syntax
opt = nlhwOptions
opt = nlhwOptions(Name,Value)
Description
opt = nlhwOptions creates the default option set for nlhw. Use dot notation to customize the
option set, if needed.
opt = nlhwOptions(Name,Value) creates an option set with options specified by one or more
Name,Value pair arguments. The options that you do not specify retain their default value.
Examples
Create estimation option set for nlhw to view estimation progress and to set the maximum iteration
steps to 50.
opt = nlhwOptions;
opt.Display = 'on';
opt.SearchOptions.MaxIterations = 50;
load iddata3
sys = nlhw(z3,[4 2 1],'sigmoidnet','deadzone',opt);
opt = nlhwOptions('InitialCondition','estimate','SearchMethod','gn');
                                                                                              1-813
1   Functions
          Input Arguments
          Name-Value Pair Arguments
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
          Example: nlhwOptions('InitialCondition','estimate')
          Handling of initial conditions during estimation using nlhw, specified as the comma-separated pair
          consisting of InitialCondition and one of the following:
          Estimation progress display setting, specified as the comma-separated pair consisting of 'Display'
          and one of the following:
          • 'noise' — Optimal weighting is automatically computed as the inverse of the estimated noise
            variance. This weighting minimizes det(E'*E), where E is the matrix of prediction errors. This
            option is not available when using 'lsqnonlin' as a 'SearchMethod'.
          • A positive semidefinite matrix, W, of size equal to the number of outputs. This weighting minimizes
            trace(E'*E*W/N), where E is the matrix of prediction errors and N is the number of data
            samples.
          Options for regularized estimation of model parameters, specified as the comma-separated pair
          consisting of 'Regularization' and a structure with fields:
1-814
                                                                                            nlhwOptions
To specify field values in Regularization, create a default nlhwOptions set and modify the fields
using dot notation. Any fields that you do not modify retain their default values.
opt = nlhwOptions;
opt.Regularization.Lambda = 1.2;
opt.Regularization.R = 0.5*eye(np);
Regularization is a technique for specifying model flexibility constraints, which reduce uncertainty in
the estimated parameter values. For more information, see “Regularized Estimates of Model
Parameters”.
Numerical search method used for iterative parameter estimation, specified as the comma-separated
pair consisting of 'SearchMethod' and one of the following:
• 'auto' — A combination of the line search algorithms, 'gn', 'lm', 'gna', and 'grad' methods
  is tried in sequence at each iteration. The first descent direction leading to a reduction in
  estimation cost is used.
• 'gn' — Subspace Gauss-Newton least squares search. Singular values of the Jacobian matrix less
  than GnPinvConstant*eps*max(size(J))*norm(J) are discarded when computing the
  search direction. J is the Jacobian matrix. The Hessian matrix is approximated as JTJ. If there is no
  improvement in this direction, the function tries the gradient direction.
• 'gna' — Adaptive subspace Gauss-Newton search. Eigenvalues less than gamma*max(sv) of the
  Hessian are ignored, where sv contains the singular values of the Hessian. The Gauss-Newton
  direction is computed in the remaining subspace. gamma has the initial value
  InitialGnaTolerance (see Advanced in 'SearchOptions' for more information). This value
  is increased by the factor LMStep each time the search fails to find a lower value of the criterion
  in fewer than five bisections. This value is decreased by the factor 2*LMStep each time a search is
  successful without any bisections.
• 'lm' — Levenberg-Marquardt least squares search, where the next parameter value is -pinv(H
  +d*I)*grad from the previous one. H is the Hessian, I is the identity matrix, and grad is the
  gradient. d is a number that is increased until a lower value of the criterion is found.
• 'grad' — Steepest descent least squares search.
                                                                                                 1-815
1   Functions
                • Constrained minimization problems when there are bounds imposed on the model parameters.
                • Model structures where the loss function is a nonlinear or non smooth function of the
                  parameters.
                • Multi-output model estimation. A determinant loss function is minimized by default for multi-
                  output model estimation. fmincon algorithms are able to minimize such loss functions directly.
                  The other search methods such as 'lm' and 'gn' minimize the determinant loss function by
                  alternately estimating the noise variance and reducing the loss value for a given noise variance
                  value. Hence, the fmincon algorithms can offer better efficiency and accuracy for multi-output
                  model estimations.
          Option set for the search algorithm, specified as the comma-separated pair consisting of
          'SearchOptions' and a search option set with fields that depend on the value of SearchMethod.
1-816
                                                                                       nlhwOptions
                                                                                            1-817
1   Functions
1-818
                                                                                        nlhwOptions
                                                                                            1-819
1   Functions
                                      • 'sqp' — Sequential
                                        quadratic programming
                                        algorithm. The algorithm
                                        satisfies bounds at all
                                        iterations, and it can recover
                                        from NaN or Inf results. It is
                                        not a large-scale algorithm.
                                        For more information, see
                                        “Large-Scale vs. Medium-
                                        Scale Algorithms”
                                        (Optimization Toolbox).
                                      • 'trust-region-
                                        reflective' — Subspace
                                        trust-region method based
                                        on the interior-reflective
                                        Newton method. It is a large-
                                        scale algorithm.
                                      • 'interior-point' —
                                        Large-scale algorithm that
                                        requires Optimization
                                        Toolbox software. The
                                        algorithm satisfies bounds at
                                        all iterations, and it can
                                        recover from NaN or Inf
                                        results.
                                      • 'active-set' — Requires
                                        Optimization Toolbox
                                        software. The algorithm can
                                        take large steps, which adds
                                        speed. It is not a large-scale
                                        algorithm.
1-820
                                                                                         nlhwOptions
To specify field values in SearchOptions, create a default nlhwOptions set and modify the fields
using dot notation. Any fields that you do not modify retain their default values.
opt = nlhwOptions;
opt.SearchOptions.MaxIterations = 50;
opt.SearchOptions.Advanced.RelImprovement = 0.5;
Additional advanced options, specified as the comma-separated pair consisting of 'Advanced' and a
structure with fields:
To specify field values in Advanced, create a default nlhwOptions set and modify the fields using
dot notation. Any fields that you do not modify retain their default values.
opt = nlhwOptions;
opt.Advanced.ErrorThreshold = 1.2;
                                                                                              1-821
1   Functions
          Output Arguments
          opt — Option set for nlhw
          nlhwOptions option set
          Compatibility Considerations
          Renaming of Estimation and Analysis Options
          The names of some estimation and analysis options were changed in R2018a. Prior names still work.
          For details, see the R2018a release note “Renaming of Estimation and Analysis Options”.
          See Also
          nlhw
Introduced in R2015a
1-822
                                                                                            noise2meas
noise2meas
Noise component of model
Syntax
noise_model = noise2meas(sys)
noise_model = noise2meas(sys,noise)
Description
noise_model = noise2meas(sys) returns the noise component, noise_model, of a linear
identified model, sys. Use noise2meas to convert a time-series model (no inputs) to an input/output
model. The converted model can be used for linear analysis, including viewing pole/zero maps, and
plotting the step response.
Input Arguments
sys
noise
• 'innovations' — Noise sources are not normalized and remain as the innovations process.
• 'normalize' — Noise sources are normalized to be independent and of unit variance.
Default: 'innovations'
Output Arguments
noise_model
G is the transfer function between the measured input, u(t), and the output, y(t). H is the noise model
and describes the effect of the disturbance, e(t), on the model’s response.
                                                                                                 1-823
1   Functions
          v(t) is white noise with independent channels and unit variances. The white-noise signal e(t)
          represents the model’s innovations and has variance LLT. The noise-variance data is stored using the
          NoiseVariance property of sys.
y(t) = He(t)
                noise2meas returns the noise channels of sys as the input channels of noise_model. The input
                channels are named using the format 'e@yk', where yk corresponds to the OutputName property
                of an output. The measured input channels of sys are discarded and the noise variance is set to
                zero.
          • If noise is 'normalize', then noise2meas first normalizes
e(t) = Lv(t)
y(t) = HLv(t)
                The input channels are named using the format 'v@yk', where yk corresponds to the
                OutputName property of an output.
          To obtain the model coefficients of noise_model in state-space form, use ssdata. Similarly, to
          obtain the model coefficients in transfer-function form, use tfdata.
Examples
Convert a time-series model to an input/output model that may be used by linear analysis tools.
          load iddata9 z9
          sys = ar(z9,4,'ls');
1-824
                                                                                           noise2meas
You can use noise_model for linear analysis functions such as step, iopzmap, etc.
Convert an identified linear model to an input/output model, and normalize its noise variance.
ans = 4×1
    0.2719
    1.6570
    0.6318
    0.2877
ans = 4×1
    0.0007
    0.0043
    0.0016
    0.0007
Compare the bode response with a model that ignores the noise variance of sys.
                                                                                                 1-825
1   Functions
          noise_model_innovation = noise2meas(sys,'innovations');
          bodemag(noise_model_normalize,noise_model_innovation);
          legend('Normalized noise variance','Ignored noise variance');
          See Also
          idssdata | noisecnv | spectrum | tfdata | zpkdata
Introduced in R2012a
1-826
                                                                                                 noisecnv
noisecnv
Transform identified linear model with noise channels to model with measured channels only
Syntax
mod1 = noisecnv(mod)
mod2 = noisecnv(mod,'normalize')
Description
mod1 = noisecnv(mod) and mod2 = noisecnv(mod,'normalize') transform an identified
linear model with noise channels to a model with measured channels only.
mod is any linear identified model, idproc, idtf, idgrey, idpoly, or idss.
The noise input channels in mod are converted as follows: Consider a model with both measured input
channels u (nu channels) and noise channels e (ny channels) with covariance matrix Λ:
    y = Gu + He
    cov(e) = Λ = LL′
where L is a lower triangular matrix. Note that mod.NoiseVariance = Λ. The model can also be
described with unit variance, using a normalized noise source v:
    y = Gu + HLv
    cov(v) = I
• mod1 = noisecnv(mod) converts the model to a representation of the system [G H] with nu+ny
  inputs and ny outputs. All inputs are treated as measured, and mod1 does not have any noise
  model. The former noise input channels have names e@yname, where yname is the name of the
  corresponding output.
• mod2 = noisecnv(mod,'norm') converts the model to a representation of the system [G HL]
  with nu+ny inputs and ny outputs. All inputs are treated as measured, and mod2 does not have
  any noise model. The former noise input channels have names v@yname, where yname is the name
  of the corresponding output. Note that the noise variance matrix factor L typically is uncertain
  (has a nonzero covariance). This is taken into account in the uncertainty description of mod2.
• If mod is a time series, that is, nu = 0, mod1 is a model that describes the transfer function H
  with measured input channels. Analogously, mod2 describes the transfer function HL.
• mod(:,[]) gives a description of the noise model characteristics as a time-series model, that is, it
  describes H and also the covariance of e. In contrast, noisecnv(m(:,[])) or noise2meas(m)
  describe just the transfer function H. To obtain a description of the normalized transfer function
  HL, use noisecnv(m(:,[]),'normalize') or noise2meas('normalize').
Converting the noise channels to measured inputs is useful to study the properties of the individual
transfer functions from noise to output. It is also useful for transforming identified linear models to
representations that do not handle disturbance descriptions explicitly.
                                                                                                   1-827
1   Functions
          Examples
          Identify a model with a measured component (G) and a non-trivial noise component (H). Compare the
          amplitude of the measured component's frequency response to the noise component's spectrum
          amplitude. You must convert the noise component into a measured one by using noisecnv if you
          want to compare its behavior against a truly measured component.
          load iddata2 z2
          sys1 = armax(z2,[2 2 2 1]); % model with noise component
          sys2 = tfest(z2,3); % model with a trivial noise component
          sys1 = noisecnv(sys1);
          sys2 = noisecnv(sys2);
          bodemag(sys1,sys2)
          See Also
          idssdata | noise2meas | tfdata | zpkdata
          Topics
          “Treating Noise Channels as Measured Inputs”
1-828
                                                                                               norm
norm
Norm of linear model
Syntax
n = norm(sys)
n = norm(sys,2)
n = norm(sys,Inf)
[n,fpeak] = norm(sys,Inf)
[n,fpeak] = norm(sys,Inf,tol)
Description
n = norm(sys) or n = norm(sys,2) returns the root-mean-squares of the impulse response of the
linear dynamic system model sys. This value is equivalent to the H2 norm on page 1-831 of sys.
n = norm(sys,Inf) returns the L∞ norm (Control System Toolbox) of sys, which is the peak gain of
the frequency response of sys across frequencies. For MIMO systems, this quantity is the peak gain
over all frequencies and all input directions, which corresponds to the peak value of the largest
singular value of sys. For stable systems, the L∞ norm is equivalent to the H∞ norm. For more
information, see hinfnorm.
[n,fpeak] = norm(sys,Inf) also returns the frequency fpeak at which the gain reaches its peak
value.
Examples
Compute the H2 and L∞ norms of the following discrete-time transfer function, with sample time 0.1
second.
Compute the H2 norm of the transfer function. The H2 norm is the root-mean-square of the impulse
response of sys.
sys = tf([1 -2.841 2.875 -1.004],[1 -2.417 2.003 -0.5488],0.1);
n2 = norm(sys)
n2 = 1.2438
                                                                                             1-829
1   Functions
[ninf,fpeak] = norm(sys,Inf)
ninf = 2.5721
fpeak = 3.0178
          Because sys is a stable system, ninf is the peak gain of the frequency response of sys, and fpeak is
          the frequency at which the peak gain occurs. Confirm these values using getPeakGain.
[gpeak,fpeak] = getPeakGain(sys)
gpeak = 2.5721
fpeak = 3.0178
          Input Arguments
          sys — Dynamic system
          dynamic system model | model array
          Input dynamic system, specified as any SISO or MIMO linear dynamic system model or model array.
          sys can be continuous-time or discrete-time.
          Output Arguments
          n — H2 or L∞ norm
          scalar | array
          Frequency at which the gain achieves the peak value gpeak, returned as a nonnegative real scalar
          value or an array of nonnegative real values. The frequency is expressed in units of rad/TimeUnit,
          relative to the TimeUnit property of sys.
1-830
                                                                                                  norm
More About
H2 norm
The H2 norm of a stable system H is the root-mean-square of the impulse response of the system. The
H2 norm measures the steady-state covariance (or power) of the output response y = Hw to unit
white noise inputs w:
         2                         T                          T
     H   2   = limE y(t) y(t) ,        E w(t)w(τ)                  = δ t−τ I.
                 t    ∞
The H2 norm of a continuous-time system with transfer function H(s) is given by:
                          ∫
                      1       ∞                 H
     H   2   =                    Trace H( jω) H( jω)  dω .
                     2π   −∞
For a discrete-time system with transfer function H(z), the H2 norm is given by:
                          ∫ Trace H(e
                      1       π
     H       =                               jω)H H(e jω)   dω .
         2           2π   −π
• sys is unstable.
• sys is continuous and has a nonzero feedthrough (that is, nonzero gain at the frequency ω = ∞).
L-infinity norm
The L∞ norm of a SISO linear system is the peak gain of the frequency response. For a MIMO system,
the L∞ norm is the peak gain across all input/output channels.
     Hs       L∞     = max H jω                    (SISO)
                         ω∈R
For stable systems, the L∞ norm is equivalent to the H∞ norm. For more information, see hinfnorm.
For a system with unstable poles, the H∞ norm is infinite. For all systems, norm returns the L∞ norm,
which is the peak gain without regard to system stability.
                                                                                                1-831
1   Functions
          Algorithms
          After converting sys to a state space model, norm uses the same algorithm as covar for the H2
          norm. For the L∞ norm, norm uses the algorithm of [1]. norm computes the peak gain using the
          SLICOT library. For more information about the SLICOT library, see http://slicot.org.
          References
          [1] Bruisma, N.A. and M. Steinbuch, "A Fast Algorithm to Compute the H∞-Norm of a Transfer
                  Function Matrix," System Control Letters, 14 (1990), pp. 287-293.
          See Also
          freqresp | getPeakGain | hinfnorm | sigma
1-832
                                                                                               nparams
nparams
Number of model parameters
Syntax
np = nparams(sys)
np = nparams(sys,'free')
Description
np = nparams(sys) returns the number of parameters in the identified model sys.
Note Not all model coefficients are parameters, such as the leading entry of the denominator
polynomials in idpoly and idtf models.
Input Arguments
sys
Output Arguments
np
idgrey models can contain non-scalar parameters. nparams accounts for each individual entry of
the non-scalar parameters in the total parameter count.
Examples
Obtain the number of parameters of a transfer function model.
                                                                                                1-833
1   Functions
          See Also
          idfrd | idgrey | idpoly | idproc | idss | idtf | size
Introduced in R2012a
1-834
                                                                                                 nuderst
nuderst
Set step size for numerical differentiation
Syntax
nds = nuderst(pars)
Description
Many estimation functions use numerical differentiation with respect to the model parameters to
compute their values.
The step size used in these numerical derivatives is determined by the nuderst command. The
output argument nds is a row vector whose kth entry gives the increment to be used when
differentiating with respect to the kth element of the parameter vector pars.
The default version of nuderst uses a very simple method. The step size is the maximum of 10-4
times the absolute value of the current parameter and 10-7. You can adjust this to the actual value of
the corresponding parameter by editing nuderst. Note that the nominal value, for example 0, of a
parameter might not reflect its normal size.
                                                                                                 1-835
1   Functions
          nyquist
          Nyquist plot of frequency response
          Syntax
          nyquist(sys)
          nyquist(sys,w)
          nyquist(sys1,sys2,...,sysN)
          nyquist(sys1,sys2,...,sysN,w)
          nyquist(sys1,'PlotStyle1',...,sysN,'PlotStyleN')
          [re,im,w] = nyquist(sys)
          [re,im] = nyquist(sys,w)
          [re,im,w,sdre,sdim] = nyquist(sys)
          Description
          nyquist creates a Nyquist plot of the frequency response of a dynamic system model. When invoked
          without left-hand arguments, nyquist produces a Nyquist plot on the screen. Nyquist plots are used
          to analyze system properties including gain margin, phase margin, and stability.
          nyquist(sys) creates a Nyquist plot of a dynamic system sys. This model can be continuous or
          discrete, and SISO or MIMO. In the MIMO case, nyquist produces an array of Nyquist plots, each
          plot showing the response of one particular I/O channel. The frequency points are chosen
          automatically based on the system poles and zeros.
          nyquist(sys,w) explicitly specifies the frequency range or frequency points to be used for the plot.
          To focus on a particular frequency interval, set w = {wmin,wmax}. To use particular frequency
          points, set w to the vector of desired frequencies. Use logspace to generate logarithmically spaced
          frequency vectors. Frequencies must be in rad/TimeUnit, where TimeUnit is the time units of the
          input dynamic system, specified in the TimeUnit property of sys.
          [re,im,w] = nyquist(sys) and [re,im] = nyquist(sys,w) return the real and imaginary
          parts of the frequency response at the frequencies w (in rad/TimeUnit). re and im are 3-D arrays
          (see "Arguments" below for details).
          [re,im,w,sdre,sdim] = nyquist(sys) also returns the standard deviations of re and im for the
          identified system sys.
          Arguments
          The output arguments re and im are 3-D arrays with dimensions
1-836
                                                                                             nyquist
For SISO systems, the scalars re(1,1,k) and im(1,1,k) are the real and imaginary parts of the
response at the frequency ωk = w(k).
     re(1, 1, k) = Re h( jωk)
     im(1, 1, k) = Im h( jwk)
For MIMO systems with transfer function H(s), re(:,:,k) and im(:,:,k) give the real and
imaginary parts of H(jωk) (both arrays with as many rows as outputs and as many columns as inputs).
Thus,
     re (i, j, k) = Re hi j( jωk)
     im (i, j, k) = Im hi j( jωk)
Examples
Create the following transfer function and plot its Nyquist response.
        2s2 + 5s + 1
Hs =                 .
        s2 + 2s + 3
                                                                                             1-837
1   Functions
          The nyquist function can display a grid of M-circles, which are the contours of constant closed-loop
          magnitude. M-circles are defined as the locus of complex numbers where the following quantity is a
          constant value across frequency.
                      G jω
          T jω =    1 + G jω
                               .
          Here, ω is the frequency in radians/TimeUnit, where TimeUnit is the system time units, and G is
          the collection of complex numbers that satisfy the constant magnitude requirement.
          To display the grid of M-circles, right-click in the plot and select Grid. Alternatively, use the grid
          command.
grid on
1-838
                                                                                                nyquist
Compute the standard deviations of the real and imaginary parts of the frequency response of an
identified model. Use this data to create a 3σ plot of the response uncertainty.
sys_p = tfest(z2,2);
Obtain the standard deviations for the real and imaginary parts of the frequency response for a set of
512 frequencies, w.
w = linspace(-10*pi,10*pi,512);
[re,im,wout,sdre,sdim] = nyquist(sys_p,w);
Here re and im are the real and imaginary parts of the frequency response, and sdre and sdim are
their standard deviations, respectively. The frequencies in wout are the same as the frequencies you
specified in w.
                                                                                                1-839
1   Functions
          re = squeeze(re);
          im = squeeze(im);
          sdre = squeeze(sdre);
          sdim = squeeze(sdim);
          plot(re,im,'b',re+3*sdre,im+3*sdim,'k:',re-3*sdre,im-3*sdim,'k:')
          xlabel('Real Axis');
          ylabel('Imaginary Axis');
          Tips
          • You can change the properties of your plot, for example the units. For information on the ways to
            change properties of your plots, see “Ways to Customize Plots” (Control System Toolbox). For the
            most flexibility in customizing plot properties, use the nyquistplot command instead of
            nyquist.
          • There are two zoom options available from the right-click menu that apply specifically to Nyquist
            plots:
                • Full View — Clips unbounded branches of the Nyquist plot, but still includes the critical point
                  (–1, 0).
                • Zoom on (-1,0) — Zooms around the critical point (–1,0). (To access critical-point zoom
                  programmatically, use nyquistplot instead.)
          • To activate data markers that display the real and imaginary values at a given frequency, click
            anywhere on the curve. The following figure shows a nyquist plot with a data marker.
1-840
                                                                      nyquist
Algorithms
See bode.
See Also
Linear System Analyzer | bode | evalfr | freqresp | nichols | sigma
                                                                      1-841
1   Functions
            nyquistoptions
            List of Nyquist plot options
            Syntax
            P = nyquistoptions
            P = nyquistoptions('cstprefs')
            Description
            P = nyquistoptions returns the default options for Nyquist plots. You can use these options to
            customize the Nyquist plot appearance using the command line.
            P = nyquistoptions('cstprefs') initializes the plot options with the options you selected in the
            Control System and System Identification Toolbox Preferences Editor. For more information about the
            editor, see “Toolbox Preferences Editor”.
Option                         Description
Title, XLabel, YLabel          Label text and style
TickLabel                      Tick label style
Grid                           Show or hide the grid
                               Specified as one of the following values: 'off' | 'on'
                               Default: 'off'
GridColor                      Color of the grid lines
                               Specified as one of the following: Vector of RGB values in the range [0,1] |
                               character vector of color name | 'none'. For example, for yellow color, specify as
                               one of the following: [1 1 0], 'yellow', or 'y'.
                               Default: [0.15,0.15,0.15]
XlimMode, YlimMode             Limit modes
Xlim, Ylim                     Axes limits
IOGrouping                     Grouping of input-output pairs
                               Specified as one of the following values: 'none' |'inputs'|'outputs'|'all'
                               Default: 'none'
InputLabels, OutputLabels      Input and output label styles
InputVisible, OutputVisible    Visibility of input and output channels
1-842
                                                                                    nyquistoptions
Option            Description
FreqUnits         Frequency units, specified as one of the following values:
                  • 'Hz'
                  • 'rad/second'
                  • 'rpm'
                  • 'kHz'
                  • 'MHz'
                  • 'GHz'
                  • 'rad/nanosecond'
                  • 'rad/microsecond'
                  • 'rad/millisecond'
                  • 'rad/minute'
                  • 'rad/hour'
                  • 'rad/day'
                  • 'rad/week'
                  • 'rad/month'
                  • 'rad/year'
                  • 'cycles/nanosecond'
                  • 'cycles/microsecond'
                  • 'cycles/millisecond'
                  • 'cycles/hour'
                  • 'cycles/day'
                  • 'cycles/week'
                  • 'cycles/month'
                  • 'cycles/year'
Default: 'rad/s'
                  You can also specify 'auto' which uses frequency units rad/TimeUnit relative
                  to system time units specified in the TimeUnit property. For multiple systems
                  with different time units, the units of the first system are used.
MagUnits          Magnitude units
                  Specified as one of the following values: 'dB' | 'abs'
                  Default: 'dB'
PhaseUnits        Phase units
                  Specified as one of the following values: 'deg' | 'rad'
                  Default: 'deg'
ShowFullContour   Show response for negative frequencies
                  Specified as one of the following values: 'on' | 'off'
                  Default: 'on'
                                                                                           1-843
1   Functions
Option                       Description
ConfidenceRegionNumberS Number of standard deviations to use to plotting the response confidence region
D                       (identified models only).
                        Default: 1.
ConfidenceRegionDisplaySp The frequency spacing of confidence ellipses. For identified models only.
acing                     Default: 5, which means the confidence ellipses are shown at every 5th
                          frequency sample.
          Examples
          This example shows how to create a Nyquist plot displaying the full contour (the response for both
          positive and negative frequencies).
          P = nyquistoptions;
          P.ShowFullContour = 'on';
          h = nyquistplot(tf(1,[1,.2,1]),P);
          See Also
          getoptions | nyquist | nyquistplot | setoptions | setoptions | showConfidence
Introduced in R2012a
1-844
                                                                                                nyquistplot
nyquistplot
Nyquist plot with additional plot customization options
Syntax
h = nyquistplot(sys)
nyquistplot(sys,{wmin,wmax})
nyquistplot(sys,w)
nyquistplot(sys1,sys2,...,w)
nyquistplot(AX,...)
nyquistplot(..., plotoptions)
Description
h = nyquistplot(sys) draws the Nyquist plot of the dynamic system model sys. It also returns
the plot handle h. You can use this handle to customize the plot with the getoptions and
setoptions commands. Type
help nyquistoptions
The frequency range and number of points are chosen automatically. See bode for details on the
notion of frequency in discrete time.
nyquistplot(sys,{wmin,wmax}) draws the Nyquist plot for frequencies between wmin and wmax
(in rad/TimeUnit, where TimeUnit is the time units of the input dynamic system, specified in the
TimeUnit property of sys).
nyquistplot(sys1,'r',sys2,'y--',sys3,'gx')
nyquistplot(..., plotoptions) plots the Nyquist response with the options specified in
plotoptions. Type
help nyquistoptions
                                                                                                    1-845
1   Functions
          Examples
          Customize Nyquist Plot Title
Create a Nyquist plot of a dynamic system model and store a handle to the plot.
          sys = tf(100,[1,2,1]);
          h = nyquistplot(sys);
          Change the plot title to read "Nyquist Plot of sys." To do so, use getoptions to extract the existing
          plot options from the plot handle h.
opt = getoptions(h)
opt =
                                     FreqUnits:      'rad/s'
                                      MagUnits:      'dB'
                                    PhaseUnits:      'deg'
                               ShowFullContour:      'on'
                      ConfidenceRegionNumberSD:      1
                ConfidenceRegionDisplaySpacing:      5
                                    IOGrouping:      'none'
                                   InputLabels:      [1x1 struct]
                                  OutputLabels:      [1x1 struct]
                                  InputVisible:      {'on'}
                                 OutputVisible:      {'on'}
1-846
                                                                                       nyquistplot
opt.Title
Change the String field of the Title structure, and use setoptions to apply the change to the
plot.
                                                                                           1-847
1   Functions
          Plot the Nyquist frequency response of a dynamic system. Assign a variable name to the plot handle
          so that you can access it for further manipulation.
          sys = tf(100,[1,2,1]);
          h = nyquistplot(sys);
1-848
                                                                                                nyquistplot
Zoom in on the critical point, (–1,0). You can do so interactively by right-clicking on the plot and
selecting Zoom on (-1,0). Alternatively, use the zoomcp command on the plot handle h.
zoomcp(h)
                                                                                                    1-849
1   Functions
          Compare the frequency responses of identified state-space models of order 2 and 6 along with their
          1-std confidence regions rendered at every 50th frequency sample.
          load iddata1
          sys1 = n4sid(z1,2); % discrete-time IDSS model of order 2
          sys2 = n4sid(z1,6); % discrete-time IDSS model of order 6
          Both models produce about 76% fit to data. However, sys2 shows higher uncertainty in its frequency
          response, especially close to Nyquist frequency as shown by the plot. To see this, generate a Nyquist
          plot and show the confidence region at a subset of the points at which the Nyquist response is
          displayed.
          w = linspace(10,10*pi,256);
          h = nyquistplot(sys1,sys2,w);
          setoptions(h,'ConfidenceRegionDisplaySpacing',50,...
                       'ShowFullContour','off');
          To turn on the confidence region display, right-click the plot and select Characteristics >
          Confidence Region.
1-850
                                                                                           nyquistplot
Tips
• You can change the properties of your plot, for example the units. For information on the ways to
  change properties of your plots, see “Ways to Customize Plots” (Control System Toolbox).
• There are two zoom options available from the right-click menu that apply specifically to Nyquist
  plots:
   • Full View — Clips unbounded branches of the Nyquist plot, but still includes the critical point
     (–1, 0).
   • Zoom on (-1,0) — Zooms around the critical point (–1,0). To access critical-point zoom
     programmatically, use the zoomcp command. See “Zoom on Critical Point” on page 1-848.
• To activate data markers that display the real and imaginary values at a given frequency, click
  anywhere on the curve. The following figure shows a nyquist plot with a data marker.
                                                                                               1-851
1   Functions
          See Also
          getoptions | nyquist | setoptions | showConfidence
Introduced in R2012a
1-852
                                                                                                     oe
oe
Estimate output-error polynomial model using time-domain or frequency-domain data
Syntax
sys   =   oe(data,[nb nf nk])
sys   =   oe(data,[nb nf nk],Name,Value)
sys   =   oe(data,init_sys)
sys   =   oe(data, ___ ,opt)
Description
Output-error (OE) models are a special configuration of polynomial models, having only two active
polynomials—B and F. OE models represent conventional transfer functions that relate measured
inputs to outputs while also including white noise as an additive output disturbance. You can estimate
OE models using time- and frequency-domain data. The tfest command offers the same functionality
as oe. For tfest, you specify the model orders using number of poles and zeros rather than
polynomial degrees. For continuous-time estimation, tfest provides faster and more accurate
results, and is recommended.
               B(q)
      y(t) =        u(t − nk) + e(t)
               F(q)
y(t) is the output, u(t) is the input, and e(t) is the error.
oe estimates sys using the measured input-output data data, which can be in the time or the
frequency domain. The orders [nb nf nk] define the number of parameters in each component of
the estimated polynomial.
sys = oe(data,init_sys) uses the linear system init_sys to configure the initial
parameterization of sys.
sys = oe(data, ___ ,opt) estimates a polynomial model using the option set opt to specify
estimation behavior. You can use this syntax with any of the previous input-argument combinations.
Examples
Estimate an OE polynomial from time-domain data using two methods to specify input delay.
load iddata1 z1
                                                                                               1-853
1   Functions
          Set the orders of the B and F polynomials nb and nf. Set the input delay nk to one sample. Compute
          the model sys.
          nb = 2;
          nf = 2;
          nk = 1;
          sys = oe(z1,[nb nf nk]);
compare(z1,sys)
          The plot shows that the fit percentage between the simulated model and the estimation data is
          greater than 70%.
          Instead of using nk, you can also use the name-value pair argument 'InputDelay' to specify the
          one-sample delay.
          nk = 0;
          sys1 = oe(z1,[nb nf nk],'InputDelay',1);
          figure
          compare(z1,sys1)
1-854
                                                                                             oe
You can view more information about the estimation by exploring the idpoly property sys.Report.
sys.Report
ans =
              Status:        'Estimated using OE'
              Method:        'OE'
    InitialCondition:        'zero'
                 Fit:        [1x1 struct]
          Parameters:        [1x1 struct]
         OptionsUsed:        [1x1 idoptions.polyest]
           RandState:        [1x1 struct]
            DataUsed:        [1x1 struct]
         Termination:        [1x1 struct]
For example, find out more information about the termination conditions.
sys.Report.Termination
                                                                                         1-855
1   Functions
LastImprovement: 5.1744e-06
          The report includes information on the number of iterations and the reason the estimation stopped
          iterating.
The idfrd object data contains the continuous-time frequency response for the following model:
                              s+3
                G(s) =
                         s3 + 2s2 + s + 1
1-856
                                                                                                  oe
Estimate a high-order OE model from data collected by simulating a high-order system. Determine
the regularization constants by trial and error and use the values for model estimation.
m1 = oe(m0simdata,[30 30 1]);
Obtain a regularized OE model by determining the Lambda value using trial and error.
opt = oeOptions;
opt.Regularization.Lambda = 1;
m2 = oe(m0simdata,[30 30 1],opt);
opt = compareOptions('InitialCondition','z');
compare(m0simdata,m1,m2,opt);
The regularized model m2 produces a better fit than the unregularized model m1.
                                                                                            1-857
1   Functions
          h = bodeplot(m1,m2);
          opt = getoptions(h);
          opt.PhaseMatching = 'on';
          opt.ConfidenceRegionNumberSD = 3;
          opt.PhaseMatching = 'on';
          setoptions(h,opt);
          showConfidence(h);
The regularized model m2 has a reduced variance compared to the unregularized model m1.
An iddata object data contains the discrete-time frequency response for the following model:
                          1000
                G(s) =
                         s + 500
1-858
                                                                                                   oe
Ts
Ts = 1.0000e-03
data.Ts
ans = 1.0000e-03
You can estimate a continuous model from data by limiting the input and output frequency bands to
the Nyquist frequency. To do so, specify the estimation prefilter option 'WeightingFilter' to define
a passband from 0 to 0.5*pi/Ts rad/s. The software ignores any response values with frequencies
outside of that passband.
data.Ts = 0;
nb = 1;
nf = 3;
sys = oe(data,[nb nf],opt);
Input Arguments
data — Estimation data
iddata object | frd object | idfrd object
For time-domain estimation, data must be an iddata object containing the input and output signal
values.
Time-domain estimation data must be uniformly sampled. By default, the software sets the sample
time of the model to the sample time of the estimation data.
For multiexperiment data, the sample times and intersample behavior of all the experiments must
match.
You can compute discrete-time models from time-domain data or discrete-time frequency-domain
data. Use tfest to compute continuous-time models.
                                                                                              1-859
1   Functions
                          B(q)
                 y(t) =        u(t − nk) + e(t)
                          F(q)
          where y(t) is the output, u(t) is the input, and e(t) is the error, the elements of [nb nf nk] are as
          follows:
          • nb — Order of the B(q) polynomial + 1, which is equivalent to the length of the B(q) polynomial.
            nb is an Ny-by-Nu matrix. Ny is the number of outputs and Nu is the number of inputs.
          • nf — Order of the F polynomial. nf is an Ny-by-Nu matrix.
          • nk — Input delay, expressed as the number of samples. nk is an Ny-by-Nu matrix. The delay
            appears as leading zeros of the B polynomial.
          For estimation using continuous-time frequency-domain data, specify only [nb nf] and omit nk. For
          an example, see “Estimate Continuous-Time OE Model Using Frequency Response” on page 1-856.
          Linear system that configures the initial parameterization of sys, specified as an idpoly model,
          another linear model, or a structure. You obtain init_sys either by performing an estimation using
          measured data or by direct construction.
          If init_sys is an idpoly model of the OE structure, oe uses the parameter values of init_sys as
          the initial guess for estimating sys. The sample time of init_sys must match the sample time of the
          data.
          Use the Structure property of init_sys to configure initial guesses and constraints for B(q) and
          F(q). For example:
          • To specify an initial guess for the F(q) term of init_sys, set init_sys.Structure.F.Value as
            the initial guess.
          • To specify constraints for the B(q) term of init_sys:
          If init_sys is not a polynomial model of the OE structure, the software first converts init_sys to
          an OE structure model. oe uses the parameters of the resulting model as the initial guess for
          estimating sys.
          If you do not specify opt and init_sys was obtained by estimation, then the software uses
          estimation options from init_sys.Report.OptionsUsed.
1-860
                                                                                                    oe
Estimation options, specified as an oeOptions option set. Options specified by opt include:
• Estimation objective
• Handling of initial conditions
• Numerical search method and the associated options
For examples of specifying estimation options, see “Estimate Continuous Model Using Band-Limited
Discrete-Time Frequency-Domain Data” on page 1-858.
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Example: 'InputDelay',1
Input delays for each input channel, specified as the comma-separated pair consisting of
'InputDelay' and a numeric vector.
• For continuous-time models, specify 'InputDelay' in the time units stored in the TimeUnit
  property.
• For discrete-time models, specify 'InputDelay' in integer multiples of the sample time Ts. For
  example, setting 'InputDelay' to 3 specifies a delay of three sampling periods.
For a system with Nu inputs, set InputDelay to an Nu-by-1 vector. Each entry of this vector is a
numerical value that represents the input delay for the corresponding input channel.
Transport delays for each input-output pair, specified as the comma-separated pair consisting of
'IODelay' and a numeric array.
• For continuous-time models, specify 'IODelay' in the time units stored in the TimeUnit
  property.
• For discrete-time models, specify 'IODelay' in integer multiples of the sample time Ts. For
  example, setting 'IODelay' to 4 specifies a transport delay of four sampling periods.
For a system with Nu inputs and Ny outputs, set 'IODelay' to an Ny-by-Nu matrix. Each entry is an
integer value representing the transport delay for the corresponding input-output pair.
You can specify 'IODelay' as an alternative to the nk value. Doing so simplifies the model structure
by reducing the number of leading zeros in the B polynomial. In particular, you can represent
max(nk-1,0) leading zeros as input-output delays using 'IODelay' instead.
                                                                                               1-861
1   Functions
          Output Arguments
          sys — OE polynomial model
          idpoly object
          OE polynomial model that fits the estimation data, returned as an idpoly model object. This model is
          created using the specified model orders, delays, and estimation options. The sample time of sys
          matches the sample time of the estimation data. Therefore, sys is always a discrete-time model when
          estimated from time-domain data. For continuous-time model identification using time-domain data,
          use tfest.
          The Report property of the model stores information about the estimation results and options used.
          Report has the following fields.
           Report      Description
           Field
           Status      Summary of the model status, which indicates whether the model was created by
                       construction or obtained by estimation.
           Method      Estimation command used.
           InitialCo Handling of initial conditions during model estimation, returned as one of the following
           ndition   values:
                       This field is especially useful to view how the initial conditions were handled when the
                       InitialCondition option in the estimation option set is 'auto'.
           Fit         Quantitative assessment of the estimation, returned as a structure. See “Loss Function
                       and Model Quality Metrics” for more information on these quality metrics. The
                       structure has the following fields:
                        Field        Description
                        FitPerce Normalized root mean squared error (NRMSE) measure of how well the
                        nt       response of the model fits the estimation data, expressed as the
                                 percentage fit = 100(1-NRMSE).
                        LossFcn      Value of the loss function when the estimation completes.
                        MSE          Mean squared error (MSE) measure of how well the response of the
                                     model fits the estimation data.
                        FPE          Final prediction error for the model.
                        AIC          Raw Akaike Information Criteria (AIC) measure of model quality.
                        AICc         Small sample-size corrected AIC.
                        nAIC         Normalized AIC.
                        BIC          Bayesian Information Criteria (BIC).
1-862
                                                                                                      oe
Report       Description
Field
Parameter Estimated values of model parameters.
s
OptionsUs Option set used for estimation. If no custom options were configured, this is a set of
ed        default options. See oeOptions for more information.
RandState State of the random number stream at the start of estimation. Empty, [], if
          randomization was not used during estimation. For more information, see rng in the
          MATLAB documentation.
DataUsed     Attributes of the data used for estimation, returned as a structure with the following
             fields:
             Field         Description
             Name          Name of the data set.
             Type          Data type.
             Length        Number of data samples.
             Ts            Sample time.
             InterSam Input intersample behavior, returned as one of the following values:
             ple
                      • 'zoh' — Zero-order hold maintains a piecewise-constant input signal
                         between samples.
                           • 'foh' — First-order hold maintains a piecewise-linear input signal
                             between samples.
                           • 'bl' — Band-limited behavior specifies that the continuous-time input
                             signal has zero power above the Nyquist frequency.
             InputOff Offset removed from time-domain input data during estimation. For
             set      nonlinear models, it is [].
             OutputOf Offset removed from time-domain output data during estimation. For
             fset     nonlinear models, it is [].
                                                                                                1-863
1   Functions
           Report          Description
           Field
           Terminati Termination conditions for the iterative search used for prediction error minimization.
           on        Structure with the following fields:
                            Field        Description
                            WhyStop      Reason for terminating the numerical search.
                            Iteratio Number of search iterations performed by the estimation algorithm.
                            ns
                            FirstOrd ∞-norm of the gradient search vector when the search algorithm
                            erOptima terminates.
                            lity
                            FcnCount Number of times the objective function was called.
                            UpdateNo Norm of the gradient search vector in the last iteration. Omitted when the
                            rm       search method is 'lsqnonlin' or 'fmincon'.
                            LastImpr Criterion improvement in the last iteration, expressed as a percentage.
                            ovement Omitted when the search method is 'lsqnonlin' or 'fmincon'.
                            Algorith Algorithm used by 'lsqnonlin' or 'fmincon' search method. Omitted
                            m        when other search methods are used.
                           For estimation methods that do not require numerical search optimization, the
                           Termination field is omitted.
          More About
          Output-Error (OE) Model
                         B(q)
                y(t) =        u(t − nk) + e(t)
                         F(q)
          The orders of the numerator and denominator are nb and nf, similar to the discrete-time case.
          However, the sample delay nk does not exist in the continuous case, and you should not specify nk
1-864
                                                                                                 oe
when you command the estimation. Instead, express any system delay using the name-value pair
argument 'IODelay' along with the system delay in the time units that are stored in the property
TimeUnit. For example, suppose that your continuous system has a delay of iod seconds. Use model
= oe(data,[nb nf],'IODelay',iod).
Extended Capabilities
Automatic Parallel Support
Accelerate code by automatically running computation in parallel using Parallel Computing Toolbox™.
Parallel computing support is available for estimation using the lsqnonlin search method (requires
Optimization Toolbox). To enable parallel computing, use oeOptions, set SearchMethod to
'lsqnonlin', and set SearchOptions.Advanced.UseParallel to true.
For example:
opt = oeOptions;
opt.SearchMethod = 'lsqnonlin';
opt.SearchOptions.Advanced.UseParallel = true;
See Also
armax | arx | bj | compare | iddata | idfrd | idpoly | iv4 | n4sid | oeOptions | polyest | sim
| tfest
Topics
“What Are Polynomial Models?”
“Data Supported by Polynomial Models”
“Regularized Estimates of Model Parameters”
                                                                                             1-865
1   Functions
          oeOptions
          Option set for oe
          Syntax
          opt = oeOptions
          opt = oeOptions(Name,Value)
          Description
          opt = oeOptions creates the default options set for oe.
          opt = oeOptions(Name,Value) creates an option set with the options specified by one or more
          Name,Value pair arguments.
          Input Arguments
          Name-Value Pair Arguments
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Handling of initial conditions during estimation, specified as one of the following values:
          Weighting prefilter applied to the loss function to be minimized during estimation. To understand the
          effect of WeightingFilter on the loss function, see “Loss Function and Model Quality Metrics”.
1-866
                                                                                                oeOptions
   Passbands are expressed in rad/TimeUnit for time-domain data and in FrequencyUnit for
   frequency-domain data, where TimeUnit and FrequencyUnit are the time and frequency units
   of the estimation data.
• SISO filter — Specify a single-input-single-output (SISO) linear filter in one of the following ways:
      This option calculates the weighting function as a product of the filter and the input spectrum
      to estimate the transfer function.
• Weighting vector — Applicable for frequency-domain data only. Specify a column vector of
  weights. This vector must have the same length as the frequency vector of the data set,
  Data.Frequency. Each input and output response in the data is multiplied by the corresponding
  weight at that frequency.
Control whether to enforce stability of estimated model, specified as the comma-separated pair
consisting of 'EnforceStability' and either true or false.
Use this option when estimating models using frequency-domain data. Models estimated using time-
domain data are always stable.
Data Types: logical
If EstimateCovariance is true, then use getcov to fetch the covariance matrix from the
estimated model.
Specify whether to display the estimation progress, specified as one of the following values:
• 'on' — Information on model structure and estimation results are displayed in a progress-viewer
  window.
• 'off' — No progress or results information is displayed.
Removal of offset from time-domain input data during estimation, specified as the comma-separated
pair consisting of 'InputOffset' and one of the following:
• A column vector of positive integers of length Nu, where Nu is the number of inputs.
                                                                                                  1-867
1   Functions
          • [] — Indicates no offset.
          • Nu-by-Ne matrix — For multi-experiment data, specify InputOffset as an Nu-by-Ne matrix. Nu
            is the number of inputs, and Ne is the number of experiments.
Each entry specified by InputOffset is subtracted from the corresponding input data.
          Removal of offset from time-domain output data during estimation, specified as the comma-separated
          pair consisting of 'OutputOffset' and one of the following:
Each entry specified by OutputOffset is subtracted from the corresponding output data.
          Options for regularized estimation of model parameters. For more information on regularization, see
          “Regularized Estimates of Model Parameters”.
Specify a positive scalar to add the regularization term to the estimation cost.
                Default: 0
          • R — Weighting matrix.
                Specify a vector of nonnegative numbers or a square positive semi-definite matrix. The length
                must be equal to the number of free parameters of the model.
                For black-box models, using the default value is recommended. For structured and grey-box
                models, you can also specify a vector of np positive numbers such that each entry denotes the
                confidence in the value of the associated parameter.
                The default value of 1 implies a value of eye(npfree), where npfree is the number of free
                parameters.
                Default: 1
          • Nominal — The nominal value towards which the free parameters are pulled during estimation.
                The default value of zero implies that the parameter values are pulled towards zero. If you are
                refining a model, you can set the value to 'model' to pull the parameters towards the parameter
                values of the initial model. The initial parameter values must be finite for this setting to work.
Default: 0
1-868
                                                                                              oeOptions
Numerical search method used for iterative parameter estimation, specified as the comma-separated
pair consisting of 'SearchMethod' and one of the following:
• 'auto' — A combination of the line search algorithms, 'gn', 'lm', 'gna', and 'grad' methods
  is tried in sequence at each iteration. The first descent direction leading to a reduction in
  estimation cost is used.
• 'gn' — Subspace Gauss-Newton least squares search. Singular values of the Jacobian matrix less
  than GnPinvConstant*eps*max(size(J))*norm(J) are discarded when computing the
  search direction. J is the Jacobian matrix. The Hessian matrix is approximated as JTJ. If there is no
  improvement in this direction, the function tries the gradient direction.
• 'gna' — Adaptive subspace Gauss-Newton search. Eigenvalues less than gamma*max(sv) of the
  Hessian are ignored, where sv contains the singular values of the Hessian. The Gauss-Newton
  direction is computed in the remaining subspace. gamma has the initial value
  InitialGnaTolerance (see Advanced in 'SearchOptions' for more information). This value
  is increased by the factor LMStep each time the search fails to find a lower value of the criterion
  in fewer than five bisections. This value is decreased by the factor 2*LMStep each time a search is
  successful without any bisections.
• 'lm' — Levenberg-Marquardt least squares search, where the next parameter value is -pinv(H
  +d*I)*grad from the previous one. H is the Hessian, I is the identity matrix, and grad is the
  gradient. d is a number that is increased until a lower value of the criterion is found.
• 'grad' — Steepest descent least squares search.
• 'lsqnonlin' — Trust-region-reflective algorithm of lsqnonlin. Requires Optimization Toolbox
  software.
• 'fmincon' — Constrained nonlinear solvers. You can use the sequential quadratic programming
  (SQP) and trust-region-reflective algorithms of the fmincon solver. If you have Optimization
  Toolbox software, you can also use the interior-point and active-set algorithms of the fmincon
  solver. Specify the algorithm in the SearchOptions.Algorithm option. The fmincon algorithms
  may result in improved estimation results in the following scenarios:
   • Constrained minimization problems when there are bounds imposed on the model parameters.
   • Model structures where the loss function is a nonlinear or non smooth function of the
     parameters.
   • Multi-output model estimation. A determinant loss function is minimized by default for multi-
     output model estimation. fmincon algorithms are able to minimize such loss functions directly.
     The other search methods such as 'lm' and 'gn' minimize the determinant loss function by
     alternately estimating the noise variance and reducing the loss value for a given noise variance
     value. Hence, the fmincon algorithms can offer better efficiency and accuracy for multi-output
     model estimations.
Option set for the search algorithm, specified as the comma-separated pair consisting of
'SearchOptions' and a search option set with fields that depend on the value of SearchMethod.
                                                                                                 1-869
1   Functions
1-870
                                                                                             oeOptions
                                                                                               1-871
1   Functions
1-872
                                                                         oeOptions
                            • 'sqp' — Sequential
                              quadratic programming
                              algorithm. The algorithm
                              satisfies bounds at all
                              iterations, and it can recover
                              from NaN or Inf results. It is
                              not a large-scale algorithm.
                              For more information, see
                              “Large-Scale vs. Medium-
                              Scale Algorithms”
                              (Optimization Toolbox).
                            • 'trust-region-
                              reflective' — Subspace
                              trust-region method based
                              on the interior-reflective
                              Newton method. It is a large-
                              scale algorithm.
                            • 'interior-point' —
                              Large-scale algorithm that
                              requires Optimization
                              Toolbox software. The
                              algorithm satisfies bounds at
                              all iterations, and it can
                              recover from NaN or Inf
                              results.
                            • 'active-set' — Requires
                              Optimization Toolbox
                              software. The algorithm can
                              take large steps, which adds
                              speed. It is not a large-scale
                              algorithm.
                                                                           1-873
1   Functions
• ErrorThreshold — Specifies when to adjust the weight of large errors from quadratic to linear.
                Errors larger than ErrorThreshold times the estimated standard deviation have a linear weight
                in the loss function. The standard deviation is estimated robustly as the median of the absolute
                deviations from the median of the prediction errors, divided by 0.7. For more information on
                robust norm choices, see section 15.2 of [2].
                Default: 0
          • MaxSize — Specifies the maximum number of elements in a segment when input-output data is
            split into segments.
                Default: 250000
          • StabilityThreshold — Specifies thresholds for stability tests.
                • s — Specifies the location of the right-most pole to test the stability of continuous-time models.
                  A model is considered stable when its right-most pole is to the left of s.
                   Default: 0
                • z — Specifies the maximum distance of all poles from the origin to test stability of discrete-
                  time models. A model is considered stable if all poles are within the distance z from the origin.
1-874
                                                                                             oeOptions
      Default: 1+sqrt(eps)
• AutoInitThreshold — Specifies when to automatically estimate the initial condition.
      yp, z − ymeas
                    > AutoInitThreshold
      yp, e − ymeas
Default: 1.05
Output Arguments
opt — Options set for oe
oeOptions option set
Examples
Create an options set for oe using the 'backcast' algorithm to initialize the condition and set the
Display to 'on'.
opt = oeOptions('InitialCondition','backcast','Display','on');
Compatibility Considerations
Renaming of Estimation and Analysis Options
The names of some estimation and analysis options were changed in R2018a. Prior names still work.
For details, see the R2018a release note “Renaming of Estimation and Analysis Options”.
                                                                                               1-875
1   Functions
References
          [1] Wills, Adrian, B. Ninness, and S. Gibson. “On Gradient-Based Search for Multivariable System
                   Estimates”. Proceedings of the 16th IFAC World Congress, Prague, Czech Republic, July 3–8,
                   2005. Oxford, UK: Elsevier Ltd., 2005.
          [2] Ljung, L. System Identification: Theory for the User. Upper Saddle River, NJ: Prentice-Hall PTR,
                  1999.
          See Also
          idfilt | oe
          Topics
          “Loss Function and Model Quality Metrics”
Introduced in R2012a
1-876
                                                                                      idnlarx/operspec
idnlarx/operspec
Construct operating point specification object for idnlarx model
Syntax
spec = operspec(nlsys)
Description
spec = operspec(nlsys) creates a default operating point specification object for the idnlarx
model nlsys. This object is used with findop and specifies constraints on the model input and
output signal values. Modify the default specifications using dot notation.
Input Arguments
nlsys — Nonlinear ARX model
idnlarx object
Output Arguments
spec — Operating point specification
operating point specification object
Operating point specification, used to determine an operating point of the idnlarx model using
findop, returned as an object containing the following:
                                                                                                 1-877
1   Functions
          See Also
          idnlarx/findop
Introduced in R2008a
1-878
                                                                                       idnlhw/operspec
idnlhw/operspec
Construct operating point specification object for idnlhw model
Syntax
spec = operspec(nlsys)
Description
spec = operspec(nlsys) creates a default operating point specification object for the idnlhw
model nlsys. This object is used with findop and specifies constraints on the model input and
output signal values. Modify the default specifications using dot notation.
Input Arguments
nlsys — Nonlinear Hammerstein-Wiener model
idnlhw object
Output Arguments
spec — Operating point specification
operating point specification object
Operating point specification, used to determine an operating point of the idnlhw model using
findop, returned as an object containing the following:
                                                                                                 1-879
1   Functions
Note
          1     If Input.Known is true for all model inputs, then the initial state values are determined using
                the input specifications only. In this case, findop ignores the specifications in the Output
                structure.
          2     Otherwise, findop uses the output specifications to meet the objectives indicated by
                Output.Known.
          See Also
          idnlhw/findop
Introduced in R2008a
1-880
                                                                                                  order
order
Query model order
Syntax
NS = order(sys)
Description
NS = order(sys) returns the model order NS. The order of a dynamic system model is the number
of poles (for proper transfer functions) or the number of states (for state-space models). For improper
transfer functions, the order is defined as the minimum number of states needed to build an
equivalent state-space model (ignoring pole/zero cancellations).
order(sys) is an overloaded method that accepts SS, TF, and ZPK models. For LTI arrays, NS is an
array of the same size listing the orders of each model in sys.
Caveat
order does not attempt to find minimal realizations of MIMO systems. For example, consider this 2-
by-2 MIMO system:
s=tf('s');
h = [1, 1/(s*(s+1)); 1/(s+2), 1/(s*(s+1)*(s+2))];
order(h)
ans =
order(ss(h,'min'))
See Also
balred | pole
Introduced in R2012a
                                                                                                 1-881
1   Functions
          particleFilter
          Particle filter object for online state estimation
          Description
          A particle filter is a recursive, Bayesian state estimator that uses discrete particles to approximate
          the posterior distribution of an estimated state. It is useful for online state estimation when
          measurements and a system model, that relates model states to the measurements, are available. The
          particle filter algorithm computes the state estimates recursively and involves initialization,
          prediction, and correction steps.
          particleFilter creates an object for online state estimation of a discrete-time nonlinear system
          using the discrete-time particle filter algorithm.
          Consider a plant with states x, input u, output m, process noise w, and measurement y. Assume that
          you can represent the plant as a nonlinear system.
          The algorithm computes the state estimates x of the nonlinear system using the state transition and
          measurement likelihood functions you specify.
          The software supports arbitrary nonlinear state transition and measurement models, with arbitrary
          process and measurement noise distributions.
          To perform online state estimation, create the nonlinear state transition function and measurement
          likelihood function. Then construct the particleFilter object using these nonlinear functions.
          After you create the object:
          The prediction step uses the latest state to predict the next state based on the state transition model
          you provide. The correction step uses the current sensor measurement to correct the state estimate.
          The algorithm optionally redistributes, or resamples, the particles in the state space to match the
          posterior distribution of the estimated state. Each particle represents a discrete state hypothesis of
          these state variables. The set of all particles is used to help determine the state estimate.
1-882
                                                                                              particleFilter
Creation
Syntax
pf = particleFilter(StateTransitionFcn,MeasurementLikelihoodFcn)
Object Description
After creating the object, use the initialize command to initialize the particles with a known mean
and covariance or uniformly distributed particles within defined bounds. Then, use the correct and
predict commands to update particles (and hence the state estimate) using sensor measurements.
Input Arguments
State transition function, specified as a function handle, determines the transition of particles (state
hypotheses) between time steps. Also a property of the particleFilter object. For more
information, see “Properties” on page 1-883.
Measurement likelihood function, specified as a function handle, is used to calculate the likelihood of
particles (state hypotheses) from sensor measurements. Also a property of the particleFilter
object. For more information, see “Properties” on page 1-883.
Properties
NumStateVariables — Number of state variables
[ ] (default) | scalar
Number of state variables, specified as a scalar. This property is read-only and is set using
initialize. The number of states is implicit based on the specified matrices for the initial mean of
particles, or the state bounds.
Number of particles used in the filter, specified as a scalar. Each particle represents a state
hypothesis. You specify this property only by using initialize.
                                                                                                    1-883
1   Functions
          State transition function, specified as a function handle, determines the transition of particles (state
          hypotheses) between time steps. This function calculates the particles at the next time step, including
          the process noise, given particles at a time step.
          You write and save the state transition function for your nonlinear system, and specify it as a function
          handle when constructing the particleFilter object. For example, if
          vdpParticleFilterStateFcn.m is the state transition function, specify StateTransitionFcn as
          @vdpParticleFilterStateFcn. You can also specify StateTransitionFcn as a function handle
          to an anonymous function.
          The StateTransitionFcn function accepts at least one input argument. The first argument is the
          set of particles previousParticles that represents the state hypotheses at the previous time step.
          The optional use of varargin in the function enables you to input any extra parameters that are
          relevant for predicting the next state, using predict, as follows:
          predict(pf,arg1,arg2)
          StateTransitionFcn must return exactly one output, predictedParticles, which is the set of
          predicted particle locations for the current time step (array with same dimensions as
          previousParticles).
          StateTransitionFcn must include the random process noise (from any distribution suitable for
          your application) in the predictedParticles.
          To see an example of a state transition function with the StateOrientation property set to
          'column', type edit vdpParticleFilterStateFcn at the command line.
          Measurement likelihood function, specified as a function handle, is used to calculate the likelihood of
          particles (state hypotheses) using the sensor measurements. For each state hypothesis (particle), the
          function first calculates an N-element measurement hypothesis vector. Then the likelihood of each
          measurement hypothesis is calculated based on the sensor measurement and the measurement noise
          probability distribution.
          You write and save the measurement likelihood function based on your measurement model, and use
          it to construct the object. For example, if vdpMeasurementLikelihoodFcn.m is the measurement
          likelihood function, specify MeasurementLikelihoodFcn as @vdpMeasurementLikelihoodFcn.
          You can also specify MeasurementLikelihoodFcn as a function handle to an anonymous function.
1-884
                                                                                               particleFilter
The MeasurementLikelihoodFcn function accepts at least two input arguments. The first
argument is the set of particles predictedParticles that represents the predicted state
hypothesis. If StateOrientation is 'column', then predictedParticles is a
NumStateVariables-by-NumParticles array. If StateOrientation is 'row', then
predictedParticles is a NumParticles-by-NumStateVariables array. The second argument,
measurement, is the N-element sensor measurement at the current time step. You can provide
additional input arguments using varargin.
The MeasurementLikelihoodFcn must return exactly one output, likelihood, a vector with
NumParticles length, which is the likelihood of the given measurement for each particle (state
hypothesis).
Whether the state variables have a circular distribution, specified as a logical array.
Circular (or angular) distributions use a probability density function with a range of [-pi,pi].
IsStateVariableCircular is a row-vector with NumStateVariables elements. Each vector
element indicates whether the associated state variable is circular.
The resampling of particles is a vital step in estimating states using a particle filter. It enables you to
select particles based on the current state, instead of using the particle distribution given at
initialization. By continuously resampling the particles around the current estimate, you can get more
accurate tracking and improve long-term performance.
You can trigger resampling either at fixed intervals or dynamically, based on the number of effective
particles. The minimum effective particle ratio is a measure of how well the current set of particles
approximates the posterior distribution. The number of effective particles is calculated by:
In this equation, N is the number of particles, and w is the normalized weight of each particle. The
effective particle ratio is then Neff / NumParticles. Therefore, the effective particle ratio is a
function of the weights of all the particles. After the weights of the particles reach a low enough
value, they are not contributing to the state estimation. This low value triggers resampling, so the
particles are closer to the current state estimation and have higher weights.
                                                                                                     1-885
1   Functions
           Description
           V
           TP
           a
           yr
           lo
           p
           u
           ep
           e
            r
            t
            y
           It
           '
           c    T is a method to determine when resampling occurs, based on the value chosen. The 'interval'
           r
           h
           valuer      triggers resampling at regular time steps of the particle filter operation. The 'ratio' value
           a    triggers
                i         resampling based on the ratio of effective total particles.
           rt   g
            i
            a   g
            o
            c   e
            t'  r
             (M
             e
             rd e
              e
              v t
              fh
              e
              a
              c o
              tud
               l
               o
               rt
                )
           '
           i
           n
           t
           e
           r
           v
           a
           l
           '
1-886
                                                                                                  particleFilter
Description
V
TP
a
yr
lo
p
u
ep
e
 r
 t
 y
s1
 Fixed
    S  interval between resampling, specified as a scalar. This interval determines during which
correction
 (a
 c          steps the resampling is executed. For example, a value of 2 means the resampling is
executed
 d
 a  m      every second correction step. A value of inf means that resampling is never executed.
 le p
This
  fl
  a   property only applies with the TriggerMethod is set to 'interval'.
  rai
   un
   lg
   tI
   )n
    t
    e
    r
    v
    a
    l
It
s0  M is the minimum desired ratio of the effective number of particles to the total number of particles
 .i
 c
 NumParticles.         The effective number of particles is a measure of how well the current set of
 5
 a
 particles
    n          approximates the posterior distribution. A lower effective particle ratio implies that a lower
 l(number
    E         of particles are contributing to the estimation and resampling is required.
  d
  a ff
  reIf the ratio of the effective number of particles to the total number of particles NumParticles falls
   fbelow
    c       the MinEffectiveParticleRatio, a resampling step is triggered.
   at
   ui
   lv
   te
   )P
a
    r
    t
    i
    c
    l
    e
    R
    a
    t
    i
    o
                                                                                                        1-887
1   Functions
          • 'multinomial'
          • 'residual'
          • 'stratified'
          • 'systematic'
Method used for extracting a state estimate from particles, specified as one of the following:
          • 'mean' - The object outputs the weighted mean of the particles, depending on the properties
            Weights and Particles, as the state estimate.
          • 'maxweight' - The object outputs the particle with the highest weight as the state estimate.
Particle weights, defined as a vector based on the value of the StateOrientation property:
Current state estimate, defined as a vector based on the value of the StateOrientation property:
1-888
                                                                                              particleFilter
Object Functions
initialize          Initialize the state of the particle filter
predict             Predict state and state estimation error covariance at next time step using
                    extended or unscented Kalman filter, or particle filter
correct             Correct state and state estimation error covariance using extended or unscented
                    Kalman filter, or particle filter and measurements
getStateEstimate    Extract best state estimate and covariance from particles
clone               Copy online state estimation object
Examples
To create a particle filter object for estimating the states of your system, create appropriate state
transition function and measurement likelihood function for the system.
Create the particle filter object. Use function handles to provide the state transition and
measurement likelihood functions to the object.
myPF = particleFilter(@vdpParticleFilterStateFcn,@vdpMeasurementLikelihoodFcn);
To initialize and estimate the states and state estimation error covariance from the constructed
object, use the initialize, predict, and correct commands.
Load the van der Pol ODE data, and specify the sample time.
vdpODEdata.mat contains a simulation of the van der Pol ODE with nonlinearity parameter mu=1,
using ode45, with initial conditions [2;0]. The true state was extracted with sample time dt =
0.05.
load ('vdpODEdata.mat','xTrue','dt')
tSpan = 0:dt:5;
                                                                                                    1-889
1   Functions
          Get the measurements. For this example, a sensor measures the first state with a Gaussian noise with
          standard deviation 0.04.
          sqrtR = 0.04;
          yMeas = xTrue(:,1) + sqrtR*randn(numel(tSpan),1);
Create a particle filter, and set the state transition and measurement likelihood functions.
myPF = particleFilter(@vdpParticleFilterStateFcn,@vdpMeasurementLikelihoodFcn);
Initialize the particle filter at state [2; 0] with unit covariance, and use 1000 particles.
initialize(myPF,1000,[2;0],eye(2));
          myPF.StateEstimationMethod = 'mean';
          myPF.ResamplingMethod = 'systematic';
Estimate the states using the correct and predict commands, and store the estimated states.
          xEst = zeros(size(xTrue));
          for k=1:size(xTrue,1)
              xEst(k,:) = correct(myPF,yMeas(k));
              predict(myPF);
          end
Plot the results, and compare the estimated and true states.
          figure(1)
          plot(xTrue(:,1),xTrue(:,2),'x',xEst(:,1),xEst(:,2),'ro')
          legend('True','Estimated')
1-890
                                                                                   particleFilter
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
For more information, see “Generate Code for Online State Estimation in MATLAB”.
See Also
Functions
clone | correct | extendedKalmanFilter | initialize | predict | unscentedKalmanFilter
Topics
“Nonlinear State Estimation Using Unscented Kalman Filter and Particle Filter”
“Generate Code for Online State Estimation in MATLAB”
“What Is Online Estimation?”
“Validate Online State Estimation at the Command Line”
“Troubleshoot Online State Estimation”
                                                                                         1-891
1   Functions
Introduced in R2017b
1-892
                                                                                                        pe
pe
Prediction error for identified model
Syntax
err = pe(sys,data,K)
err = pe(sys,data,K,opt)
[err,x0e,sys_pred] = pe( ___ )
pe(sys,data,K, ___ )
pe(sys,Linespec,data,K, ___ )
pe(sys1,...,sysN,data,K, ___ )
pe(sys1,Linespec1,...,sysN,LinespecN,data,K, ___ )
Description
err = pe(sys,data,K) returns the K-step prediction error for the output of the identified model
sys. The prediction error is determined by subtracting the K-step ahead predicted response from the
measured output. The prediction error is calculated for the time span covered by data. For more
information on the computation of predicted response, see predict.
err = pe(sys,data,K,opt) returns the prediction error using the option set, opt, to specify
prediction error calculation behavior.
[err,x0e,sys_pred] = pe( ___ ) also returns the estimated initial state, x0e, and a predictor
system, sys_pred.
pe(sys,data,K, ___ ) plots the prediction error. Use with any of the previous input argument
combinations. To change display options in the plot, right-click the plot to access the context menu.
For more details about the menu, see “Tips” on page 1-896.
pe(sys,Linespec,data,K, ___ ) uses Linespec to specify the line type, marker symbol, and
color.
pe(sys1,...,sysN,data,K, ___ ) plots the prediction errors for multiple identified models. pe
automatically chooses colors and line styles.
Input Arguments
sys
Identified model.
data
                                                                                                 1-893
1   Functions
          If sys is a time-series model, which has no input signals, then specify data as an iddata object with
          no inputs. In this case, you can also specify data as a matrix of the past time-series values.
Prediction horizon.
          Specify K as a positive integer that is a multiple of the data sample time. Use K = Inf to compute
          the pure simulation error.
Default: 1
opt
Prediction options.
          opt is an option set, created using peOptions, that configures the computation of the predicted
          response. Options that you can specify include:
Linespec
Line style, marker, and color, specified as a character vector. For example, 'b' or 'b+:'.
          Output Arguments
          err
Prediction error.
          err is returned as an iddata object or matrix, depending on how you specify data. For example, if
          data is an iddata object, then so is err.
          Outputs up to the time t-K and inputs up to the time instant t are used to calculate the prediction
          error at the time instant t.
          For multi-experiment data, err contains the prediction error data for each experiment. The time span
          of the prediction error matches that of the observed data.
x0e
sys_pred
Predictor system.
1-894
                                                                                                 pe
For multi-experiment data, sys_pred is an array of models, with one entry for each experiment.
Examples
Use the error data to compute the variance of the noise source e(t).
noise = [(1:150)';(151:-1:2)'];
noise is a triangular wave that is added to the output signal of z1, an iddata object.
K = 1;
err = pe(z1,sys,K);
pe computes the one-step prediction error for the output of the identified model, sys.
noise_var = err.y'*err.y/(299-nparams(sys)-order(sys));
sys.NoiseVariance
load iddata1;
data = z1;
                                                                                             1-895
1   Functions
          Plot the prediction error for the estimated models. Specify prediction horizon as 10, and specify the
          line styles for plotting the prediction error of each system.
          pe(sys1,'r--',sys2,'b',data,10);
          To change the display options, right-click the plot to access the context menu. For example, to view
          the estimation data, select Show Validation Data from the context menu. To view the predicted
          outputs, select Predicted Response Plot.
          Tips
          • Right-clicking the plot of the prediction error opens the context menu, where you can access the
            following options:
                • Systems — Select systems to view prediction error. By default, the prediction error of all
                  systems is plotted.
                • Data Experiment — For multi-experiment data only. Toggle between data from different
                  experiments.
1-896
                                                                                                    pe
      • Peak Value — View the absolute peak value of the data. Applicable for time–domain data
        only.
      • Peak Response — View peak response of the data. Applicable for frequency–response data
        only.
      • Mean Value — View mean value of the data. Applicable for time–domain data only.
   • Show — For frequency–domain and frequency–response data only.
See Also
ar | arx | compare | iddata | n4sid | peOptions | predict | resid | sim
                                                                                                 1-897
1   Functions
          peOptions
          Option set for pe
          Syntax
          opt = peOptions
          opt = peOptions(Name,Value)
          Description
          opt = peOptions creates the default options set for pe.
          opt = peOptions(Name,Value) creates an option set with the options specified by one or more
          Name,Value pair arguments.
          Input Arguments
          Name-Value Pair Arguments
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
InitialCondition
                For nonlinear grey-box models, only those initial states i that are designated as free in the model
                (sys.InitialStates(i).Fixed = false) are estimated. To estimate all the states of the
                model, first specify all the Nx states of the idnlgrey model sys as free.
                for i = 1:Nx
                sys.InitialStates(i).Fixed = false;
                end
                Similarly, to fix all the initial states to values specified in sys.InitialStates, first specify all
                the states as fixed in the sys.InitialStates property of the nonlinear grey-box model.
          • 'd' — Similar to 'e', but absorbs nonzero delays into the model coefficients. The delays are first
            converted to explicit model states, and the initial values of those states are also estimated and
            returned.
1-898
                                                                                             peOptions
   Ne is the number of experiments. Otherwise, use a column vector to specify the same initial
   conditions for all experiments. Use this option for state-space (idss and idgrey) and nonlinear
   models (idnlarx, idnlhw, and idnlgrey) only.
• Structure with the following fields, which contain the historical input and output values for a time
  interval immediately before the start time of the data used by pe:
       Field      Description
       Input      Input history, specified as a matrix with Nu columns, where Nu is the number of
                  input channels. For time series models, use []. The number of rows must be
                  greater than or equal to the model order.
       Output     Output history, specified as a matrix with Ny columns, where Ny is the number of
                  output channels. The number of rows must be greater than or equal to the model
                  order.
   For multi-experiment data, configure the initial conditions separately for each experiment by
   specifying InitialCondition as a structure array with Ne elements. To specify the same initial
   conditions for all experiments, use a single structure.
   The software uses data2state to map the historical data to states. If your model is not idss,
   idgrey, idnlgrey, or idnlarx, the software first converts the model to its state-space
   representation and then maps the data to states. If conversion of your model to idss is not
   possible, the estimated states are returned empty.
• x0obj — Specification object created using idpar. Use this object for discrete-time state-space
  (idss and idgrey) and nonlinear grey-box (idnlgrey) models only. Use x0obj to impose
  constraints on the initial states by fixing their value or specifying minimum or maximum bounds.
Default: 'e'
InputOffset
Removes offset from time domain input data during prediction-error calculation.
For multi-experiment data, specify InputOffset as an Nu-by-Ne matrix. Nu is the number of inputs,
and Ne is the number of experiments.
Each entry specified by InputOffset is subtracted from the corresponding input data.
Default: []
OutputOffset
Removes offset from time domain output data during prediction-error calculation.
Each entry specified by OutputOffset is subtracted from the corresponding output data.
                                                                                                1-899
1   Functions
Default: []
OutputWeight
          • [] — No weighting is used. This value is the same as using eye(Ny) for the output weight, where
            Ny is the number of outputs.
          • 'noise' — Inverse of the noise variance stored with the model.
          • matrix — A positive, semidefinite matrix of dimension Ny-by-Ny, where Ny is the number of
            outputs.
Default: []
          Output Arguments
          opt
Examples
opt = peOptions;
Create an options set for pe using zero initial conditions, and set the input offset to 5.
opt = peOptions('InitialCondition','z','InputOffset',5);
          opt = peOptions;
          opt.InitialCondition = 'z';
          opt.InputOffset = 5;
          See Also
          idpar | pe
Introduced in R2012a
1-900
                                                                                                pem
pem
Prediction error estimate for linear and nonlinear model
Syntax
sys = pem(data,init_sys)
sys = pem(data,init_sys,opt)
Description
sys = pem(data,init_sys) updates the parameters of an initial model to fit the estimation data.
The function uses prediction-error minimization algorithm to update the parameters of the initial
model. Use this command to refine the parameters of a previously estimated model.
Examples
Estimate a discrete-time state-space model using the subspace method. Then, refine it by minimizing
the prediction error.
Estimate a discrete-time state-space model using n4sid, which applies the subspace method.
init_sys.Report.Fit.FitPercent
ans = 73.8490
sys = pem(z7a,init_sys);
compare(z7a,sys,init_sys);
                                                                                              1-901
1   Functions
          Load the experimental data, and specify the signal attributes such as start time and units.
          load(fullfile(matlabroot,'toolbox','ident','iddemos','data','dcmotordata'));
          data = iddata(y, u, 0.1);
          data.Tstart = 0;
          data.TimeUnit = 's';
          For this example, use dcmotor_m.m file. To view this file, type edit dcmotor_m.m at the MATLAB®
          command prompt.
          file_name = 'dcmotor_m';
          order = [2 1 2];
          parameters = [1;0.28];
          initial_states = [0;0];
          Ts = 0;
          init_sys = idnlgrey(file_name,order,parameters,initial_states,Ts);
          init_sys.TimeUnit = 's';
1-902
                                                                                                  pem
setinit(init_sys,'Fixed',{false false});
init_sys is a nonlinear grey-box model with its structure described by dcmotor_m.m. The model
has one input, two outputs and two states, as specified by order.
sys = pem(data,init_sys);
sys is an idnlgrey model, which encapsulates the estimated parameters and their covariance.
compare(data,sys,init_sys);
Create a process model structure and update its parameter values to minimize prediction error.
                                                                                                 1-903
1   Functions
          init_sys = idproc('P2UDZ');
          init_sys.Kp = 10;
          init_sys.Tw = 0.4;
          init_sys.Zeta = 0.5;
          init_sys.Td = 0.1;
          init_sys.Tz = 0.01;
The Kp, Tw, Zeta, Td, and Tz coefficients of init_sys are configured with their initial guesses.
          Use init_sys to configure the estimation of a prediction error minimizing model using measured
          data. Because init_sys is an idproc model, use procestOptions to create the option set.
sys.Report.Fit.FitPercent
ans = 70.6330
          Input Arguments
          data — Estimation data
          iddata | idfrd
          Estimation data that contains measured input-output data, specified as an iddata or idfrd object.
          You can use frequency-domain data only when init_sys is a linear model.
          Identified model that configures the initial parameterization of sys, specified as a linear, or nonlinear
          model. You can obtain init_sys by performing an estimation using measured data or by direct
          construction.
          init_sys must have finite parameter values. You can configure initial guesses, specify minimum/
          maximum bounds, and fix or free for estimating any parameter of init_sys:
          • For linear models, use the Structure property. For more information, see “Imposing Constraints
            on Model Parameter Values”.
          • For nonlinear grey-box models, use the InitialStates and Parameters properties. Parameter
            constraints cannot be specified for nonlinear ARX and Hammerstein-Wiener models.
1-904
                                                                                                    pem
Estimation options that configure the algorithm settings, handling of estimation focus, initial
conditions, and data offsets, specified as an option set. The command used to create the option set
depends on the initial model type:
Output Arguments
sys — Identified model
linear model | nonlinear model
Identified model, returned as the same model type as init_sys. The model is obtained by estimating
the free parameters of init_sys using the prediction error minimization algorithm.
Algorithms
PEM uses numerical optimization to minimize the cost function, a weighted norm of the prediction
error, defined as follows for scalar outputs:
                  N
    V N G, H =   ∑     e2 t
                 t=1
where e(t) is the difference between the measured output and the predicted output of the model. For
a linear model, the error is defined as:
where e(t) is a vector and the cost function V N G, H is a scalar value. The subscript N indicates that
the cost function is a function of the number of data samples and becomes more accurate for larger
values of N. For multiple-output models, the previous equation is more complex. For more
information, see chapter 7 in System Identification: Theory for the User, Second Edition, by Lennart
Ljung, Prentice Hall PTR, 1999.
Alternative Functionality
You can achieve the same results as pem by using dedicated estimation commands for the various
model structures. For example, use ssest(data,init_sys) for estimating state-space models.
                                                                                                  1-905
1   Functions
          See Also
          armax | bj | greyest | n4sid | nlarx | nlgreyest | nlhw | oe | polyest | procest | ssest |
          tfest
          Topics
          “Refine Linear Parametric Models”
1-906
                                                                                                     pexcit
pexcit
Level of excitation of input signals
Syntax
Ped = pexcit(Data)
[Ped.Maxnr] = pexcit(Data,Maxnr,Threshold)
Description
Ped = pexcit(Data) tests the degree of persistence of excitation for the input. Data is an iddata
object with time- or frequency-domain signals. Ped is the degree or order of excitation of the inputs
in Data and is a row vector of integers with as many components as there are inputs in Data. The
intuitive interpretation of the degree of excitation in an input is the order of a model that the input is
capable of estimating in an unambiguous way.
References
Section 13.2 in Ljung (1999).
See Also
advice | feedback | iddata | idnlarx
                                                                                                    1-907
1   Functions
          iddata/plot
          Plot input-output data
          Syntax
          plot(data)
          plot(data,LineSpec)
          plot(data1,...,dataN)
          plot(data1,LineSpec1...,dataN,LineSpecN)
plot(axes_handle, ___ )
h = plot( ___ )
          Description
          plot(data) plots the input and output channels of an iddata object. The outputs are plotted on the
          top axes and the inputs on the bottom axes.
          • For time-domain data, the input and output signals are plotted as a function of time. Depending on
            the InterSample property of the iddata object, the input signals are plotted as linearly
            interpolated curves or as staircase plots. For example, if data.InterSample = 'zoh', the input
            is piecewise constant between sampling points, and it is then plotted accordingly.
          • For frequency-domain data, the magnitude and phase of each input and output signal is plotted
            over the available frequency span.
plot(data,LineSpec) specifies the color, line style and marker symbol for the dataset.
          plot(data1,...,dataN) plots multiple datasets. The number of plot axes are determined by the
          number of unique input and output names among all the datasets.
          plot(axes_handle, ___ ) plots into the axes with handle axes_handle instead of into the current
          axes (gca). This syntax can include any of the input argument combinations in the previous syntaxes.
          plot( ___ ,plotoptions) specifies the plot options. This syntax can include any of the input
          argument combinations in the previous syntaxes.
1-908
                                                                                             iddata/plot
h = plot( ___ ) returns the handle to the plot. You can use this handle to customize the plot with
getoptions and setoptions.
Input Arguments
data — Input-output data
iddata object
Input-output data, specified as an iddata object. The data can be time-domain or frequency-domain.
It can be a single- or multi-channel data, or single- or multi-experiment data.
Line style, marker symbol, and color, specified as a character vector. LineSpec takes values such as
'b', 'b+:'. For more information, see the plot reference page in the MATLAB documentation.
Data Types: char
Axes handle, which is the reference to an axes object. Use the gca function to get the handle to the
current axes, for example, axes_handle= gca.
Output Arguments
h — Lineseries handle
scalar | vector
Lineseries handle, returned as a scalar or vector. These are unique identifiers, which you can use to
query and modify properties of a specific plot.
Examples
plot(z1)
                                                                                                 1-909
1   Functions
The output is plotted on the top axes and the input on the bottom axes.
You can right-click the plot to explore its characteristics such as peak and mean values.
load iddata1 z1
zf = fft(z1);
plot(zf);
1-910
                                                     iddata/plot
plot(u)
                                                        1-911
1   Functions
plot(y)
1-912
                                      iddata/plot
plot(y,u)
                                         1-913
1   Functions
          load iddata1 z1
          load iddata2 z2
          zm = merge(z1,z2);
plot(zm);
1-914
                                                                                             iddata/plot
For multi-experiment data, each experiment is treated as a separate data set. You can right-click the
plots to view their characteristics.
plot(z1,'y:*',z2,'b')
                                                                                                1-915
1   Functions
Create a figure with two subplots and return the handle to each subplot axes, s(1) and s(2).
1-916
                                                                 iddata/plot
load iddata1;
load iddata2;
plot(s(1),z1)
plot(s(2),z2)
                                                                    1-917
1   Functions
opt = iddataPlotOptions('time');
opt.TimeUnits = 'minutes';
opt.Grid = 'on';
          load iddata1 z1
          plot(z1, opt);
1-918
                                            iddata/plot
load iddata1;
h = plot(z1);
                                               1-919
1   Functions
setoptions(h,'TimeUnits','minutes');
1-920
                                                iddata/plot
z = iddata(randn(100,1),rand(100,2));
opt = iddataPlotOptions('time');
h = plot(z,opt);
                                                   1-921
1   Functions
          Change the orientation of the plots such that all inputs are plotted in one column, and all outputs are
          in a second column.
          opt.Orientation = 'two-column';
          h = plot(z,opt);
1-922
                                                                                          iddata/plot
setoptions(h,'Orientation','two-column')
You can also change the orientation by right-clicking the plot and choosing Orientation in the
context menu.
Tips
• Right-clicking the plot opens the context menu where you can access the following options and
  plot controls:
       • Peak Value — Peak value of the data. Useful for transient data.
       • Mean Value — Mean value of the data. Useful for steady-state data.
   • Orientation — Choose orientation of the input and output plots.
       • Output row and input row — (For datasets containing more than one input or output
         channel) Plot all outputs in one row and all inputs in a second row.
       • Output column and input column — (For datasets containing more than one input or
         output channel) Plot all outputs in one column and all inputs in a second column.
                                                                                             1-923
1   Functions
          See Also
          iddata | iddataPlotOptions | identpref
Introduced in R2014a
1-924
                                                                                          idnlarx/plot
idnlarx/plot
Plot nonlinearity of nonlinear ARX model
Syntax
plot(model)
plot(model,color)
plot(model1,...,modelN)
plot(model1,color1...,modelN,colorN)
plot( ___ ,'NumberofSamples',N)
Description
plot(model) plots the nonlinearity of a nonlinear ARX model on a nonlinear ARX plot on page 1-
929. The plot shows the nonlinearity for all outputs of the model as a function of its input
regressors.
plot(model1,color1...,modelN,colorN) specifies the color for each model. You do not need to
specify the color for all models.
plot( ___ ,'NumberofSamples',N) specifies the number of samples to use to grid the regressor
space on each axis. This syntax can include any of the input argument combinations in the previous
syntaxes.
Examples
load iddata1
model1 = nlarx(z1,[4 2 1],'wave','nlr',[1:3]);
plot(model1)
                                                                                              1-925
1   Functions
          • The regressors to use on the plot axes, and specify the center points for the other regressors in
            the configuration panel. For multi-output models, each output is plotted separately.
          • The output to view from the drop-down list located at the top of the plot.
          load iddata1
          model1 = nlarx(z1,[4 2 1],'wave','nlr',[1:3]);
          model2 = nlarx(z1,[4 2 1],'sigmoidnet','nlr',[1:3]);
          plot(model1,'b', model2, 'g')
1-926
                                                       idnlarx/plot
load iddata1
model1 = nlarx(z1,[4 2 1],'wave','nlr',[1:3]);
model2 = nlarx(z1,[4 2 1],'sigmoidnet','nlr',[1:3]);
plot(model1,'b', model2, 'g','NumberofSamples',50)
                                                           1-927
1   Functions
          Input Arguments
          model — Estimated nonlinear ARX model
          idnlarx model
          Estimated nonlinear ARX model, specified as an idnlarx model object. Use nlarx to estimate the
          model.
                • 'b'
                • 'y'
1-928
                                                                                            idnlarx/plot
   • 'm'
   • 'c'
   • 'r'
   • 'g'
   • 'w'
• 3-element double vector of RGB values
N — Number of points
20 (default) | positive integer
Number of points used on the regressor axis to display the regressor samples, specified as a positive
integer.
Data Types: double
More About
What is a Nonlinear ARX Plot?
A nonlinear ARX plot displays the evaluated model nonlinearity for a chosen model output as a
function of one or two model regressors. For a model M, the model nonlinearity (M.Nonlinearity) is
a nonlinearity estimator function, such as wavenet, sigmoidnet, or treepartition, that uses
model regressors as its inputs.
To understand what is plotted, suppose that {r1,r2,…,rN} are the N regressors used by a nonlinear
ARX model M with nonlinearity nl corresponding to a model output. You can use getreg(M) to view
these regressors. The expression Nonlin = evaluate(nl,[v1,v2,...,vN]) returns the model
                                                                                                1-929
1   Functions
          output for given values of these regressors, that is, r1 = v1, r2 = v2, ..., rN = vN. For plotting the
          nonlinearities, you select one or two of the N regressors, for example, rsub = {r1,r4}. The
          software varies the values of these regressors in a specified range, while fixing the value of the
          remaining regressors, and generates the plot of Nonlin vs. rsub. By default, the software sets the
          values of the remaining fixed regressors to their estimated means, but you can change these values.
          The regressor means are stored in the Nonlinearity.Parameters.RegressorMean property of
          the model.
          Examining a nonlinear ARX plot can help you gain insight into which regressors have the strongest
          effect on the model output. Understanding the relative importance of the regressors on the output
          can help you decide which regressors to include in the nonlinear function for that output. If the shape
          of the plot looks like a plane for all the chosen regressor values, then the model is probably linear in
          those regressors. In this case, you can remove the corresponding regressors from nonlinear block,
          and repeat the estimation.
          Furthermore, you can create several nonlinear models for the same data using different nonlinearity
          estimators, such a wavenet network and treepartition, and then compare the nonlinear surfaces
          of these models. Agreement between plots for various models increases the confidence that these
          nonlinear models capture the true dynamics of the system.
To learn more about configuring the plot, see “Configuring a Nonlinear ARX Plot”.
          See Also
          evaluate | getreg | idnlarx | nlarx
          Topics
          “Structure of Nonlinear ARX Models”
          “Validate Nonlinear ARX Models”
Introduced in R2014a
1-930
                                                                                         idnlhw/plot
idnlhw/plot
Plot input and output nonlinearity, and linear responses of Hammerstein-Wiener model
Syntax
plot(model)
plot(model,LineSpec)
plot(model1,...,modelN)
plot(model1,LineSpec1...,modelN,LineSpecN)
Description
plot(model) plots the input and output nonlinearity, and linear responses of a Hammerstein-Wiener
model on a Hammerstein-Wiener plot on page 1-937. The plot shows the responses of the input and
output nonlinearity, and linear blocks that represent the model.
plot( ___ ,Name,Value) specifies plot properties using additional options specified by one or more
Name,Value pair arguments. This syntax can include any of the input argument combinations in the
previous syntaxes.
Examples
Plot Input and Output Nonlinearity and Linear Response of a Hammerstein-Wiener Model
Estimate a Hammerstein-Wiener Model and plot responses of its input and output nonlinearity and
linear blocks.
load iddata3
model1 = nlhw(z3,[4 2 1],'sigmoidnet','deadzone');
plot(model1)
                                                                                            1-931
1   Functions
          Explore the various plots in the plot window by clicking one of the three blocks that represent the
          model:
1-932
                                                                           idnlhw/plot
load iddata3
model1 = nlhw(z3,[4 2 1],'sigmoidnet','deadzone');
model2 = nlhw(z3, [4 2 1],[],'sigmoidnet');
plot(model1,'b-',model2,'g')
load iddata3
model1 = nlhw(z3,[4 2 1],'sigmoidnet','deadzone');
                                                                              1-933
1   Functions
          load iddata3
          model1 = nlhw(z3,[4 2 1],'sigmoidnet','deadzone');
          model2 = nlhw(z3, [4 2 1],[],'sigmoidnet');
          plot(model1,model2,'time',1:500,'freq',{0.01,100},'OutputRange',[0 1000]);
1-934
                                                                                      idnlhw/plot
Input Arguments
model — Estimated Hammerstein-Wiener model
idnlhw model
Estimated Hammerstein-Wiener model, specified as an idnlhw model object. Use nlhw to estimate
the model.
                                                                                         1-935
1   Functions
          Line style, marker symbol, and color, specified as a character vector. LineSpec takes values such as
          'b', 'b+:'. For more information, see the plot reference page in the MATLAB documentation.
          Data Types: char
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
          Example: plot(model,'NumberofSamples',10) specifies to use 10 data points for the input
          regressors.
          Number of data points to use for the input regressors when evaluating the nonlinearities at individual
          input or output channels, specified as a positive integer. This property does not affect the plots of the
          linear block.
          Data Types: double
          InputRange — Minimum and maximum regressor values for evaluating input nonlinearities
          range of regressor values used during each model's estimation. (default) | positive integer | vector
          Minimum and maximum regressor values to use when evaluating the nonlinearities at each input
          channel, specified as positive integers or [min max] vector, where minimum value is less than the
          maximum value.
          Minimum and maximum regressor values to use when evaluating the nonlinearities at each output
          channel, specified as positive integers or [min max] vector, where minimum value is less than the
          maximum value.
          The time samples at which the transient responses (step and impulse) of the linear block of the
          idnlhw model must be computed, specified as one of the following values:
          • Positive scalar — Denotes end time for transient responses of all models. For example, 10.
          • Vector of time instants — A double vector of equi-sampled values denotes the time samples at
            which the transient response must be computed. For example, [0:0.1:10].
This property takes the same values as the step command on the model.
1-936
                                                                                             idnlhw/plot
Frequencies at which to compute the Bode response, specified as one of the following values:
• [Wmin Wmax] range — Frequency interval between Wmin and Wmax (in units rad/
  (model.TimeUnit)) covered using logarithmically placed points.
• Vector of non-negative frequency values — Allows computation of bode response at those
  frequencies.
By default, the response is computed at some automatically chosen frequencies inside the Nyquist
frequency range. Frequencies above Nyquist frequency (pi/model.Ts) are ignored.
This property takes the same values as the bode command on the model.
More About
What is a Hammerstein-Wiener Plot?
A Hammerstein-Wiener plot displays the static input and output nonlinearities and linear responses of
a Hammerstein-Wiener model.
Examining a Hammerstein-Wiener plot can help you determine whether you have selected a
complicated nonlinearity for modeling your system. For example, suppose you use a piecewise-linear
input nonlinearity to estimate your model, but the plot indicates saturation behavior. You can estimate
a new model using the simpler saturation nonlinearity instead. For multivariable systems, you can use
the Hammerstein-Wiener plot to determine whether to exclude nonlinearities for specific channels. If
the nonlinearity for a specific input or output channel does not exhibit strong nonlinear behavior, you
can estimate a new model after setting the nonlinearity at that channel to unit gain.
                                                                                                  1-937
1   Functions
          You can generate these plots in the System Identification app and at the command line. In the plot
          window, you can view the nonlinearities and linear responses by clicking one of the three blocks that
          represent the model:
          • uNL (input nonlinearity)— Click this block to view the static nonlinearity at the input to the Linear
            Block. The plot displays evaluate(M.InputNonlinearity,u) where M is the Hammerstein-
            Wiener model, and u is the input to the input nonlinearity block. For information about the blocks,
            see “Structure of Hammerstein-Wiener Models”.
          • Linear Block — Click this block to view the Step, impulse, Bode, and pole-zero response plots of
            the embedded linear model (M.LinearModel). By default, a step plot of the linear model is
            displayed.
          • yNL (output nonlinearity) — Click this block to view the static nonlinearity at the output of the
            Linear Block. The plot displays evaluate(M.OutputNonlinearity,x), where x is the
            output of the linear block.
          To learn more about how to configure the linear and nonlinear blocks plots, see “Configuring a
          Hammerstein-Wiener Plot”.
          See Also
          idnlhw | nlhw
          Topics
          “Structure of Hammerstein-Wiener Models”
          “Validating Hammerstein-Wiener Models”
1-938
                       idnlhw/plot
Introduced in R2014a
                          1-939
1   Functions
          pole
          Poles of dynamic system
          Syntax
          P = pole(sys)
          P = pole(sys,J1,...,JN)
          Description
          P = pole(sys) returns the poles of the SISO or MIMO dynamic system model sys. The output is
          expressed as the reciprocal of the time units specified in sys.TimeUnit. The poles of a dynamic
          system determine the stability and response of the system.
          • In continuous-time, all the poles of the transfer function have negative real parts. When the poles
            are visualized on the complex s-plane, then they must all lie in the left-half plane (LHP) to ensure
            stability.
          • In discrete-time, all the poles must have a magnitude strictly smaller than one, that is they must
            all lie inside the unit circle.
          P = pole(sys,J1,...,JN) returns the poles P of the entries in model array sys with subscripts
          (J1,...,JN).
Examples
                           0 . 0478z − 0 . 0464
                sys z =    2
                          z − 1 . 81z + 0 . 9048
P = 2×1 complex
                0.9050 + 0.2929i
                0.9050 - 0.2929i
          For stable discrete systems, all their poles must have a magnitude strictly smaller than one, that is
          they must all lie inside the unit circle. The poles in this example are a pair of complex conjugates, and
          lie inside the unit circle. Hence, the system sys is stable.
1-940
                                                                                                    pole
sys = tf([4.2,0.25,-0.004],[1,9.6,17]);
P = pole(sys)
P = 2×1
   -7.2576
   -2.3424
For stable continuous systems, all their poles must have negative real parts. sys is stable since the
poles are negative, that is, they lie in the left half of the complex plane.
For this example, load invertedPendulumArray.mat, which contains a 3-by-3 array of inverted
pendulum models. The mass of the pendulum varies as you move from model to model along a single
column of sys, and the length of the pendulum varies as you move along a single row. The mass
values used are 100g, 200g and 300g, and the pendulum lengths used are 3m, 2m and 1m
respectively.
load('invertedPendulumArray.mat','sys');
size(sys)
P = pole(sys);
P(:,:,2,1)
ans = 3×1
    2.1071
   -2.1642
   -0.1426
P(:,:,2,1) corresponds to the poles of the model with 200g pendulum weight and 3m length.
                                                                                                 1-941
1   Functions
          Input Arguments
          sys — Dynamic system
          dynamic system model | model array
          Dynamic system, specified as a SISO or MIMO dynamic system model, or an array of SISO or MIMO
          dynamic system models. Dynamic systems that you can use include continuous-time or discrete-time
          numeric LTI models such as tf, zpk, or ss models.
          If sys is a generalized state-space model genss or an uncertain state-space model uss, pole returns
          the poles of the current or nominal value of sys. If sys is an array of models, pole returns the poles
          of the model corresponding to its subscript J1,...,JN in sys. For more information on model
          arrays, see “Model Arrays” (Control System Toolbox).
          Indices of models in array whose poles you want to extract, specified as a positive integer. You can
          provide as many indices as there are array dimensions in sys. For example, if sys is a 4-by-5 array of
          dynamic system models, the following command extracts the poles for entry (2,3) in the array.
          P = pole(sys,2,3);
          Output Arguments
          P — Poles of the dynamic system
          column vector | array
          • A single model, then P is a column vector of poles of the dynamic system model sys
          • A model array, then P is an array of poles of each model in sys
          P is expressed as the reciprocal of the time units specified in sys.TimeUnit. For example, pole is
          expressed in 1/minute if sys.TimeUnit = 'minutes'.
Depending on the type of system model, poles are computed in the following way:
          • For state-space models, the poles are the eigenvalues of the A matrix, or the generalized
            eigenvalues of A – λE in the descriptor case.
          • For SISO transfer functions or zero-pole-gain models, the poles are the denominator roots. For
            more information, see roots.
          • For MIMO transfer functions (or zero-pole-gain models), the poles are returned as the union of the
            poles for each SISO entry. If some I/O pairs have a common denominator, the roots of such I/O pair
            denominator are counted only once.
          Limitations
          • Multiple poles are numerically sensitive and cannot be computed with high accuracy. A pole λ with
            multiplicity m typically results in a cluster of computed poles distributed on a circle with center λ
            and radius of order
ρ ≈ ε1/m,
1-942
                                                                                                     pole
   For more information on multiple poles, see “Sensitivity of Multiple Roots” (Control System
   Toolbox).
• If sys has internal delays, poles are obtained by first setting all internal delays to zero so that the
  system has a finite number of poles, thereby creating a zero-order Padé approximation. For some
  systems, setting delays to zero creates singular algebraic loops, which result in either improper or
  ill-defined, zero-delay approximations. For these systems, pole returns an error.
To assess the stability of models with internal delays, use step or impulse.
See Also
damp | impulse | pzmap | pzplot | step | zero
Topics
“Pole and Zero Locations” (Control System Toolbox)
“Sensitivity of Multiple Roots” (Control System Toolbox)
Introduced in R2012a
                                                                                                  1-943
1   Functions
          polydata
          Access polynomial coefficients and uncertainties of identified model
          Syntax
          [A,B,C,D,F] = polydata(sys)
          [A,B,C,D,F,dA,dB,dC,dD,dF] = polydata(sys)
          [ ___ ] = polydata(sys,J1,...,JN)
          [ ___ ] = polydata( ___ ,'cell')
          Description
          [A,B,C,D,F] = polydata(sys) returns the coefficients of the polynomials A, B, C, D, and F that
          describe the identified model sys. The polynomials describe the idpoly representation of sys as
          follows.
                               B q−1                C q−1
                 A q−1 y t =           u t − nk +           et .
                               F q−1                D q−1
                u(t) are the inputs to sys. y(t) are the outputs. e(t) is a white noise disturbance.
          • For continuous-time sys:
                             Bs            Cs
                 AsY s =        U s e−τs +    Es .
                             Fs            Ds
                U(s) are the Laplace transformed inputs to sys. Y(s) are the Laplace transformed outputs. E(s) is
                the Laplace transform of a white noise disturbance.
          If sys is an identified model that is not an idpoly model, polydata converts sys to idpoly form to
          extract the polynomial coefficients.
          [A,B,C,D,F,dA,dB,dC,dD,dF] = polydata(sys) also returns the uncertainties dA, dB, dC, dD,
          and dF of each of the corresponding polynomial coefficients of sys.
          [ ___ ] = polydata( ___ ,'cell') returns all polynomials as cell arrays of double vectors,
          regardless of the input and output dimensions of sys.
          Input Arguments
          sys
          Identified model or array of identified models. sys can be continuous-time or discrete-time. sys can
          be SISO or MIMO.
1-944
                                                                                                 polydata
J1,...,JN
Indices selecting a particular model from an N-dimensional array sys of identified models.
Output Arguments
A,B,C,D,F
• If sys is a SISO model, each of A, B, C, D, and F is a row vector. The length of each row vector is
  the order of the corresponding polynomial.
   • For discrete-time sys, the coefficients are ordered in ascending powers of q–1. For example, B
     = [1 -4 9] means that B(q–1) = 1 – 4q–1 + 9q–2.
   • For continuous-time sys, the coefficients are ordered in descending powers of s. For example,
     B = [1 -4 9] means that B(s) = s2 – 4s + 9.
• If sys is a MIMO model, each of A, B, C, D, and F is a cell array. The dimensions of the cell arrays
  are determined by the input and output dimensions of sys as follows:
Each entry in a cell array is a row vector that contains the coefficients of the corresponding
polynomial. The polynomial coefficients are ordered the same way as the SISO case.
dA,dB,dC,dD,dF
dA, dB, dC, dD, and dF are row vectors or cell arrays whose dimensions exactly match the
corresponding A, B, C, D, and F outputs.
Each entry in dA, dB, dC, dD, and dF gives the standard deviation of the corresponding estimated
coefficient. For example, dA{1,1}(2) gives the standard deviation of the estimated coefficient
returned at A{1,1}(2).
Examples
load iddata1 z1
load iddata2 z2
data = [z1 z2(1:300)];
nk = [1 1; 1 0];
na = [2 2; 1 3];
                                                                                                  1-945
1   Functions
          nb    =   [2 3; 1 4];
          nc    =   [2;3];
          nd    =   [1;2];
          nf    =   [2 2;2 1];
          The data loaded into z1 and z2 is discrete-time iddata with a sample time of 0.1 s. Therefore, sys is
          a two-input, two-output discrete-time idpoly model of the form:
                                  B q−1                C q−1
                    A q−1 y t =           u t − nk +           et
                                  F q−1                D q−1
Access the estimated polynomial coefficients of sys and the uncertainties in those coefficients.
[A,B,C,D,F,dA,dB,dC,dD,dF] = polydata(sys);
          The outputs A, B, C, D, and F are cell arrays of coefficient vectors. The dimensions of the cell arrays
          are determined by the input and output dimensions of sys. For example, A is a 2-by-2 cell array
          because sys has two inputs and two outputs. Each entry in A is a row vector containing identified
          polynomial coefficients. For example, examine the second diagonal entry in A.
A{2,2}
ans = 1×4
          For discrete-time sys, the coefficients are arranged in order of increasing powers of q−1. Therefore,
          A{2,2} corresponds to the polynomial 1 − 0 . 8682q−1 − 0 . 2244q−2 + 0 . 4467q−3 .
          The dimensions of dA match those of A. Each entry in dA gives the standard deviation of the
          corresponding estimated polynomial coefficient in A. For example, examine the uncertainties of the
          second diagonal entry in A.
dA{2,2}
ans = 1×4
          The lead coefficient of A{2,2} is fixed at 1, and therefore has no uncertainty. The remaining entries
          in dA{2,2} are the uncertainties in the q−1, q−2, and q−3 coefficients, respectively.
          See Also
          iddata | idpoly | idssdata | polyest | tfdata | zpkdata
1-946
                                                                                                    polyest
polyest
Estimate polynomial model using time- or frequency-domain data
Syntax
sys    =   polyest(data,[na nb nc nd nf nk])
sys    =   polyest(data,[na nb nc nd nf nk],Name,Value)
sys    =   polyest(data,init_sys)
sys    =   polyest( ___ , opt)
Description
sys = polyest(data,[na nb nc nd nf nk]) estimates a polynomial model, sys, using the
time- or frequency-domain data, data.
                   B(q)             C(q)
      A(q)y(t) =        u(t − nk) +      e(t)
                   F(q)             D(q)
A(q), B(q), F(q), C(q) and D(q) are polynomial matrices. u(t) is the input, and nk is the input delay. y(t)
is the output and e(t) is the disturbance signal. na ,nb, nc, nd and nf are the orders of the A(q), B(q),
C(q), D(q) and F(q) polynomials, respectively.
sys = polyest(data,init_sys) estimates a polynomial model using the linear system init_sys
to configure the initial parameterization.
sys = polyest( ___ , opt) estimates a polynomial model using the option set, opt, to specify
estimation behavior.
Input Arguments
data
Estimation data.
For time-domain estimation, data is an iddata object containing the input and output signal values.
You can estimate only discrete-time models using time-domain data. For estimating continuous-time
models using time-domain data, see tfest.
                                                                                                    1-947
1   Functions
It may be more convenient to use oe or tfest to estimate a model for frequency-domain data.
na
          na is an Ny-by-Ny matrix of nonnegative integers. Ny is the number of outputs, and Nu is the number
          of inputs.
nb
          nb is an Ny-by-Nu matrix of nonnegative integers. Ny is the number of outputs, and Nu is the number
          of inputs.
nc
nd
nf
          nf is an Ny-by-Nu matrix of nonnegative integers. Ny is the number of outputs, and Nu is the number
          of inputs.
nk
Input delay in number of samples, expressed as fixed leading zeros of the B polynomial.
opt
Estimation options.
1-948
                                                                                                 polyest
opt is an options set, created using polyestOptions, that specifies estimation options including:
• Estimation objective
• Handling of initial conditions
• Numerical search method to be used in estimation
init_sys
You obtain init_sys by either performing an estimation using measured data or by direct
construction.
If init_sys is an idpoly model, polyest uses the parameters and constraints defined in
init_sys as the initial guess for estimating sys.
Use the Structure property of init_sys to configure initial guesses and constraints for A(q), B(q),
F(q), C(q), and D(q). For example:
• To specify an initial guess for the A(q) term of init_sys, set init_sys.Structure.A.Value as
  the initial guess.
• To specify constraints for the B(q) term of init_sys:
If init_sys is not an idpoly model, the software first converts init_sys to a polynomial model.
polyest uses the parameters of the resulting model as the initial guess for estimation.
If opt is not specified, and init_sys is created by estimation, then the estimation options from
init_sys.Report.OptionsUsed are used.
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
IODelay
Transport delays. IODelay is a numeric array specifying a separate transport delay for each input/
output pair.
For continuous-time systems, specify transport delays in the time unit stored in the TimeUnit
property. For discrete-time systems, specify transport delays in integer multiples of the sample time,
Ts.
For a MIMO system with Ny outputs and Nu inputs, set IODelay to a Ny-by-Nu array. Each entry of
this array is a numerical value that represents the transport delay for the corresponding input/output
pair. You can also set IODelay to a scalar value to apply the same delay to all input/output pairs.
                                                                                                 1-949
1   Functions
InputDelay
          Input delay for each input channel, specified as a scalar value or numeric vector. For continuous-time
          systems, specify input delays in the time unit stored in the TimeUnit property. For discrete-time
          systems, specify input delays in integer multiples of the sample time Ts. For example, InputDelay =
          3 means a delay of three sample times.
          For a system with Nu inputs, set InputDelay to an Nu-by-1 vector. Each entry of this vector is a
          numerical value that represents the input delay for the corresponding input channel.
You can also set InputDelay to a scalar value to apply the same delay to all channels.
Default: 0
IntegrateNoise
                      1
          Where,           is the integrator in the noise channel, e(t).
                   1 − q−1
For example,
          Output Arguments
          sys
          Polynomial model, returned as an idpoly model. This model is created using the specified model
          orders, delays, and estimation options.
                         B(s)
                Y(s) =        U(s) + E(s)
                         F(s)
          Y(s), U(s) and E(s) are the Laplace transforms of the time-domain signals y(t), u(t) and e(t),
          respectively.
          Information about the estimation results and options used is stored in the Report property of the
          model. Report have the following fields:
1-950
                                                                                                polyest
Report       Description
Field
Status       Summary of the model status, which indicates whether the model was created by
             construction or obtained by estimation.
Method       Estimation command used.
InitialCo Handling of initial conditions during model estimation, returned as one of the following
ndition   values:
             This field is especially useful to view how the initial conditions were handled when the
             InitialCondition option in the estimation option set is 'auto'.
Fit          Quantitative assessment of the estimation, returned as a structure. See “Loss Function
             and Model Quality Metrics” for more information on these quality metrics. The
             structure has the following fields:
             Field         Description
             FitPerce Normalized root mean squared error (NRMSE) measure of how well the
             nt       response of the model fits the estimation data, expressed as the
                      percentage fit = 100(1-NRMSE).
             LossFcn       Value of the loss function when the estimation completes.
             MSE           Mean squared error (MSE) measure of how well the response of the
                           model fits the estimation data.
             FPE           Final prediction error for the model.
             AIC           Raw Akaike Information Criteria (AIC) measure of model quality.
             AICc          Small sample-size corrected AIC.
             nAIC          Normalized AIC.
             BIC           Bayesian Information Criteria (BIC).
Parameter Estimated values of model parameters.
s
OptionsUs Option set used for estimation. If no custom options were configured, this is a set of
ed        default options. See polyestOptions for more information.
RandState State of the random number stream at the start of estimation. Empty, [], if
          randomization was not used during estimation. For more information, see rng in the
          MATLAB documentation.
                                                                                                1-951
1   Functions
           Report      Description
           Field
           DataUsed    Attributes of the data used for estimation, returned as a structure with the following
                       fields:
                        Field        Description
                        Name         Name of the data set.
                        Type         Data type.
                        Length       Number of data samples.
                        Ts           Sample time.
                        InterSam Input intersample behavior, returned as one of the following values:
                        ple
                                 • 'zoh' — Zero-order hold maintains a piecewise-constant input signal
                                    between samples.
                                     • 'foh' — First-order hold maintains a piecewise-linear input signal
                                       between samples.
                                     • 'bl' — Band-limited behavior specifies that the continuous-time input
                                       signal has zero power above the Nyquist frequency.
                        InputOff Offset removed from time-domain input data during estimation. For
                        set      nonlinear models, it is [].
                        OutputOf Offset removed from time-domain output data during estimation. For
                        fset     nonlinear models, it is [].
           Terminati Termination conditions for the iterative search used for prediction error minimization.
           on        Structure with the following fields:
                        Field        Description
                        WhyStop      Reason for terminating the numerical search.
                        Iteratio Number of search iterations performed by the estimation algorithm.
                        ns
                        FirstOrd ∞-norm of the gradient search vector when the search algorithm
                        erOptima terminates.
                        lity
                        FcnCount Number of times the objective function was called.
                        UpdateNo Norm of the gradient search vector in the last iteration. Omitted when the
                        rm       search method is 'lsqnonlin' or 'fmincon'.
                        LastImpr Criterion improvement in the last iteration, expressed as a percentage.
                        ovement Omitted when the search method is 'lsqnonlin' or 'fmincon'.
                        Algorith Algorithm used by 'lsqnonlin' or 'fmincon' search method. Omitted
                        m        when other search methods are used.
                       For estimation methods that do not require numerical search optimization, the
                       Termination field is omitted.
1-952
                                                                                               polyest
Examples
Estimate a model with redundant parameterization. That is, a model with all polynomials ( A, B, C, D,
and F) active.
na   =   2;
nb   =   2;
nc   =   3;
nd   =   3;
nf   =   2;
nk   =   1;
m1 = polyest(m0simdata(1:150),[0 20 20 20 20 1]);
Estimate a regularized polynomial model of the same order. Determine the Lambda value by trial and
error.
opt = polyestOptions;
opt.Regularization.Lambda = 1;
m2 = polyest(m0simdata(1:150),[0 20 20 20 20 1],opt);
Obtain a lower-order polynomial model by converting a regularized ARX model and reducing its
order. Use arxregul to determine the regularization parameters.
                                                                                                1-953
1   Functions
          opt2 = compareOptions('InitialCondition','z');
          compare(m0simdata(150:end),m1,m2,mr,opt2);
Load input/output data and create cumulative sum input and output signals for estimation.
          load iddata1 z1
          data = iddata(cumsum(z1.y),cumsum(z1.u),z1.Ts,'InterSample','foh');
Specify the model polynomial orders. Set the orders of the inactive polynomials, D and F, to 0.
          na    =   2;
          nb    =   2;
          nc    =   2;
          nd    =   0;
          nf    =   0;
          nk    =   1;
1-954
                                                                                                    polyest
load iddata1 z1
load iddata2 z2
data = [z1 z2(1:300)];
data is a data set with 2 inputs and 2 outputs. The first input affects only the first output. Similarly,
the second input affects only the second output.
Specify the model orders and delays. The F and D polynomials are inactive.
na   =   [2 2; 2   2];
nb   =   [2 2; 3   4];
nk   =   [1 1; 0   0];
nc   =   [2;2];
nd   =   [0;0];
nf   =   [0 0; 0   0];
In the estimated ARMAX model, the cross terms, which model the effect of the first input on the
second output and vice versa, are negligible. If you assigned higher orders to those dynamics, their
estimation would show a high level of uncertainty.
h = bodeplot(sys);
showConfidence(h,3)
                                                                                                    1-955
1   Functions
          Tips
          • In most situations, all the polynomials of an identified polynomial model are not simultaneously
            active. Set one or more of the orders na, nc, nd and nf to zero to simplify the model structure.
For example, you can estimate an Output-Error (OE) model by specifying na, nc and nd as zero.
                Alternatively, you can use a dedicated estimating function for the simplified model structure.
                Linear polynomial estimation functions include oe, bj, arx and armax.
          Alternatives
          • To estimate a polynomial model using time-series data, use ar.
          • Use polyest to estimate a polynomial of arbitrary structure. If the structure of the estimated
            polynomial model is known, that is, you know which polynomials will be active, then use the
            appropriate dedicated estimating function. For examples, for an ARX model, use arx. Other
            polynomial model estimating functions include, oe, armax, and bj.
          • To estimate a continuous-time transfer function, use tfest. You can also use oe, but only with
            continuous-time frequency-domain data.
1-956
                                                                                            polyest
Extended Capabilities
Automatic Parallel Support
Accelerate code by automatically running computation in parallel using Parallel Computing Toolbox™.
Parallel computing support is available for estimation using the lsqnonlin search method (requires
Optimization Toolbox). To enable parallel computing, use polyestOptions, set SearchMethod to
'lsqnonlin', and set SearchOptions.Advanced.UseParallel to true.
For example:
opt = polyestOptions;
opt.SearchMethod = 'lsqnonlin';
opt.SearchOptions.Advanced.UseParallel = true;
See Also
ar | armax | arx | bj | forecast | iddata | idpoly | oe | pem | polyestOptions | procest |
ssest | tfest
Topics
“Regularized Estimates of Model Parameters”
Introduced in R2012a
                                                                                             1-957
1   Functions
          polyestOptions
          Option set for polyest
          Syntax
          opt = polyestOptions
          opt = polyestOptions(Name,Value)
          Description
          opt = polyestOptions creates the default option set for polyest.
          opt = polyestOptions(Name,Value) creates an option set with the options specified by one or
          more Name,Value pair arguments.
          Input Arguments
          Name-Value Pair Arguments
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Handling of initial conditions during estimation, specified as one of the following values:
          Error to be minimized in the loss function during estimation, specified as the comma-separated pair
          consisting of 'Focus' and one of the following values:
          • 'prediction' — The one-step ahead prediction error between measured and predicted outputs
            is minimized during estimation. As a result, the estimation focuses on producing a good predictor
            model.
          • 'simulation' — The simulation error between measured and simulated outputs is minimized
            during estimation. As a result, the estimation focuses on making a good fit for simulation of model
            response with the current inputs.
          The Focus option can be interpreted as a weighting filter in the loss function. For more information,
          see “Loss Function and Model Quality Metrics”.
1-958
                                                                                          polyestOptions
Weighting prefilter applied to the loss function to be minimized during estimation. To understand the
effect of WeightingFilter on the loss function, see “Loss Function and Model Quality Metrics”.
   Passbands are expressed in rad/TimeUnit for time-domain data and in FrequencyUnit for
   frequency-domain data, where TimeUnit and FrequencyUnit are the time and frequency units
   of the estimation data.
• SISO filter — Specify a single-input-single-output (SISO) linear filter in one of the following ways:
       This option calculates the weighting function as a product of the filter and the input spectrum
       to estimate the transfer function.
• Weighting vector — Applicable for frequency-domain data only. Specify a column vector of
  weights. This vector must have the same length as the frequency vector of the data set,
  Data.Frequency. Each input and output response in the data is multiplied by the corresponding
  weight at that frequency.
Control whether to enforce stability of estimated model, specified as the comma-separated pair
consisting of 'EnforceStability' and either true or false.
This option is not available for multi-output models with a non-diagonal A polynomial array.
Data Types: logical
If EstimateCovariance is true, then use getcov to fetch the covariance matrix from the
estimated model.
                                                                                                  1-959
1   Functions
Specify whether to display the estimation progress, specified as one of the following values:
          • 'on' — Information on model structure and estimation results are displayed in a progress-viewer
            window.
          • 'off' — No progress or results information is displayed.
          Removal of offset from time-domain input data during estimation, specified as the comma-separated
          pair consisting of 'InputOffset' and one of the following:
          • A column vector of positive integers of length Nu, where Nu is the number of inputs.
          • [] — Indicates no offset.
          • Nu-by-Ne matrix — For multi-experiment data, specify InputOffset as an Nu-by-Ne matrix. Nu
            is the number of inputs, and Ne is the number of experiments.
Each entry specified by InputOffset is subtracted from the corresponding input data.
          Removal of offset from time-domain output data during estimation, specified as the comma-separated
          pair consisting of 'OutputOffset' and one of the following:
Each entry specified by OutputOffset is subtracted from the corresponding output data.
          Options for regularized estimation of model parameters. For more information on regularization, see
          “Regularized Estimates of Model Parameters”.
Specify a positive scalar to add the regularization term to the estimation cost.
                Default: 0
          • R — Weighting matrix.
                Specify a vector of nonnegative numbers or a square positive semi-definite matrix. The length
                must be equal to the number of free parameters of the model.
1-960
                                                                                          polyestOptions
   For black-box models, using the default value is recommended. For structured and grey-box
   models, you can also specify a vector of np positive numbers such that each entry denotes the
   confidence in the value of the associated parameter.
   The default value of 1 implies a value of eye(npfree), where npfree is the number of free
   parameters.
   Default: 1
• Nominal — The nominal value towards which the free parameters are pulled during estimation.
   The default value of zero implies that the parameter values are pulled towards zero. If you are
   refining a model, you can set the value to 'model' to pull the parameters towards the parameter
   values of the initial model. The initial parameter values must be finite for this setting to work.
Default: 0
Numerical search method used for iterative parameter estimation, specified as the comma-separated
pair consisting of 'SearchMethod' and one of the following:
• 'auto' — A combination of the line search algorithms, 'gn', 'lm', 'gna', and 'grad' methods
  is tried in sequence at each iteration. The first descent direction leading to a reduction in
  estimation cost is used.
• 'gn' — Subspace Gauss-Newton least squares search. Singular values of the Jacobian matrix less
  than GnPinvConstant*eps*max(size(J))*norm(J) are discarded when computing the
  search direction. J is the Jacobian matrix. The Hessian matrix is approximated as JTJ. If there is no
  improvement in this direction, the function tries the gradient direction.
• 'gna' — Adaptive subspace Gauss-Newton search. Eigenvalues less than gamma*max(sv) of the
  Hessian are ignored, where sv contains the singular values of the Hessian. The Gauss-Newton
  direction is computed in the remaining subspace. gamma has the initial value
  InitialGnaTolerance (see Advanced in 'SearchOptions' for more information). This value
  is increased by the factor LMStep each time the search fails to find a lower value of the criterion
  in fewer than five bisections. This value is decreased by the factor 2*LMStep each time a search is
  successful without any bisections.
• 'lm' — Levenberg-Marquardt least squares search, where the next parameter value is -pinv(H
  +d*I)*grad from the previous one. H is the Hessian, I is the identity matrix, and grad is the
  gradient. d is a number that is increased until a lower value of the criterion is found.
• 'grad' — Steepest descent least squares search.
• 'lsqnonlin' — Trust-region-reflective algorithm of lsqnonlin. Requires Optimization Toolbox
  software.
• 'fmincon' — Constrained nonlinear solvers. You can use the sequential quadratic programming
  (SQP) and trust-region-reflective algorithms of the fmincon solver. If you have Optimization
  Toolbox software, you can also use the interior-point and active-set algorithms of the fmincon
  solver. Specify the algorithm in the SearchOptions.Algorithm option. The fmincon algorithms
  may result in improved estimation results in the following scenarios:
   • Constrained minimization problems when there are bounds imposed on the model parameters.
   • Model structures where the loss function is a nonlinear or non smooth function of the
     parameters.
                                                                                                 1-961
1   Functions
                • Multi-output model estimation. A determinant loss function is minimized by default for multi-
                  output model estimation. fmincon algorithms are able to minimize such loss functions directly.
                  The other search methods such as 'lm' and 'gn' minimize the determinant loss function by
                  alternately estimating the noise variance and reducing the loss value for a given noise variance
                  value. Hence, the fmincon algorithms can offer better efficiency and accuracy for multi-output
                  model estimations.
          Option set for the search algorithm, specified as the comma-separated pair consisting of
          'SearchOptions' and a search option set with fields that depend on the value of SearchMethod.
1-962
                                                                                    polyestOptions
                                                                                            1-963
1   Functions
1-964
                                                                                        polyestOptions
                                                                                               1-965
1   Functions
                                      • 'sqp' — Sequential
                                        quadratic programming
                                        algorithm. The algorithm
                                        satisfies bounds at all
                                        iterations, and it can recover
                                        from NaN or Inf results. It is
                                        not a large-scale algorithm.
                                        For more information, see
                                        “Large-Scale vs. Medium-
                                        Scale Algorithms”
                                        (Optimization Toolbox).
                                      • 'trust-region-
                                        reflective' — Subspace
                                        trust-region method based
                                        on the interior-reflective
                                        Newton method. It is a large-
                                        scale algorithm.
                                      • 'interior-point' —
                                        Large-scale algorithm that
                                        requires Optimization
                                        Toolbox software. The
                                        algorithm satisfies bounds at
                                        all iterations, and it can
                                        recover from NaN or Inf
                                        results.
                                      • 'active-set' — Requires
                                        Optimization Toolbox
                                        software. The algorithm can
                                        take large steps, which adds
                                        speed. It is not a large-scale
                                        algorithm.
1-966
                                                                                          polyestOptions
• ErrorThreshold — Specifies when to adjust the weight of large errors from quadratic to linear.
   Errors larger than ErrorThreshold times the estimated standard deviation have a linear weight
   in the loss function. The standard deviation is estimated robustly as the median of the absolute
   deviations from the median of the prediction errors, divided by 0.7. For more information on
   robust norm choices, see section 15.2 of [2].
   Default: 0
• MaxSize — Specifies the maximum number of elements in a segment when input-output data is
  split into segments.
   Default: 250000
• StabilityThreshold — Specifies thresholds for stability tests.
   • s — Specifies the location of the right-most pole to test the stability of continuous-time models.
     A model is considered stable when its right-most pole is to the left of s.
      Default: 0
   • z — Specifies the maximum distance of all poles from the origin to test stability of discrete-
     time models. A model is considered stable if all poles are within the distance z from the origin.
                                                                                                 1-967
1   Functions
                   Default: 1+sqrt(eps)
          • AutoInitThreshold — Specifies when to automatically estimate the initial condition.
                  yp, z − ymeas
                                > AutoInitThreshold
                  yp, e − ymeas
Default: 1.05
          Output Arguments
          opt — Options set for polyest
          polyestOptions option set
Examples
opt = polyestOptions;
Create an option set for polyest where you enforce model stability and set the Display to 'on'.
opt = polyestOptions('EnforceStability',true,'Display','on');
          opt = polyestOptions;
          opt.EnforceStability = true;
          opt.Display = 'on';
          Compatibility Considerations
          Renaming of Estimation and Analysis Options
          The names of some estimation and analysis options were changed in R2018a. Prior names still work.
          For details, see the R2018a release note “Renaming of Estimation and Analysis Options”.
1-968
                                                                                         polyestOptions
References
[1] Wills, Adrian, B. Ninness, and S. Gibson. “On Gradient-Based Search for Multivariable System
         Estimates”. Proceedings of the 16th IFAC World Congress, Prague, Czech Republic, July 3–8,
         2005. Oxford, UK: Elsevier Ltd., 2005.
[2] Ljung, L. System Identification: Theory for the User. Upper Saddle River, NJ: Prentice-Hall PTR,
        1999.
See Also
polyest
Topics
“Loss Function and Model Quality Metrics”
Introduced in R2012a
                                                                                                1-969
1   Functions
          polyreg
          Powers and products of standard regressors
          Syntax
          R = polyreg(model)
          R = polyreg(model,'MaxPower',n)
          R = polyreg(model,'MaxPower',n,'CrossTerm',CrossTermVal)
          Description
          R = polyreg(model) creates an array R of polynomial regressors up to the power 2. If a model
          order has input u and output y, na=nb=2, and delay nk=1, polynomial regressors are y(t−1)2, u(t
          −1)2, y(t−2)2, u(t−2)2. model is an idnlarx object. You must add these regressors to the model by
          assigning the CustomRegressors model property or by using addreg.
Examples
          Regressors:
              y1(t-1)
              y1(t-2)
              u1(t-1)
              u1(t-2)
              y1(t-1).^2
1-970
                                                                                                 polyreg
     y1(t-2).^2
     u1(t-1).^2
     u1(t-2).^2
load iddata1
m = nlarx(z1,[2 1 1]);
R = polyreg(m,'MaxPower',3,'CrossTerm','on')
16x1 array of Custom Regressors with fields: Function, Arguments, Delays, Vectorized
                                                                                         2
If the model m has three standard regressors a, b and c, then R includes the terms a2, b , c2, ab, ac,
                2             2            3
bc, a2b, a2c, ab , abc, ac2, b c, bc2, a3, b , and c3.
m = nlarx(z1,[2 1 1],'wavenet','CustomReg',R);
See Also
addreg | customreg | getreg | idnlarx | nlarx
Topics
“Identifying Nonlinear ARX Models”
Introduced in R2007a
                                                                                                  1-971
1   Functions
          poly1d
          Class representing single-variable polynomial nonlinear estimator for Hammerstein-Wiener models
          Syntax
          t=poly1d('Degree',n)
          t=poly1d('Coefficients',C)
          t=poly1d(n)
          Description
          poly1d is an object that stores the single-variable polynomial nonlinear estimator for Hammerstein-
          Wiener models.
You can use the constructor to create the nonlinearity object, as follows:
Use evaluate(p,x) to compute the value of the function defined by the poly1d object p at x.
          poly1d Properties
          After creating the object, you can use get or dot notation to access the object property values. For
          example:
          % List all property values
          get(p)
          % Get value of Coefficients property
          p.Coefficients
For example:
                                  poly1d('Degree',3)
Coefficients                      1-by-(n+1) matrix containing the polynomial coefficients.
          Examples
          Use poly1s to specify the single-variable polynomial nonlinearity estimator in Hammerstein-Wiener
          models. For example:
          m=nlhw(Data,Orders,poly1d('deg',3),[]);
1-972
                                                                                               poly1d
Tips
Use poly1d to define a nonlinear function y = F(x), where F is a single-variable polynomial function
of x:
See Also
nlhw
Introduced in R2007b
                                                                                               1-973
1   Functions
          predict
          Predict K-step ahead model output
          Syntax
          yp = predict(sys,data,K)
          yp = predict(sys,data,K,opt)
          [yp,x0,sys_pred] = predict( ___ )
          predict(sys,data,K, ___ )
          predict(sys,Linespec,data,K, ___ )
          predict(sys1,...,sysN,data,K, ___ )
          predict(sys1,Linespec1,...,sysN,LinespecN,data,K, ___ )
          Description
          This predict command computes the K-step ahead output of an identified model using measured
          input-output data. To identify the model, you first collect all the input-output data and then estimate
          the model parameters offline. To perform online state estimation of a nonlinear system using real-
          time data, use the predict command for extended and unscented Kalman filters instead.
          yp = predict(sys,data,K) predicts the output of an identified model sys, K steps ahead using
          the measured input-output data.
          predict command predicts the output response over the time span of measured data. In contrast,
          forecast performs prediction into the future in a time range beyond the last instant of measured
          data. Use predict to validate sys over the time span of measured data.
          yp = predict(sys,data,K,opt) uses the option set opt to specify additional prediction options
          such as handling of initial conditions and data offsets.
          [yp,x0,sys_pred] = predict( ___ ) also returns the estimated values for initial states x0 and a
          predictor model sys_pred. Use with any of the previous input argument combinations.
          predict(sys,data,K, ___ ) plots the predicted output. Use with any of the previous input
          argument combinations. To change display options in the plot, right-click the plot to access the
          context menu. For more details about the menu, see “Tips” on page 1-983.
          You can also plot the predicted model response using the compare command. The compare
          command compares the prediction results with observed data and displays a quantitative goodness of
          fit.
          predict(sys,Linespec,data,K, ___ ) uses Linespec to specify the line type, marker symbol,
          and color.
1-974
                                                                                             predict
Examples
data is an iddata object containing the simulated response data of a time series model.
na = 1;
nb = 2;
sys = armax(data(1:200),[na nb]);
K = 4;
yp = predict(sys,data,K);
yp is an iddata object. The predicted output is returned in the OutputData property of the object.
plot(data(201:400),yp(201:400));
legend('Estimation data','Predicted data');
                                                                                             1-975
1   Functions
Alternatively, to plot the predicted response and estimation data, use compare(sys,data,K).
          load iddata1;
          data = z1;
sys2 = tfest(data,2);
Create a predict option set to specify zero initial conditions for prediction.
opt = predictOptions('InitialCondition','z');
          Plot the predicted outputs for the estimated models. Use the specified prediction option set, opt, and
          specify prediction horizon as 10. Specify line styles for plotting the predicted output of each system.
predict(sys1,'r--',sys2,'b',data,10,opt);
1-976
                                                                                                predict
To change the display options, right-click the plot to access the context menu. For example, to view
the estimation data, select Show Validation Data from the context menu. To view the prediction
error, select Prediction Error Plot.
You can also plot the predicted response using the compare command. To do so, first create an option
set for compare to specify the use of zero initial conditions.
opt = compareOptions('InitialCondition','z');
compare(data,sys1,'r--',sys2,'b',10,opt);
                                                                                                1-977
1   Functions
          Use estimation data to estimate a model, and then compute the predicted model output and predictor
          model using the predict command. Simulate the predictor model to reproduce the predicted output.
          load iddata3 z3
          data = z3;
          K = 4;
          [yp,x0,sysp] = predict(sys,data,K);
          yp is the predicted model response, x0 is the estimated value for initial states, and sysp is the
          predictor model.
1-978
                                                                                                   predict
opt = simOptions;
opt.InitialCondition = x0;
ys = sim(sysp,[data.OutputData,data.InputData],opt);
t = yp.SamplingInstants;
plot(t,yp.OutputData,'b',t,ys,'.r');
legend('Predicted Output','Simulated Output')
Perform model prediction using historical data to specify initial conditions. You first predict using the
predict command and specify the historical data using the predictOptions option set. You then
reproduce the predicted response by manually mapping the historical data to initial states.
load iddata7 z7
sys = n4sid(z7,5);
                                                                                                   1-979
1   Functions
          zA = z7(1:15);
          zB = z7(16:end);
          Suppose that you want to compute the 10-step-ahead prediction of the response of the identified
          system for data zB. For initial conditions, use the signal values in zA as the historical record. That is,
          the input and output values for the time immediately preceding data in zB.
          IO = struct('Input',zA.InputData,'Output',zA.OutputData);
          opt = predictOptions('InitialCondition',IO);
Generate the 10-step-ahead prediction for data zB using the specified initial conditions and predict.
[yp,x0,Predictor] = predict(sys,zB,10,opt);
          yp is the predicted model response, x0 are the initial states corresponding to the predictor model
          Predictor. You can simulate Predictor using x0 as initial conditions to reproduce
          yp.OutputData.
          Now reproduce the output by manually mapping the historical data to initial states. To do so,
          minimize 1-step prediction errors over the time span of zA.
x0est = data2state(sys,zA);
          x0est contains the values of the five states of sys at the time instant immediately after the most
          recent data sample in zA.
          The Predictor has more states than the original system due to the 10-step prediction horizon.
          Specify the additional states induced by the horizon to zero initial values, and then append x0est.
          x0Predictor = zeros(order(Predictor),1);
          x0Predictor(end-4:end) = x0est;
          Plot the predicted output of the predict command yp.OutputData and the manually computed
          results ysim.
plot(t,yp.OutputData,t,ysim, '.')
1-980
                                                                                             predict
Input Arguments
sys — Identified model
linear model | nonlinear model
   When sys is an idnlhw or idnlgrey model, the predicted output yp is the same as the simulated
   response computed using data.InputData as input.
If a model is unavailable, estimate sys from data using commands such as ar, armax, tfest,
nlarx, and ssest.
• iddata object — Use observed input and output signals to create an iddata object. For time-
  series data (no inputs), specify as an iddata object with no inputs iddata(output,[]).
                                                                                             1-981
1   Functions
          • Matrix of doubles — For models withNu inputs and Ny outputs, specify data as an N-by-(Ny+Nu)
            matrix. Where, N is the number of observations.
          K — Prediction horizon
          1 (default) | positive integer | Inf
          • Positive integer — Output yp is calculated K steps into the future, where K represents a multiple
            of data sample time.
                The output at time instant t is calculated using previously measured outputs up to time t-K and
                inputs up to the time instant t.
          • Inf — No previous outputs are used in the computation, and predict returns the same result as
            simulation using the sim command.
          For Output-Error models, there is no difference between the K step-ahead predictions and the
          simulated output. This is because Output-Error models only use past inputs to predict future outputs.
          Note For careful model validation, a one-step-ahead prediction (K = 1) is usually not a good test for
          validating the model sys over the time span of measured data. Even the trivial one step-ahead
          predictor, y (t) = y(t − 1), can give good predictions. So a poor model may look fine for one-step-
          ahead prediction of data that has a small sample time. Prediction with K = Inf, which is the same as
          performing simulation with sim command, can lead to diverging outputs because low-frequency
          disturbances in the data are emphasized, especially for models with integration. Use a K value
          between 1 and Inf to capture the mid-frequency behavior of the measured data.
          Prediction options, specified as a predictOptions option set. Use the option set to specify
          prediction options such as handling of initial conditions and data offsets.
Line style, marker, and color, specified as a character vector. For example, 'b' or 'b+:'.
For more information about configuring Linespec, see the Linespec argument of plot.
          Output Arguments
          yp — Predicted output response
          iddata object | matrix of doubles
          • iddata object — When data is an iddata object. The OutputData property of yp stores the
            values of the predicted output. The time variable takes values in the range represented by
            data.SamplingInstants.
1-982
                                                                                                predict
The output at time instant t is calculated using previously measured outputs up to time t-K and
inputs up to the time instant t. In other words, the predicted response at time point r of measured
data is stored in the r+K-1 sample of yp. Note that at time r, the future inputs u(r+1), u(r+2),...,
u(r+K) required for prediction are assumed to be known. For multi-experiment data, yp contains a
predicted data set for each experiment. The time span of the predicted outputs matches that of the
observed data.
When sys is specified using an idnlhw or idnlgrey model, yp is the same as the simulated
response computed using data.InputData as input.
Estimated initial states corresponding to the predictor model sys_pred, returned as a column vector
of size equal to number of states. If data is multi-experiment, x0 is a cell array of size Ne, where Ne
is the number of experiments. You can simulate sys_pred using x0 as initial conditions, to reproduce
the results of prediction. For an example, see “Reproduce Prediction Results by Simulation” on page
1-978.
If you specify opt.InitialCondition as 'z', the initial conditions of data are not estimated and
x0 equals 0.
Predictor model, returned as a dynamic system model. For multi-experiment data, sys_pred is an
array of models, with one entry for each experiment. You can use the predictor model sys_pred and
estimated initial states x0 to reproduce the results of prediction:
• If sys is a linear model, the predictor model is returned as either a model of the same type as sys
  or as a state-space version of the model (idss). To reproduce the results of prediction, simulate
  sys_pred using [data.OutputData data.InputData] as input and x0 as initial conditions.
  The simulation output is the same as the predicted output yp.OutputData. For an example, see
  “Reproduce Prediction Results by Simulation” on page 1-978.
• When sys is a nonlinear grey-box model (idnlgrey) or Hammerstein-Wiener model (idnlhw),
  the noise-component of the model is trivial, and so the predictor model is the same as the model.
  sys_pred is returned empty. To reproduce the results of prediction, simulate sys using initial
  conditions x0. For a definition of the states of idnlhw models, see “Definition of idnlhw States” on
  page 1-557.
• If sys is a nonlinear ARX model (idnlarx), sys_pred and x0 are returned empty. You cannot
  reproduce the prediction results by simulation.
For discrete-time data that is time-domain or frequency-domain data with sample time Ts greater
than zero, sys_pred is a discrete-time model, even if sys is a continuous-time model.
Tips
• Right-clicking the plot of the predicted output opens the context menu, where you can access the
  following options:
                                                                                                1-983
1   Functions
                • Systems — Select systems to view predicted response. By default, the response of all systems
                  is plotted.
                • Data Experiment — For multi-experiment data only. Toggle between data from different
                  experiments.
                • Characteristics — View the following data characteristics:
                   • Peak Value — View the absolute peak value of the data. Applicable for time–domain data
                     only.
                   • Peak Response — View peak response of the data. Applicable for frequency-response data
                     only.
                   • Mean Value — View mean value of the data. Applicable for time–domain data only.
                • Show — For frequency-domain and frequency-response data only.
          See Also
          compare | forecast | iddata | pe | predictOptions | sim | simsd
          Topics
          “Simulate and Predict Identified Model Output”
1-984
                                                  predict
                                                  1-985
1   Functions
          predict
          Predict state and state estimation error covariance at next time step using extended or unscented
          Kalman filter, or particle filter
          Syntax
          [PredictedState,PredictedStateCovariance] = predict(obj)
          [PredictedState,PredictedStateCovariance] = predict(obj,Us1,...Usn)
          Description
          The predict command predicts the state and state estimation error covariance of an
          extendedKalmanFilter, unscentedKalmanFilter or particleFilter object at the next time
          step. To implement the extended or unscented Kalman filter algorithms, use the predict and
          correct commands together. If the current output measurement exists, you can use predict and
          correct. If the measurement is missing, you can only use predict. For information about the order
          in which to use the commands, see “Using predict and correct Commands” on page 1-993.
          Use this predict command for online state estimation using real-time data. When data is not
          available in real time, to compute the K-step ahead output of an identified model, use predict for
          offline estimation.
          Use this syntax if the state transition function f that you specified in obj.StateTransitionFcn has
          one of the following forms:
          Where x and w are the state and process noise of the system. The only inputs to f are the states and
          process noise.
1-986
                                                                                                       predict
Use this syntax if your state transition function f has one of the following forms:
Examples
Estimate the states of a van der Pol oscillator using an unscented Kalman filter algorithm and
measured output data. The oscillator has two states and one output.
Create an unscented Kalman filter object for the oscillator. Use previously written and saved state
transition and measurement functions, vdpStateFcn.m and vdpMeasurementFcn.m. These
functions describe a discrete-approximation to a van der Pol oscillator with nonlinearity parameter,
mu, equal to 1. The functions assume additive process and measurement noise in the system. Specify
the initial state values for the two states as [1;0]. This is the guess for the state value at initial time k,
using knowledge of system outputs until time k-1, x[k k − 1].
obj = unscentedKalmanFilter(@vdpStateFcn,@vdpMeasurementFcn,[1;0]);
Load the measured output data, y, from the oscillator. In this example, use simulated static data for
illustration. The data is stored in the vdp_data.mat file.
load vdp_data.mat y
Specify the process noise and measurement noise covariances of the oscillator.
obj.ProcessNoise = 0.01;
obj.MeasurementNoise = 0.16;
residBuf = [];
xcorBuf = [];
xpredBuf = [];
Implement the unscented Kalman filter algorithm to estimate the states of the oscillator by using the
correct and predict commands. You first correct x[k k − 1] using measurements at time k to get
x[k k]. Then, you predict the state value at next time step, x[k + 1 k], using x[k k], the state estimate
at time step k that is estimated using measurements until time k.
To simulate real-time data measurements, use the measured data one time step at a time. Compute
the residual between the predicted and actual measurement to assess how well the filter is
performing and converging. Computing the residual is an optional step. When you use residual,
place the command immediately before the correct command. If the prediction matches the
measurement, the residual is zero.
After you perform the real-time commands for the time step, buffer the results so that you can plot
them after the run is complete.
for k = 1:size(y)
    [Residual,ResidualCovariance] = residual(obj,y(k));
    [CorrectedState,CorrectedStateCovariance] = correct(obj,y(k));
                                                                                                       1-987
1   Functions
[PredictedState,PredictedStateCovariance] = predict(obj);
                 residBuf(k,:) = Residual;
                 xcorBuf(k,:) = CorrectedState';
                 xpredBuf(k,:) = PredictedState';
end
          When you use the correct command, obj.State and obj.StateCovariance are updated with
          the corrected state and state estimation error covariance values for time step k, CorrectedState
          and CorrectedStateCovariance. When you use the predict command, obj.State and
          obj.StateCovariance are updated with the predicted values for time step k+1, PredictedState
          and PredictedStateCovariance.
          In this example, you used correct before predict because the initial state value was x[k k − 1], a
          guess for the state value at initial time k using system outputs until time k-1. If your initial state
          value is x[k − 1 k − 1], the value at previous time k-1 using measurement until k-1, then use the
          predict command first. For more information about the order of using predict and correct, see
          “Using predict and correct Commands” on page 1-993.
          Plot the actual measurement, the corrected estimated measurement, and the residual. For the
          measurement function in vdpMeasurementFcn, the measurement is the first state.
1-988
                                                                                                 predict
M = [y,xcorBuf(:,1),residBuf];
plot(M)
grid on
title('Actual and Estimated Measurements, Residual')
legend('Measured','Estimated','Residual')
The estimate tracks the measurement closely. After the initial transient, the residual remains
relatively small throughout the run.
Load the van der Pol ODE data, and specify the sample time.
vdpODEdata.mat contains a simulation of the van der Pol ODE with nonlinearity parameter mu=1,
using ode45, with initial conditions [2;0]. The true state was extracted with sample time dt =
0.05.
load ('vdpODEdata.mat','xTrue','dt')
tSpan = 0:dt:5;
Get the measurements. For this example, a sensor measures the first state with a Gaussian noise with
standard deviation 0.04.
                                                                                                 1-989
1   Functions
          sqrtR = 0.04;
          yMeas = xTrue(:,1) + sqrtR*randn(numel(tSpan),1);
          Create a particle filter, and set the state transition and measurement likelihood functions.
          myPF = particleFilter(@vdpParticleFilterStateFcn,@vdpMeasurementLikelihoodFcn);
          Initialize the particle filter at state [2; 0] with unit covariance, and use 1000 particles.
          initialize(myPF,1000,[2;0],eye(2));
          Estimate the states using the correct and predict commands, and store the estimated states.
          xEst = zeros(size(xTrue));
          for k=1:size(xTrue,1)
              xEst(k,:) = correct(myPF,yMeas(k));
              predict(myPF);
          end
          Plot the results, and compare the estimated and true states.
          figure(1)
          plot(xTrue(:,1),xTrue(:,2),'x',xEst(:,1),xEst(:,2),'ro')
          legend('True','Estimated')
1-990
                                                                                                predict
Consider a nonlinear system with input u whose state x and measurement y evolve according to the
following state transition and measurement equations:
                                2
    y[k] = x[k] + 2 * u[k] + v[k]
The process noise w of the system is additive while the measurement noise v is nonadditive.
Create the state transition function and measurement function for the system. Specify the functions
with an additional input u.
f = @(x,u)(sqrt(x+u));
h = @(x,v,u)(x+2*u+v^2);
f and h are function handles to the anonymous functions that store the state transition and
measurement functions, respectively. In the measurement function, because the measurement noise
is nonadditive, v is also specified as an input. Note that v is specified as an input before the
additional input u.
Create an extended Kalman filter object for estimating the state of the nonlinear system using the
specified functions. Specify the initial value of the state as 1 and the measurement noise as
nonadditive.
obj = extendedKalmanFilter(f,h,1,'HasAdditiveMeasurementNoise',false);
obj.MeasurementNoise = 0.01;
You can now estimate the state of the system using the predict and correct commands. You pass
the values of u to predict and correct, which in turn pass them to the state transition and
measurement functions, respectively.
Correct the state estimate with measurement y[k]=0.8 and input u[k]=0.2 at time step k.
correct(obj,0.8,0.2)
predict(obj,0.2)
Retrieve the error, or residual, between the prediction and the measurement.
                                                                                               1-991
1   Functions
          Input Arguments
          obj — Extended or unscented Kalman filter, or particle filter object
          extendedKalmanFilter object | unscentedKalmanFilter object | particleFilter object
          Extended or unscented Kalman filter, or particle filter object for online state estimation, created using
          one of the following commands:
          Additional input arguments to state transition function, specified as input arguments of any type. The
          state transition function, f, is specified in the StateTransitionFcn property of the object. If the
          function requires input arguments in addition to the state and process noise values, you specify these
          inputs in the predict command syntax.
          For example, suppose that your state transition function calculates the predicted state x at time step
          k using system inputs u(k-1) and time k-1, in addition to the state x(k-1):
x(k) = f(x(k-1),u(k-1),k-1)
          Then when you perform online state estimation at time step k, specify these additional inputs in the
          predict command syntax:
[PredictedState,PredictedStateCovariance] = predict(obj,u(k-1),k-1);
          Output Arguments
          PredictedState — Predicted state estimate
          vector
          Predicted state estimate, returned as a vector of size M, where M is the number of states of the
          system. If you specify the initial states of obj as a column vector then M is returned as a column
          vector, otherwise M is returned as a row vector.
          For information about how to specify the initial states of the object, see the
          extendedKalmanFilter, unscentedKalmanFilter and particleFilter reference pages.
          Predicted state estimation error covariance, returned as an M-by-M matrix, where M is the number of
          states of the system.
1-992
                                                                                                    predict
More About
Using predict and correct Commands
After you have created an extended or unscented Kalman filter, or particle filter object, obj, to
implement the estimation algorithms, use the correct and predict commands together.
At time step k, correct command returns the corrected value of states and state estimation error
covariance using measured system outputs y[k] at the same time step. If your measurement function
has additional input arguments Um, you specify these as inputs to the correct command. The
command passes these values to the measurement function.
[CorrectedState,CorrectedCovariance] = correct(obj,y,Um)
The correct command updates the State and StateCovariance properties of the object with the
estimated values, CorrectedState and CorrectedCovariance.
The predict command returns the prediction of state and state estimation error covariance at the
next time step. If your state transition function has additional input arguments Us, you specify these
as inputs to the predict command. The command passes these values to the state transition
function.
[PredictedState,PredictedCovariance] = predict(obj,Us)
The predict command updates the State and StateCovariance properties of the object with the
predicted values, PredictedState and PredictedCovariance.
If the current output measurement exists at a given time step, you can use correct and predict. If
the measurement is missing, you can only use predict. For details about how these commands
implement the algorithms, see “Extended and Unscented Kalman Filter Algorithms for Online State
Estimation”.
The order in which you implement the commands depends on the availability of measured data y, Us,
and Um for your system:
• correct then predict — Assume that at time step k, the value of obj.State is x [k k − 1]. This
  value is the state of the system at time k, estimated using measured outputs until time k-1. You
  also have the measured output y[k] and inputs Us[k] and Um[k] at the same time step.
   Then you first execute the correct command with measured system data y[k] and additional
   inputs Um[k]. The command updates the value of obj.State to be x [k k], the state estimate for
   time k, estimated using measured outputs up to time k. When you then execute the predict
   command with input Us[k], obj.State now stores x [k + 1 k]. The algorithm uses this state
   value as an input to the correct command in the next time step.
• predict then correct — Assume that at time step k, the value of obj.State is x [k − 1 k − 1].
  You also have the measured output y[k] and input Um[k] at the same time step but you have
  Us[k-1] from the previous time step.
   Then you first execute the predict command with input Us[k-1]. The command updates the
   value of obj.State to x [k k − 1]. When you then execute the correct command with input
   arguments y[k] and Um[k], obj.State is updated with x [k k]. The algorithm uses this state
   value as an input to the predict command in the next time step.
                                                                                                    1-993
1   Functions
          Thus, while in both cases the state estimate for time k, x [k k] is the same, if at time k you do not
          have access to the current state transition function inputs Us[k], and instead have Us[k-1], then use
          predict first and then correct.
          For an example of estimating states using the predict and correct commands, see “Estimate
          States Online Using Unscented Kalman Filter” on page 1-987 or “Estimate States Online using
          Particle Filter” on page 1-989.
          See Also
          clone | correct | extendedKalmanFilter | initialize | particleFilter | residual |
          unscentedKalmanFilter
          Topics
          “Nonlinear State Estimation Using Unscented Kalman Filter and Particle Filter”
          “Generate Code for Online State Estimation in MATLAB”
          “What Is Online Estimation?”
          “Extended and Unscented Kalman Filter Algorithms for Online State Estimation”
Introduced in R2016b
1-994
                                                                                        predictOptions
predictOptions
Option set for predict
Syntax
opt = predictOptions
opt = predictOptions(Name,Value)
Description
opt = predictOptions creates the default option set for predict. Use dot notation to modify this
option set. Any options that you do not modify retain their default values.
opt = predictOptions(Name,Value) creates an option set with options specified by one or more
Name,Value pair arguments.
Examples
opt = predictOptions;
opt.OutputOffset = [2;5];
The software subtracts the offset value OutputOffset(i) from the i th output signal before using
the output to predict the model response. The software then adds back these offsets to the predicted
response to give the final response.
opt = predictOptions('InitialCondition','z');
load iddata7 z7
                                                                                               1-995
1   Functions
sys = n4sid(z7,5);
          zA = z7(1:15);
          zB = z7(16:end);
          Suppose that you want to compute the 10-step-ahead prediction of the response of the identified
          system for data zB. For initial conditions, use the signal values in zA as the historical record. That is,
          the input and output values for the time immediately preceding data in zB.
          IO = struct('Input',zA.InputData,'Output',zA.OutputData);
          opt = predictOptions('InitialCondition',IO);
Generate the 10-step-ahead prediction for data zB using the specified initial conditions.
[yp,x0,Predictor] = predict(sys,zB,10,opt);
          yp is the predicted model response, x0 are the initial states corresponding to the predictor model
          Predictor. You can simulate Predictor using x0 as initial conditions to reproduce
          yp.OutputData.
          To understand how the past data is mapped to the initial states of the model, see “Understand Use of
          Historical Data for Model Prediction” on page 1-979.
          Input Arguments
          Name-Value Pair Arguments
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
          Example: predictOptions('InitialCondition','z') specifies zero initial conditions for the
          measured input-output data.
                For nonlinear grey-box models, only those initial states i that are designated as free in the model
                (sys.InitialStates(i).Fixed = false) are estimated. To estimate all the states of the
                model, first specify all the Nx states of the idnlgrey model sys as free.
                for i = 1:Nx
                sys.InitialStates(i).Fixed = false;
                end
                Similarly, to fix all the initial states to values specified in sys.InitialStates, first specify all
                the states as fixed in the sys.InitialStates property of the nonlinear grey-box model.
1-996
                                                                                         predictOptions
• 'd' — Similar to 'e', but absorbs nonzero delays into the model coefficients. The delays are first
  converted to explicit model states, and the initial values of those states are also estimated and
  returned.
       Field      Description
       Input      Input history, specified as a matrix with Nu columns, where Nu is the number of
                  input channels. For time series models, use []. The number of rows must be
                  greater than or equal to the model order.
       Output     Output history, specified as a matrix with Ny columns, where Ny is the number of
                  output channels. The number of rows must be greater than or equal to the model
                  order.
   For an example, see “Use Historical Data to Specify Initial Conditions for Model Prediction” on
   page 1-995.
   For multi-experiment data, configure the initial conditions separately for each experiment by
   specifying InitialCondition as a structure array with Ne elements. To specify the same initial
   conditions for all experiments, use a single structure.
   The software uses data2state to map the historical data to states. If your model is not idss,
   idgrey, idnlgrey, or idnlarx, the software first converts the model to its state-space
   representation and then maps the data to states. If conversion of your model to idss is not
   possible, the estimated states are returned empty.
• x0obj — Specification object created using idpar. Use this object for discrete-time state-space
  (idss and idgrey) and nonlinear grey-box (idnlgrey) models only. Use x0obj to impose
  constraints on the initial states by fixing their value or specifying minimum or maximum bounds.
Input signal offset for time-domain data, specified as the comma-separated pair consisting of
'InputOffset' and one of the following values:
• [] — No input offsets.
• A column vector of length Nu, where Nu is the number of inputs. The software subtracts the offset
  value InputOffset(i) from the ith input signal before using the input to predict the model
  response.
• Nu-by-Ne matrix — For multi-experiment data, specify InputOffset as an Nu-by-Ne matrix,
  where Ne is the number of experiments. The software subtracts the offset value
  InputOffset(i,j) from the ith input signal of the jth experiment before prediction.
   If you specify a column vector of length Nu, then the offset value InputOffset(i) is subtracted
   from the ith input signal of all the experiments.
                                                                                                1-997
1   Functions
          Output signal offset for time-domain data, specified as the comma-separated pair consisting of
          'OutputOffset' and one of the following values:
          • [] — No output offsets.
          • A column vector of length Ny, where Ny is the number of outputs. The software subtracts the
            offset value OutputOffset(i) from the ith output signal before using the output to predict the
            model response. After prediction, the software adds the offsets to the predicted response to give
            the final predicted response.
          • Ny-by-Ne matrix — For multi-experiment data, specify OutputOffset as an Ny-by-Ne matrix,
            where Ne is the number of experiments. The software subtracts the offset value
            OutputOffset(i,j) from the ith output signal of the jth experiment before prediction.
                If you specify a column vector of length Ny, then the offset value OutputOffset(i) is subtracted
                from the ith output signal of all the experiments.
                After prediction, the software adds the removed offsets to the predicted response to give the final
                predicted response.
          Weight of output for initial condition estimation, specified as the comma-separated pair consisting of
          'OutputWeight' and one of the following values:
          • [] — No weighting is used by the software for initial condition estimation. This option is the same
            as using eye(Ny) for the output weight, where Ny is the number of outputs.
          • 'noise' — The software uses the inverse of the NoiseVariance property of the model as the
            weight.
          • A positive, semidefinite matrix of dimension Ny-by-Ny, where Ny is the number of outputs.
          Output Arguments
          opt — Option set for predict
          predictOptions option set
          See Also
          absorbDelay | idpar | predict
Introduced in R2012a
1-998
                                                                                                present
present
Display model information, including estimated uncertainty
Syntax
present(m)
Description
present(m) displays the linear or nonlinear identified model m and the following information:
• Estimated one standard deviation of the parameters, which gives 68.27% confidence region
• Termination conditions for iterative estimation algorithms
• Status of the model — whether the model was constructed or estimated
• Fit to estimation data
• Akaike's Final Prediction Error (FPE) criterion
• Mean-square error (MSE)
Examples
present(sys)
sys =
Parameterization:
   Number of poles: 2   Number of zeros: 1
   Number of free coefficients: 4
   Use "tfdata", "getpvec", "getcov" for parameters and their uncertainties.
Status:
Termination condition: Near (local) minimum, (norm(g) < tol)..
                                                                                                1-999
1   Functions
          See Also
          frdata | getcov | getpvec | idssdata | polydata | ssdata | tfdata | zpkdata
          Topics
          “Estimation Report”
          “Loss Function and Model Quality Metrics”
1-1000
                                                                                               procest
procest
Estimate process model using time or frequency data
Syntax
sys = procest(data,type)
sys = procest(data,type,'InputDelay',InputDelay)
sys = procest(data,init_sys)
Description
sys = procest(data,type) estimates a process model, sys, using time or frequency-domain
data, data. type defines the structure of sys.
sys = procest(data,init_sys) uses the process model init_sys to configure the initial
parameterization.
sys = procest( ___ ,opt) specifies additional model estimation options. Use opt with any of the
previous syntaxes.
[sys,offset] = procest( ___ ) returns the estimated value of the offset in input signal. Input
offset is automatically estimated when the model contains an integrator, or when you set the
InputOffset estimation option to 'estimate' using procestOptions. Use offset with any of
the previous syntaxes.
Input Arguments
data — Estimation data
iddata | idfrd | frd
Estimation data, specified as an iddata object containing the input and output signal values, for
time-domain estimation. For frequency-domain estimation, data can be one of the following:
                                                                                              1-1001
1   Functions
          Time-series models, which are models that contain no measured inputs, cannot be estimated using
          procest. Use ar, arx, or armax for time-series models instead.
          Process model structure, specified for SISO models as a character vector or string representing an
          acronym for the model structure, such as 'P1D' or 'P2DZ'. The acronym is made up of:
          For MIMO models, use an Ny-by-Nu cell array of character vectors or string array, with one entry for
          each input-output pair. Here Ny is the number of inputs and Nu is the number of outputs.
For information regarding how type affects the structure of a process model, see idproc.
          Input delays, specified as a numeric vector specifying a time delay for each input channel. Specify
          input delays in the time unit stored in the TimeUnit property.
          For a system with Nu inputs, set InputDelay to an Nu-by-1 vector. Each entry of this vector is a
          numerical value that represents the input delay for the corresponding input channel. You can also set
          InputDelay to a scalar value to apply the same delay to all channels.
          System for configuring initial parametrization of sys, specified as an idproc object. You obtain
          init_sys by either performing an estimation using measured data or by direct construction using
          idproc. The software uses the parameters and constraints defined in init_sys as the initial guess
          for estimating sys.
          Use the Structure property of init_sys to configure initial guesses and constraints for Kp, Tp1,
          Tp2, Tp3, Tw, Zeta, Td, and Tz. For example:
1-1002
                                                                                              procest
If opt is not specified, and init_sys was obtained by estimation, then the estimation options from
init_sys.Report.OptionsUsed are used.
Estimation options, specified as an procestOptions option set. The estimation options include:
• Estimation objective
• Handling on initial conditions and disturbance component
• Numerical search method to be used in estimation
Output Arguments
sys — Identified process model
idproc model
Information about the estimation results and options used is stored in the model's Report property.
Report has the following fields:
                           This field is especially useful to view how the initial conditions were
                           handled when the InitialCondition option in the estimation option
                           set is 'auto'.
                                                                                             1-1003
1   Functions
                          Field     Description
                          FitPerc Normalized root mean squared error (NRMSE) measure of
                          ent     how well the response of the model fits the estimation data,
                                  expressed as the percentage fit = 100(1-NRMSE).
                          LossFcn Value of the loss function when the estimation completes.
                          MSE       Mean squared error (MSE) measure of how well the response
                                    of the model fits the estimation data.
                          FPE       Final prediction error for the model.
                          AIC       Raw Akaike Information Criteria (AIC) measure of model
                                    quality.
                          AICc      Small sample-size corrected AIC.
                          nAIC      Normalized AIC.
                          BIC       Bayesian Information Criteria (BIC).
           Parameters     Estimated values of model parameters.
           OptionsUsed    Option set used for estimation. If no custom options were configured,
                          this is a set of default options. See procestOptions for more
                          information.
           RandState      State of the random number stream at the start of estimation. Empty, [],
                          if randomization was not used during estimation. For more information,
                          see rng in the MATLAB documentation.
1-1004
                                                                                   procest
               Field     Description
               Name      Name of the data set.
               Type      Data type. For idnlarx models, this is set to 'Time domain
                         data'.
               Length    Number of data samples.
               Ts        Sample time. This is equivalent to Data.Ts.
               InterSa Input intersample behavior. One of the following values:
               mple
                       • 'zoh' — Zero-order hold maintains a piecewise-constant
                          input signal between samples.
                         • 'foh' — First-order hold maintains a piecewise-linear
                           input signal between samples.
                         • 'bl' — Band-limited behavior specifies that the
                           continuous-time input signal has zero power above the
                           Nyquist frequency.
                                                                                  1-1005
1   Functions
                                      Field     Description
                                      WhyStop Reason for terminating the numerical search.
                                      Iterati Number of search iterations performed by the estimation
                                      ons     algorithm.
                                      FirstOr ∞-norm of the gradient search vector when the search
                                      derOpti algorithm terminates.
                                      mality
                                      FcnCoun Number of times the objective function was called.
                                      t
                                      UpdateN Norm of the gradient search vector in the last iteration.
                                      orm     Omitted when the search method is 'lsqnonlin' or
                                              'fmincon'.
                                      LastImp Criterion improvement in the last iteration, expressed as a
                                      rovemen percentage. Omitted when the search method is
                                      t       'lsqnonlin' or 'fmincon'.
                                      Algorit Algorithm used by 'lsqnonlin' or 'fmincon' search
                                      hm      method. Omitted when other search methods are used.
          Estimated value of input offset, returned as a vector. When data has multiple experiments, offset is
          a matrix where each column corresponds to an experiment.
Examples
          load iddemo_heatexchanger_data;
          data = iddata(pt,ct,Ts);
          data.InputName = '\Delta CTemp';
          data.InputUnit = 'C';
          data.OutputName = '\Delta PTemp';
          data.OutputUnit = 'C';
          data.TimeUnit   = 'minutes';
1-1006
                                   procest
type = 'P1D';
sysP1D = procest(data,type);
compare(data,sysP1D)
figure
resid(data,sysP1D);
                                   1-1007
1   Functions
          The figure shows that the residuals are correlated. To account for that, add a first order ARMA
          disturbance component to the process model.
          opt = procestOptions('DisturbanceModel','ARMA1');
          sysP1D_noise = procest(data,'p1d',opt);
compare(data,sysP1D,sysP1D_noise)
1-1008
                            procest
figure
resid(data,sysP1D_noise);
                            1-1009
1   Functions
Assume that gain is known with a higher degree of confidence than other model parameters.
Load data.
          m = idproc('P3UZ','K',7.5,'Tw',0.25,'Zeta',0.3,'Tp3',20,'Tz',0.02);
          m1 = procest(z1,m);
          opt = procestOptions;
          opt.Regularization.Nominal = 'model';
          opt.Regularization.R = [100;1;1;1;1];
          opt.Regularization.Lambda = 0.1;
          m2 = procest(z1,m,opt);
1-1010
                                                                                             procest
compare(z1,m1,m2);
Regularization helps steer the estimation process towards the correct parameter values.
Estimate a process model after specifying initial guesses for parameter values and bounding them.
type = 'P2UZD';
init_sys = idproc(type);
init_sys.Structure.Kp.Value =      1;
init_sys.Structure.Tw.Value =      2;
init_sys.Structure.Zeta.Value      = 0.1;
init_sys.Structure.Td.Value =      0;
init_sys.Structure.Tz.Value =      1;
init_sys.Structure.Kp.Minimum      = 0.1;
                                                                                            1-1011
1   Functions
          init_sys.Structure.Kp.Maximum = 10;
          init_sys.Structure.Td.Maximum = 1;
          init_sys.Structure.Tz.Maximum = 10;
          opt = procestOptions('Display','full','InitialCondition','Zero');
          opt.SearchMethod = 'lm';
          opt.SearchOptions.MaxIterations = 100;
sys = procest(data,init_sys,opt);
          Since the 'Display' option is specified as 'full', the estimation progress is displayed in a
          separate Plant Identification Progress window.
compare(data,sys,init_sys);
1-1012
                                                                                                    procest
load iddata1 z1
load iddata2 z2
data = [z1 z2(1:300)];
data is a data set with 2 inputs and 2 outputs. The first input affects only the first output. Similarly,
the second input affects only the second output.
In the estimated process model, the cross terms, modeling the effect of the first input on the second
output and vice versa, should be negligible. If higher orders are assigned to those dynamics, their
estimations show a high level of uncertainty.
type = 'P2UZ';
sys = procest(data,type);
The type variable denotes a model with complex-conjugate pair of poles, a zero, and a delay.
w = linspace(0,20*pi,100);
h = bodeplot(sys,w);
showConfidence(h);
                                                                                                   1-1013
1   Functions
          load iddata1
          [sys,offset] = procest(z1,'P1DI');
          offset
offset = 0.0412
          Extended Capabilities
          Automatic Parallel Support
          Accelerate code by automatically running computation in parallel using Parallel Computing Toolbox™.
          Parallel computing support is available for estimation using the lsqnonlin search method (requires
          Optimization Toolbox). To enable parallel computing, use procestOptions, set SearchMethod to
          'lsqnonlin', and set SearchOptions.Advanced.UseParallel to true.
For example:
          opt = procestOptions;
          opt.SearchMethod = 'lsqnonlin';
          opt.SearchOptions.Advanced.UseParallel = true;
          See Also
          ar | arx | bj | idproc | oe | polyest | procestOptions | ssest | tfest
          Topics
          “What Is a Process Model?”
          “Regularized Estimates of Model Parameters”
Introduced in R2012a
1-1014
                                                                                              procestOptions
procestOptions
Options set for procest
Syntax
opt = procestOptions
opt = procestOptions(Name,Value)
Description
opt = procestOptions creates the default options set for procest.
opt = procestOptions(Name,Value) creates an option set with the options specified by one or
more Name,Value pair arguments.
Input Arguments
Name-Value Pair Arguments
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Handling of initial conditions during estimation, specified as one of the following values:
y = G(s)u + H(s)e
H(s) is stored in the NoiseTF property of the numerator and denominator of idproc models.
                                                                                                   1-1015
1   Functions
                 1 + cs
                 1 + ds
          • 'ARMA2' — The software estimates H as a second-order ARMA model
                 1 + c1s + c2s2
                 1 + d1s + d2s2
          • 'fixed' — The software fixes the value of the NoiseTF property of the idproc model as the
            value of H.
          Error to be minimized in the loss function during estimation, specified as the comma-separated pair
          consisting of 'Focus' and one of the following values:
          • 'prediction' — The one-step ahead prediction error between measured and predicted outputs
            is minimized during estimation. As a result, the estimation focuses on producing a good predictor
            model.
          • 'simulation' — The simulation error between measured and simulated outputs is minimized
            during estimation. As a result, the estimation focuses on making a good fit for simulation of model
            response with the current inputs.
          The Focus option can be interpreted as a weighting filter in the loss function. For more information,
          see “Loss Function and Model Quality Metrics”.
          Weighting prefilter applied to the loss function to be minimized during estimation. To understand the
          effect of WeightingFilter on the loss function, see “Loss Function and Model Quality Metrics”.
                Passbands are expressed in rad/TimeUnit for time-domain data and in FrequencyUnit for
                frequency-domain data, where TimeUnit and FrequencyUnit are the time and frequency units
                of the estimation data.
          • SISO filter — Specify a single-input-single-output (SISO) linear filter in one of the following ways:
1-1016
                                                                                         procestOptions
      This option calculates the weighting function as a product of the filter and the input spectrum
      to estimate the transfer function.
• Weighting vector — Applicable for frequency-domain data only. Specify a column vector of
  weights. This vector must have the same length as the frequency vector of the data set,
  Data.Frequency. Each input and output response in the data is multiplied by the corresponding
  weight at that frequency.
If EstimateCovariance is true, then use getcov to fetch the covariance matrix from the
estimated model.
Specify whether to display the estimation progress, specified as one of the following values:
• 'on' — Information on model structure and estimation results are displayed in a progress-viewer
  window.
• 'off' — No progress or results information is displayed.
Removal of offset from time-domain input data during estimation, specified as one of the following
values:
   For example, the software estimates the input offset for a model that contains an integrator.
• A column vector of length Nu, where Nu is the number of inputs.
   Each entry specified by InputOffset is subtracted from the corresponding input data.
• A parameter object, constructed using param.Continuous, that imposes constraints on how the
  software estimates the input offset.
                                                                                                1-1017
1   Functions
                For example, create a parameter object for a 2-input model estimation. Specify the first input
                offset as fixed to zero and the second input offset as an estimation parameter.
                opt = procestOptions;
                u0 = param.Continuous('u0',[0;NaN]);
                u0.Free(1) = false;
                opt.Inputoffset = u0;
          Removal of offset from time-domain output data during estimation, specified as the comma-separated
          pair consisting of 'OutputOffset' and one of the following:
Each entry specified by OutputOffset is subtracted from the corresponding output data.
Weighting of prediction errors in multi-output estimations, specified as one of the following values:
          • 'noise' — Minimize det(E′ * E/N), where E represents the prediction error and N is the number
            of data samples. This choice is optimal in a statistical sense and leads to maximum likelihood
            estimates if nothing is known about the variance of the noise. It uses the inverse of the estimated
            noise variance as the weighting function.
                • E is the matrix of prediction errors, with one column for each output, and W is the positive
                  semidefinite symmetric matrix of size equal to the number of outputs. Use W to specify the
                  relative importance of outputs in multiple-output models, or the reliability of corresponding
                  data.
                • N is the number of data samples.
          • [] — The software chooses between the 'noise' or using the identity matrix for W.
          Options for regularized estimation of model parameters. For more information on regularization, see
          “Regularized Estimates of Model Parameters”.
1-1018
                                                                                          procestOptions
Specify a positive scalar to add the regularization term to the estimation cost.
   Default: 0
• R — Weighting matrix.
   Specify a vector of nonnegative numbers or a square positive semi-definite matrix. The length
   must be equal to the number of free parameters of the model.
   For black-box models, using the default value is recommended. For structured and grey-box
   models, you can also specify a vector of np positive numbers such that each entry denotes the
   confidence in the value of the associated parameter.
   The default value of 1 implies a value of eye(npfree), where npfree is the number of free
   parameters.
   Default: 1
• Nominal — The nominal value towards which the free parameters are pulled during estimation.
   The default value of zero implies that the parameter values are pulled towards zero. If you are
   refining a model, you can set the value to 'model' to pull the parameters towards the parameter
   values of the initial model. The initial parameter values must be finite for this setting to work.
Default: 0
Numerical search method used for iterative parameter estimation, specified as the comma-separated
pair consisting of 'SearchMethod' and one of the following:
• 'auto' — A combination of the line search algorithms, 'gn', 'lm', 'gna', and 'grad' methods
  is tried in sequence at each iteration. The first descent direction leading to a reduction in
  estimation cost is used.
• 'gn' — Subspace Gauss-Newton least squares search. Singular values of the Jacobian matrix less
  than GnPinvConstant*eps*max(size(J))*norm(J) are discarded when computing the
  search direction. J is the Jacobian matrix. The Hessian matrix is approximated as JTJ. If there is no
  improvement in this direction, the function tries the gradient direction.
• 'gna' — Adaptive subspace Gauss-Newton search. Eigenvalues less than gamma*max(sv) of the
  Hessian are ignored, where sv contains the singular values of the Hessian. The Gauss-Newton
  direction is computed in the remaining subspace. gamma has the initial value
  InitialGnaTolerance (see Advanced in 'SearchOptions' for more information). This value
  is increased by the factor LMStep each time the search fails to find a lower value of the criterion
  in fewer than five bisections. This value is decreased by the factor 2*LMStep each time a search is
  successful without any bisections.
• 'lm' — Levenberg-Marquardt least squares search, where the next parameter value is -pinv(H
  +d*I)*grad from the previous one. H is the Hessian, I is the identity matrix, and grad is the
  gradient. d is a number that is increased until a lower value of the criterion is found.
• 'grad' — Steepest descent least squares search.
                                                                                                1-1019
1   Functions
                • Constrained minimization problems when there are bounds imposed on the model parameters.
                • Model structures where the loss function is a nonlinear or non smooth function of the
                  parameters.
                • Multi-output model estimation. A determinant loss function is minimized by default for multi-
                  output model estimation. fmincon algorithms are able to minimize such loss functions directly.
                  The other search methods such as 'lm' and 'gn' minimize the determinant loss function by
                  alternately estimating the noise variance and reducing the loss value for a given noise variance
                  value. Hence, the fmincon algorithms can offer better efficiency and accuracy for multi-output
                  model estimations.
          Option set for the search algorithm, specified as the comma-separated pair consisting of
          'SearchOptions' and a search option set with fields that depend on the value of SearchMethod.
1-1020
                                                                                    procestOptions
                                                                                            1-1021
1   Functions
1-1022
                                                                                        procestOptions
                                                                                             1-1023
1   Functions
                                      • 'sqp' — Sequential
                                        quadratic programming
                                        algorithm. The algorithm
                                        satisfies bounds at all
                                        iterations, and it can recover
                                        from NaN or Inf results. It is
                                        not a large-scale algorithm.
                                        For more information, see
                                        “Large-Scale vs. Medium-
                                        Scale Algorithms”
                                        (Optimization Toolbox).
                                      • 'trust-region-
                                        reflective' — Subspace
                                        trust-region method based
                                        on the interior-reflective
                                        Newton method. It is a large-
                                        scale algorithm.
                                      • 'interior-point' —
                                        Large-scale algorithm that
                                        requires Optimization
                                        Toolbox software. The
                                        algorithm satisfies bounds at
                                        all iterations, and it can
                                        recover from NaN or Inf
                                        results.
                                      • 'active-set' — Requires
                                        Optimization Toolbox
                                        software. The algorithm can
                                        take large steps, which adds
                                        speed. It is not a large-scale
                                        algorithm.
1-1024
                                                                                         procestOptions
• ErrorThreshold — Specifies when to adjust the weight of large errors from quadratic to linear.
   Errors larger than ErrorThreshold times the estimated standard deviation have a linear weight
   in the loss function. The standard deviation is estimated robustly as the median of the absolute
   deviations from the median of the prediction errors, divided by 0.7. For more information on
   robust norm choices, see section 15.2 of [1].
   Default: 0
• MaxSize — Specifies the maximum number of elements in a segment when input-output data is
  split into segments.
   Default: 250000
• StabilityThreshold — Specifies thresholds for stability tests.
   • s — Specifies the location of the right-most pole to test the stability of continuous-time models.
     A model is considered stable when its right-most pole is to the left of s.
      Default: 0
   • z — Specifies the maximum distance of all poles from the origin to test stability of discrete-
     time models. A model is considered stable if all poles are within the distance z from the origin.
                                                                                               1-1025
1   Functions
                   Default: 1+sqrt(eps)
          • AutoInitThreshold — Specifies when to automatically estimate the initial condition.
                  yp, z − ymeas
                                > AutoInitThreshold
                  yp, e − ymeas
Default: 1.05
          Output Arguments
          opt — Option set for procest
          procestOptions option set
Examples
opt = procestOptions;
Create an option set for procest setting Focus to 'simulation' and turning on the Display.
opt = procestOptions('Focus','simulation','Display','on');
          opt = procestOptions;
          opt.Focus = 'simulation';
          opt.Display = 'on';
          Compatibility Considerations
          Renaming of Estimation and Analysis Options
          The names of some estimation and analysis options were changed in R2018a. Prior names still work.
          For details, see the R2018a release note “Renaming of Estimation and Analysis Options”.
1-1026
                                                                                         procestOptions
References
[1] Ljung, L. System Identification: Theory for the User. Upper Saddle River, NJ: Prentice-Hall PTR,
        1999.
[2] Wills, Adrian, B. Ninness, and S. Gibson. “On Gradient-Based Search for Multivariable System
         Estimates”. Proceedings of the 16th IFAC World Congress, Prague, Czech Republic, July 3–8,
         2005. Oxford, UK: Elsevier Ltd., 2005.
See Also
idfilt | idproc | procest
Topics
“Loss Function and Model Quality Metrics”
Introduced in R2012a
                                                                                               1-1027
1   Functions
          pwlinear
          Create a piecewise-linear nonlinearity estimator object
          Syntax
          NL = pwlinear
          NL = pwlinear(Name,Value)
          Description
          NL = pwlinear creates a default piecewise-linear nonlinearity estimator object with 10 break points
          for estimating Hammerstein-Wiener models. The value of the nonlinearity at the break points are set
          to []. The initial value of the nonlinearity is determined from the estimation data range during
          estimation using nlhw. Use dot notation to customize the object properties, if needed.
          Object Description
          pwlinear is an object that stores the piecewise-linear nonlinearity estimator for estimating
          Hammerstein-Wiener models.
          Use pwlinear to define a nonlinear function y = F(x, θ), where y and x are scalars, and θ represents
          the parameters specifying the number of break points and the value of nonlinearity at the break
          points.
          F is also linear to the left and right of the extreme breakpoints. The slope of these extensions is a
          function of xi and yi breakpoints. The breakpoints are ordered by ascending x-values, which is
          important when you set a specific breakpoint to a different value.
          There are minor difference between the breakpoint values you set and the values stored in the object
          because the toolbox has a different internal representation of breakpoints.
          For example, in the following plot, the breakpoints are xk = [-2,1,4] and the corresponding
          nonlinearity values are yk = [4,3,5].
1-1028
                                                                                     pwlinear
The value F(x) is computed by evaluate(NL,x), where NL is the pwlinear object. When using
evaluate, the break points have to be initialized manually.
Examples
NL = pwlinear;
NL.NumberOfUnits = 5;
load twotankdata;
z = iddata(y,u,0.2,'Name','Two tank system');
z1 = z(1:1000);
                                                                                     1-1029
1   Functions
          Since BreakPoints is specified as a vector, the specified vector is interpreted as the x-values of the
          break points. The y-values of the break points are set to 0, and are determined during model
          estimation.
          Input Arguments
          Name-Value Pair Arguments
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
          Use Name,Value arguments to specify additional properties on page 1-550 of pwlinear nonlinearity.
          For example, NL= pwlinear('NumberofUnits',5) creates a piecewise-linear nonlinearity
          estimator object with 5 breakpoints.
          Properties
          pwlinear object properties include:
NumberofUnits
Default: 10
BreakPoints
          Break points, xk, and the corresponding nonlinearity values at the breakpoints, yk, specified as one of
          the following:
          • 2-by-n matrix — The x and y values for each of the n break points are specified as [x1,x2, ...., xn;y1,
            y2, ..., yn].
          • 1-by-n vector — The specified vector is interpreted as the x values of the break points: x1,x2, ...., xn.
            All the y values of the break points are set to 0.
          When the nonlinearity object is created, the breakpoints are ordered by ascending x-values. This is
          important to consider if you set a specific breakpoint to a different value after creating the object.
Default: []
          Output Arguments
          NL — Piecewise-linear nonlinearity estimator object
          pwlinear object
1-1030
                                                                                 pwlinear
See Also
nlhw
Introduced in R2007a
                                                                                 1-1031
1   Functions
          pzmap
          Pole-zero plot of dynamic system
          Syntax
          pzmap(sys)
          pzmap(sys1,sys2,...,sysN)
[p,z] = pzmap(sys)
          Description
          pzmap(sys) creates a pole-zero plot of the continuous or discrete-time dynamic system model sys. x
          and o indicates the poles and zeros respectively, as shown in the following figure.
From the figure above, an open-loop linear time-invariant system is stable if:
          • In continuous-time, all the poles on the complex s-plane must be in the left-half plane (blue region)
            to ensure stability. The system is marginally stable if distinct poles lie on the imaginary axis, that
            is, the real parts of the poles are zero.
          • In discrete-time, all the poles in the complex z-plane must lie inside the unit circle (blue region).
            The system is marginally stable if it has one or more poles lying on the unit circle.
          pzmap(sys1,sys2,...,sysN) creates the pole-zero plot of multiple models on a single figure. The
          models can have different numbers of inputs and outputs and can be a mix of continuous and discrete
          systems. For SISO systems, pzmap plots the system poles and zeros. For MIMO systems, pzmap plots
          the system poles and transmission zeros.
          [p,z] = pzmap(sys) returns the system poles and transmission zeros as column vectors p and z.
          The pole-zero plot is not displayed on the screen.
Examples
Plot the poles and zeros of the continuous-time system represented by the following transfer function:
                       2s2 + 5s + 1
                Hs =                .
                       s2 + 3s + 5
1-1032
                                                                                                 pzmap
Turning on the grid displays lines of constant damping ratio (zeta) and lines of constant natural
frequency (wn). This system has two real zeros, marked by o on the plot. The system also has a pair of
complex poles, marked by x.
Plot the pole-zero map of a discrete time identified state-space (idss) model. In practice you can
obtain an idss model by estimation based on input-output measurements of a system. For this
example, create one from state-space data.
pzmap(sys)
                                                                                               1-1033
1   Functions
          load('tfArray.mat','sys');
          size(sys)
          Plot the poles and zeros of each model in the array with distinct colors. For this example, use red for
          the first model, green for the second and blue for the third model in the array.
          pzmap(sys(:,:,1),'r',sys(:,:,2),'g',sys(:,:,3),'b')
          sgrid
1-1034
                                                                                                 pzmap
sgrid plots lines of constant damping ratio and natural frequency in the s-plane of the pole-zero plot.
Use pzmap to calculate the poles and zeros of the following transfer function:
sys = tf([4.2,0.25,-0.004],[1,9.6,17]);
[p,z] = pzmap(sys)
p = 2×1
   -7.2576
   -2.3424
z = 2×1
   -0.0726
    0.0131
                                                                                               1-1035
1   Functions
          This example uses a model of a building with eight floors, each with three degrees of freedom: two
          displacements and one rotation. The I/O relationship for any one of these displacements is
          represented as a 48-state model, where each state represents a displacement or its rate of change
          (velocity).
          load('building.mat');
          size(G)
pzmap(G)
          From the plot, observe that there are numerous near-canceling pole-zero pairs that could be
          potentially eliminated to simplify the model, with no effect on the overall model response. pzmap is
          useful to visually identify such near-canceling pole-zero pairs to perform pole-zero simplification.
1-1036
                                                                                                  pzmap
Input Arguments
sys — Dynamic system
dynamic system model | model array
Dynamic system, specified as a dynamic system model or model array. Dynamic systems that you can
use include continuous-time or discrete-time numeric LTI models such as tf, zpk, or ss models.
If sys is an array of models, pzmap plots all the poles and zeros of every model in the array on the
same plot.
Output Arguments
p — Poles of the system
column vector
Poles of the system, returned as a column vector, in order of its increasing natural frequency. p is the
same as the output of pole(sys), except for the order.
Transmission zeros of the system, returned as a column vector. z is the same as the output of
tzero(sys).
Tips
• Use the functions sgrid or zgrid to plot lines of constant damping ratio and natural frequency in
  the s- or z-plane on the pole-zero plot.
• For MIMO models, pzmap displays all system poles and transmission zeros on a single plot. To
  map poles and zeros for individual I/O pairs, use iopzmap.
• For additional options to customize the appearance of the pole-zero plot, use pzplot.
See Also
damp | dsort | esort | iopzmap | pole | pzplot | rlocus | sgrid | zero | zgrid
                                                                                                 1-1037
1   Functions
          pzoptions
          Create list of pole/zero plot options
          Syntax
          P = pzoptions
          P = pzoption('cstprefs')
          Description
          P = pzoptions returns a list of available options for pole/zero plots (pole/zero, input-output pole/
          zero and root locus) with default values set.. You can use these options to customize the pole/zero plot
          appearance from the command line.
          P = pzoption('cstprefs') initializes the plot options with the options you selected in the
          Control System and System Identification Toolbox Preferences Editor. For more information about the
          editor, see “Toolbox Preferences Editor”.
           Option                                             Description
           Title, XLabel, YLabel                              Label text and style
           TickLabel                                          Tick label style
           Grid                                               Show or hide the grid, specified as one of the
                                                              following values: 'off' | 'on'
                                                              Default: 'off'
           GridColor                                          Color of the grid lines, specified as one of the
                                                              following: Vector of RGB values in the range
                                                              [0,1]| character vector of color name |'none'.
                                                              For example, for yellow color, specify as one of
                                                              the following: [1 1 0], 'yellow', or 'y'.
                                                              Default: [0.15,0.15,0.15]
           XlimMode, YlimMode                                 Limit modes
           Xlim, Ylim                                         Axes limits
           IOGrouping                                         Grouping of input-output pairs, specified as one
                                                              of the following values: 'none'
                                                              |'inputs'|'outputs'|'all'
                                                              Default: 'none'
           InputLabels, OutputLabels                          Input and output label styles
           InputVisible, OutputVisible                        Visibility of input and output channels
1-1038
                                                      pzoptions
Option      Description
FreqUnits   Frequency units, specified as one of the following
            values:
            • 'Hz'
            • 'rad/second'
            • 'rpm'
            • 'kHz'
            • 'MHz'
            • 'GHz'
            • 'rad/nanosecond'
            • 'rad/microsecond'
            • 'rad/millisecond'
            • 'rad/minute'
            • 'rad/hour'
            • 'rad/day'
            • 'rad/week'
            • 'rad/month'
            • 'rad/year'
            • 'cycles/nanosecond'
            • 'cycles/microsecond'
            • 'cycles/millisecond'
            • 'cycles/hour'
            • 'cycles/day'
            • 'cycles/week'
            • 'cycles/month'
            • 'cycles/year'
Default: 'rad/s'
                                                       1-1039
1   Functions
           Option                                              Description
           TimeUnits                                           Time units, specified as one of the following
                                                               values:
                                                               • 'nanoseconds'
                                                               • 'microseconds'
                                                               • 'milliseconds'
                                                               • 'seconds'
                                                               • 'minutes'
                                                               • 'hours'
                                                               • 'days'
                                                               • 'weeks'
                                                               • 'months'
                                                               • 'years'
Default: 'seconds'
Examples
opt = pzoptions;
opt.Grid = 'on';
Use the specified options to plot the root locus of a transfer function.
h = rlocusplot(tf(1,[1,.2,1,0]),opt);
1-1040
                                                          pzoptions
See Also
getoptions | iopzplot | pzplot | setoptions
Introduced in R2012a
                                                          1-1041
1   Functions
          pzplot
          Pole-zero plot of dynamic system model with plot customization options
          Syntax
          h = pzplot(sys)
          pzplot(sys)
          pzplot(sys1,sys2,...,sysN)
          pzplot(ax,...)
          pzplot(...,plotoptions)
          Description
          h = pzplot(sys) plots the poles and transmission zeros of the dynamic system model sys and
          returns the plot handle h to the plot. Use this function to generate a pole-zero map with customizable
          plot options such as FreqUnits, TimeUnits, and IOGrouping. For more information about using
          and interpreting pole-zero maps, see pzmap.
          pzplot(sys) plots the poles and transmission zeros of the dynamic system model sys. x and o
          indicates poles and zeros respectively.
pzplot(ax,...) plots into the axes specified by ax instead of the current axis gca.
          pzplot(...,plotoptions) plots the poles and transmission zeros with the options specified in
          plotoptions. For more information on the ways to change properties of your plots, see “Ways to
          Customize Plots” (Control System Toolbox).
Examples
Plot the poles and zeros of the continuous-time system represented by the following transfer function:
                          2s2 + 5s + 1
                sys s =                .
                          s2 + 3s + 5
1-1042
                                                                                                pzplot
Turning on the grid displays lines of constant damping ratio (zeta) and lines of constant natural
frequency (wn). This system has two real zeros, marked by o on the plot. The system also has a pair of
complex poles, marked by x.
Change the color of the plot title. To do so, use the plot handle, h.
p = getoptions(h);
p.Title.Color = [1,0,0];
setoptions(h,p);
                                                                                              1-1043
1   Functions
          load('tfArrayMargin.mat','sys');
          size(sys)
          Plot the poles and zeros of the model array. Define the colors for each model. For this example, use
          red for the first model, green for the second and blue for the third model in the array.
pzplot(sys(:,:,1),'r',sys(:,:,2),'g',sys(:,:,3),'b');
1-1044
                                                                                                pzplot
Plot the poles and zeros of the continuous-time system represented by the following transfer function
with a custom option set:
              2s2 + 5s + 1
    sys s =                .
              s2 + 3s + 5
plotoptions = pzoptions;
plotoptions.Grid = 'on';
Use the specified options to create a pole-zero map of the transfer function.
                                                                                              1-1045
1   Functions
          Turning on the grid displays lines of constant damping ratio (zeta) and lines of constant natural
          frequency (wn). This system has two real zeros, marked by o on the plot. The system also has a pair
          of complex poles, marked by x.
          Input Arguments
          sys — Dynamic system
          dynamic system model | model array
          Dynamic system, specified as a SISO or MIMO dynamic system model, or an array of SISO or MIMO
          dynamic system models. Dynamic systems that you can use include continuous-time or discrete-time
          numeric LTI models such as tf, zpk, or ss models.
          If sys is a generalized state-space model genss or an uncertain state-space model uss, pzplot
          returns the poles and transmission of the current or nominal value of sys. If sys is an array of
          models, pzplot plots the poles and zeros of each model in the array on the same diagram.
          ax — Axes handle
          axes object
          Axes handle, specified as an axes object. If you do not specify the axes object, then pzplot uses the
          current axes gca to plot the poles and zeros of the system.
1-1046
                                                                                                     pzplot
Pole-zero plot options, specified as an options object. See pzoptions for a list of available plot
options.
Output Arguments
h — Pole-zero plot options handle
scalar
Pole-zero plot options handle, returned as a scalar. Use h to query and modify properties of your pole-
zero plot. You can use this handle to customize the plot with the getoptions and setoptions
commands.
Tips
• Use sgrid or zgrid to plot lines of constant damping ratio and natural frequency in the s- or z-
  plane.
See Also
getoptions | iopzplot | pzmap | pzoptions | setoptions
Topics
“Ways to Customize Plots” (Control System Toolbox)
                                                                                                 1-1047
1   Functions
          rarmax
          (To be removed) Estimate recursively parameters of ARMAX or ARMA models
          Syntax
          thm = rarmax(z,nn,adm,adg)
[thm,yhat,P,phi,psi] = rarmax(z,nn,adm,adg,th0,P0,phi0,psi0)
          Description
          The parameters of the ARMAX model structure
nn = [na nb nc nk]
where na, nb, and nc are the orders of the ARMAX model, and nk is the delay. Specifically,
          If z represents a time series y and nn = [na nc], rarmax estimates the parameters of an ARMA
          model for y.
A(q)y(t) = C(q)e(t)
Only single-input, single-output models are handled by rarmax. Use rpem for the multiple-input case.
          The estimated parameters are returned in the matrix thm. The kth row of thm contains the
          parameters associated with time k; that is, they are based on the data in the rows up to and including
          row k in z. Each row of thm contains the estimated parameters in the following order:
thm(k,:) = [a1,a2,...,ana,b1,...,bnb,c1,...,cnc]
          yhat is the predicted value of the output, according to the current model; that is, row k of yhat
          contains the predicted value of y(k) based on all past data.
1-1048
                                                                                                   rarmax
The actual algorithm is selected with the two arguments adm and adg. These are described under
rarx.
The input argument th0 contains the initial value of the parameters, a row vector consistent with the
rows of thm. The default value of th0 is all zeros.
The arguments P0 and P are the initial and final values, respectively, of the scaled covariance matrix
of the parameters. See rarx. The default value of P0 is 104 times the unit matrix. The arguments
phi0, psi0, phi, and psi contain initial and final values of the data vector and the gradient vector,
respectively. The sizes of these depend on the chosen model orders. The normal choice of phi0 and
psi0 is to use the outputs from a previous call to rarmax with the same model orders. (This call
could be a dummy call with default input arguments.) The default values of phi0 and psi0 are all
zeros.
Note that the function requires that the delay nk be larger than 0. If you want nk = 0, shift the input
sequence appropriately and use nk = 1.
Examples
Compute and plot, as functions of time, the four parameters in a second-order ARMA model of a time
series given in the vector y. The forgetting factor algorithm with a forgetting factor of 0.98 is applied.
Algorithms
The general recursive prediction error algorithm (11.44), (11.47) through (11.49) of Ljung (1999) is
implemented. See “Recursive Algorithms for Online Parameter Estimation” for more information.
See Also
nkshift | recursiveARMA | recursiveARMAX | rpem | rplr
Topics
“Recursive Algorithms for Online Parameter Estimation”
                                                                                                  1-1049
1   Functions
          rarx
          (To be removed) Estimate parameters of ARX or AR models recursively
Note rarx will be removed in a future release. Use recursiveAR or recursiveARX instead.
          Syntax
          thm = rarx(z,nn,adm,adg)
          [thm,yhat,P,phi] = rarx(z,nn,adm,adg,th0,P0,phi0)
          Description
          thm = rarx(z,nn,adm,adg) estimates the parameters thm of single-output ARX model from input-
          output data z and model orders nn using the algorithm specified by adm and adg. If z is a time series
          y and nn = na, rarx estimates the parameters of a single-output AR model.
          Input Arguments
          z
                Name of the matrix iddata object that represents the input-output data or a matrix z = [y u],
                where y and u are column vectors.
For multiple-input models, the u matrix contains each input as a column vector:
          nn
                For input-output models, specifies the structure of the ARX model as:
nn = [na nb nk]
where na and nb are the orders of the ARX model, and nk is the delay.
                For multiple-input models, nb and nk are row vectors that define orders and delays for each
                input.
                Note The delay nk must be larger than 0. If you want nk = 0, shift the input sequence
                appropriately and use nk = 1 (see nkshift).
1-1050
                                                                                                    rarx
     adm ='ug' and adg = gam specify the unnormalized gradient algorithm with gain gamma =
     gam. This algorithm is also known as the normalized least mean squares (LMS).
     adm ='ng' and adg = gam specify the normalized gradient or normalized least mean squares
     (NLMS) algorithm. In these cases, P is not applicable.
     adm ='kf' and adg =R1 specify the Kalman filter based algorithm with R2=1 and R1 = R1. If the
     variance of the innovations e(t) is not unity but R2; then R2* P is the covariance matrix of the
     parameter estimates, while R1 = R1 /R2 is the covariance matrix of the parameter changes.
th0
     Initial value of the parameters in a row vector, consistent with the rows of thm.
φ(t) = [y(t–1),...,y(t–na),u(t–1),...,u(t–nb–nk+1)]
     If z = [y(1),u(1); ... ;y(N),u(N)], phi0 = φ(1) and phi = φ(N). For online use of rarx,
     use phi0, th0, and P0 as the previous outputs phi, thm (last row), and P.
Output Arguments
thm
     Estimated parameters of the model. The kth row of thm contains the parameters associated with
     time k; that is, the estimate parameters are based on the data in rows up to and including row k
     in z. Each row of thm contains the estimated parameters in the following order:
     thm(k,:) = [a1,a2,...,ana,b1,...,bnb]
     For a multiple-input model, the b are grouped by input. For example, the b parameters associated
     with the first input are listed first, and the b parameters associated with the second input are
     listed next.
yhat
     Predicted value of the output, according to the current model; that is, row k of yhat contains the
     predicted value of y(k) based on all past data.
P
     Final values of the scaled covariance matrix of the parameters.
                                                                                                1-1051
1   Functions
          phi
                phi contains the final values of the data vector:
φ(t) = [y(t–1),...,y(t–na),u(t–1),...,u(t–nb–nk+1)]
          Examples
          Adaptive noise canceling: The signal y contains a component that originates from a known signal r.
          Remove this component by recursively estimating the system that relates r to y using a sixth-order
          FIR model and the NLMS algorithm.
          z = [y r];
          [thm,noise] = rarx(z,[0 6 1],'ng',0.1);
          % noise is the adaptive estimate of the noise
          % component of y
          plot(y-noise)
          If this is an online application, you can plot the best estimate of the signal y - noise at the same
          time as the data y and u become available, use the following code:
          phi = zeros(6,1);
          P=1000*eye(6);
          th = zeros(1,6);
          axis([0 100 -2 2]);
          plot(0,0,'*'), hold on
          % Use a while loop
          while ~abort
          [y,r,abort] = readAD(time);
          [th,ns,P,phi] = rarx([y r],'ff',0.98,th,P,phi);
          plot(time,y-ns,'*')
          time = time + Dt
          end
          This example uses a forgetting factor algorithm with a forgetting factor of 0.98. readAD is a function
          that reads the value of an A/D converter at the indicated time instant.
          More About
          ARX Model Structure
A(q)y(t) = B1(q)u1(t–nk1)+...+Bnuunu(t–nknu)+e(t)
1-1052
                                                            rarx
See Also
nkshift | recursiveAR | recursiveARX | rpem | rplr
Topics
“Recursive Algorithms for Online Parameter Estimation”
                                                         1-1053
1   Functions
          rbj
          (To be removed) Estimate recursively parameters of Box-Jenkins models
          Syntax
          thm = rbj(z,nn,adm,adg)
[thm,yhat,P,phi,psi] = rbj(z,nn,adm,adg,th0,P0,phi0,psi0)
          Description
          The parameters of the Box-Jenkins model structure
                         B(q)             C(q)
                y(t) =        u(t − nk) +      e(t)
                         F(q)             D(q)
nn = [nb nc nd nf nk]
where nb, nc, nd, and nf are the orders of the Box-Jenkins model, and nk is the delay. Specifically,
Only single-input, single-output models are handled by rbj. Use rpem for the multiple-input case.
          The estimated parameters are returned in the matrix thm. The kth row of thm contains the
          parameters associated with time k; that is, they are based on the data in the rows up to and including
          row k in z. Each row of thm contains the estimated parameters in the following order.
thm(k,:) = [b1,...,bnb,c1,...,cnc,d1,...,dnd,f1,...,fnf]
          yhat is the predicted value of the output, according to the current model; that is, row k of yhat
          contains the predicted value of y(k) based on all past data.
          The actual algorithm is selected with the two arguments adm and adg. These are described under
          rarx.
1-1054
                                                                                                    rbj
The input argument th0 contains the initial value of the parameters, a row vector consistent with the
rows of thm. The default value of th0 is all zeros.
The arguments P0 and P are the initial and final values, respectively, of the scaled covariance matrix
of the parameters. See rarx. The default value of P0 is 104 times the unit matrix. The arguments
phi0, psi0, phi, and psi contain initial and final values of the data vector and the gradient vector,
respectively. The sizes of these depend on the chosen model orders. The normal choice of phi0 and
psi0 is to use the outputs from a previous call to rbj with the same model orders. (This call could be
a dummy call with default input arguments.) The default values of phi0 and psi0 are all zeros.
Note that the function requires that the delay nk be larger than 0. If you want nk = 0, shift the input
sequence appropriately and use nk = 1.
Algorithms
The general recursive prediction error algorithm (11.44) of Ljung (1999) is implemented. See also
“Recursive Algorithms for Online Parameter Estimation”.
See Also
nkshift | recursiveBJ | rpem | rplr
Topics
“Recursive Algorithms for Online Parameter Estimation”
                                                                                               1-1055
1   Functions
          realdata
          Determine whether iddata is based on real-valued signals
          Syntax
          realdata(data)
          Description
          realdata returns 1 if
Examples
Load data.
load iddata1
zf = fft(z1);
isreal(z1)
ans = 1
isreal(zf)
ans = 0
realdata(zf)
          ans = logical
             1
1-1056
                               realdata
zf = complex(zf);
realdata(zf)
ans = logical
   1
                               1-1057
1   Functions
          recursiveAR
          Create System object for online parameter estimation of AR model
          Syntax
          obj   =   recursiveAR
          obj   =   recursiveAR(na)
          obj   =   recursiveAR(na,A0)
          obj   =   recursiveAR( ___ ,Name,Value)
          Description
          Use the recursiveAR command for parameter estimation with real-time data. If all data necessary
          for estimation is available at once, and you are estimating a time-invariant model, use the offline
          estimation command, ar.
          obj = recursiveAR creates a System object for online parameter estimation of a default single
          output AR model structure on page 1-1067. The default model structure has a polynomial of order 1
          and initial polynomial coefficient value eps.
          After creating the object, use the step command to update model parameter estimates using
          recursive estimation algorithms and real-time data.
          obj = recursiveAR(na,A0) specifies the polynomial order and initial values of the polynomial
          coefficients.
          obj = recursiveAR( ___ ,Name,Value) specifies additional attributes of the AR model structure
          and recursive estimation algorithm using one or more Name,Value pair arguments.
          Object Description
          recursiveAR creates a System object for online parameter estimation of single output AR models
          using a recursive estimation algorithm.
          A System object is a specialized MATLAB object designed specifically for implementing and
          simulating dynamic systems with inputs that change over time. System objects use internal states to
          store past behavior, which is used in the next computational step.
          After you create a System object, you use commands to process data or obtain information from or
          about the object. System objects use a minimum of two commands to process data — a constructor to
          create the object and the step command to update object parameters using real-time data. This
          separation of declaration from execution lets you create multiple, persistent, reusable objects, each
          with different settings.
          You can use the following commands with the online estimation System objects in System
          Identification Toolbox:
1-1058
                                                                                                 recursiveAR
Command                                              Description
step                                                 Update model parameter estimates using
                                                     recursive estimation algorithms and real-time
                                                     data.
Use the recursiveAR command to create an online estimation System object. Then estimate the AR
model parameter, A, and output using the step command with output data y.
[A,EstimatedOutput] = step(obj,y)
Examples
Create a System object™ for online parameter estimation of an AR model using recursive estimation
algorithms.
obj = recursiveAR;
The AR model has a default structure with polynomial of order 1 and initial polynomial coefficient
values, eps.
Load the time-series estimation data. In this example, use a static data set for illustration.
                                                                                                    1-1059
1   Functions
          for i = 1:numel(output)
          [A,EstimatedOutput] = step(obj,output(i));
          end
obj.A
ans = 1×2
1.0000 -0.9592
obj.ParameterCovariance
ans = 1.6204e-04
EstimatedOutput
EstimatedOutput = 0.7830
Create Online Estimation System Object for AR Model With Known Polynomial Order
na = 2;
Create a System object™ for online estimation of an AR model with the specified polynomial order.
obj = recursiveAR(na);
Create Online Estimation System Object for AR Model With Known Initial Parameters
na = 2;
Create a System object for online estimation of AR model with known initial polynomial coefficients.
          A0 = [1 0.5 0.3];
          obj = recursiveAR(na,A0);
obj.InitialParameterCovariance = 0.1;
          InitialParameterCovariance represents the uncertainty in your guess for the initial parameters.
          Typically, the default InitialParameterCovariance (10000) is too large relative to the parameter
1-1060
                                                                                               recursiveAR
values. This results in initial guesses being given less importance during estimation. If you have
confidence in the initial parameter guesses, specify a smaller initial parameter covariance.
Create a System object that uses the normalized gradient algorithm for online parameter estimation
of an AR model.
obj = recursiveAR(2,'EstimationMethod','NormalizedGradient');
Input Arguments
na — Model order
positive integer
Model order of the polynomial A(q) of an AR model on page 1-1067, specified as a positive integer.
Initial value of coefficients of the polynomial A(q), specified as a 1-by-(na+1) row vector of real values
with 1 as the first element. Specify the coefficients in order of ascending powers of q-1.
Specifying as [], uses the default value of eps for the polynomial coefficients.
Note If the initial parameter values are much smaller than InitialParameterCovariance, these
initial values are given less importance during estimation. Specify a smaller initial parameter
covariance if you have high confidence in the initial parameter values. This statement applies only for
infinite-history estimation. Finite-history estimation does not use InitialParameterCovariance.
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Use Name,Value arguments to specify writable properties on page 1-1061 of recursiveAR System
object during object creation. For example, obj =
recursiveAR(2,'EstimationMethod','Gradient') creates a System object to estimate an AR
model using the 'Gradient' recursive estimation algorithm.
Properties
recursiveAR System object properties consist of read-only and writable properties. The writable
properties are tunable and nontunable properties. The nontunable properties cannot be changed
when the object is locked, that is, after you use the step command.
Use Name,Value arguments to specify writable properties of recursiveAR objects during object
creation. After object creation, use dot notation to modify the tunable properties.
                                                                                                  1-1061
1   Functions
          obj = recursiveAR;
          obj.ForgettingFactor = 0.99;
          Estimated coefficients of polynomial A(q), returned as a row vector of real values specified in order of
          ascending powers of q-1.
          A is a read-only property and is initially empty after you create the object. It is populated after you
          use the step command for online parameter estimation.
InitialA
          Initial values for the coefficients of polynomial A(q) of order na, specified as a row vector of length na
          +1, with 1 as the first element. Specify the coefficients in order of ascending powers of q-1.
          If the initial guesses are much smaller than the default InitialParameterCovariance, 10000, the
          initial guesses are given less importance during estimation. In that case, specify a smaller initial
          parameter covariance.
InitialA is a tunable property. You can change it when the object is in a locked state.
Default: [1 eps]
InitialOutputs
The InitialOutputs property provides a means of controlling the initial behavior of the algorithm.
When InitialOutputs is set to 0, the object populates the buffer with zeros.
          If the initial buffer is set to 0 or does not contain enough information, you see a warning message
          during the initial phase of your estimation. The warning should clear after a few cycles. The number
          of cycles it takes for sufficient information to be buffered depends upon the order of your polynomials
          and your input delays. If the warning persists, you should evaluate the content of your signals.
          InitialOutputs is a tunable property. You can change InitialOutputs when the object is in a
          locked state.
Default: 0
ParameterCovariance
1-1062
                                                                                            recursiveAR
The interpretation of P depends on your settings for the History and EstimationMethod
properties.
• If History is Infinite, then your EstimationMethod selection results in one of the following:
ParameterCovariance is a read-only property and is initially empty after you create the object. It is
populated after you use the step command for online parameter estimation.
InitialParameterCovariance
• Real positive scalar, α — Covariance matrix is an N-by-N diagonal matrix, with α as the diagonal
  elements. N is the number of parameters to be estimated.
• Vector of real positive scalars, [α1,...,αN] — Covariance matrix is an N-by-N diagonal matrix, with
  [α1,...,αN] as the diagonal elements.
• N-by-N symmetric positive-definite matrix.
Default: 10000
EstimationMethod
Recursive estimation algorithm used for online estimation of model parameters, specified as one of
the following values:
Forgetting factor and Kalman filter algorithms are more computationally intensive than gradient and
unnormalized gradient methods. However, they have better convergence properties. For information
about these algorithms, see “Recursive Algorithms for Online Parameter Estimation”.
                                                                                               1-1063
1   Functions
These methods all use an infinite data history, and are available only when History is 'Infinite'.
          EstimationMethod is a nontunable property. You cannot change it during execution, that is, after
          the object is locked using the step command.
ForgettingFactor
Forgetting factor, λ, relevant for parameter estimation, specified as a scalar in the range (0,1].
          Suppose that the system remains approximately constant over T0 samples. You can choose λ such
          that:
                         1
                 T0 =
                        1−λ
ForgettingFactor is a tunable property. You can change it when the object is in a locked state.
Default: 1
EnableAdapation
          • true or 1— The step command estimates the parameter values for that time step and updates
            the parameter values.
          • false or 0 — The step command does not update the parameters for that time step and instead
            outputs the last estimated value. You can use this option when your system enters a mode where
            the parameter values do not vary with time.
                Note If you set EnableAdapation to false, you must still execute the step command. Do not
                skip step to keep parameter values constant, because parameter estimation depends on current
                and past I/O measurements. step ensures past I/O data is stored, even when it does not update
                the parameters.
EnableAdapation is a tunable property. You can change it when the object is in a locked state.
Default: true
DataType
1-1064
                                                                                              recursiveAR
Setting DataType to 'single' saves memory, but leads to loss of precision. Specify DataType
based on the precision required by the target processor where you will deploy generated code.
DataType is a nontunable property. It can only be set during object construction using Name,Value
arguments and cannot be changed afterward.
Default: 'double'
ProcessNoiseCovariance
• Real nonnegative scalar, α — Covariance matrix is an N-by-N diagonal matrix, with α as the
  diagonal elements.
• Vector of real nonnegative scalars, [α1,...,αN] — Covariance matrix is an N-by-N diagonal matrix,
  with [α1,...,αN] as the diagonal elements.
• N-by-N symmetric positive semidefinite matrix.
Kalman filter algorithm treats the parameters as states of a dynamic system and estimates these
parameters using a Kalman filter. ProcessNoiseCovariance is the covariance of the process noise
acting on these parameters. Zero values in the noise covariance matrix correspond to estimating
constant coefficients. Values larger than 0 correspond to time-varying parameters. Use large values
for rapidly changing parameters. However, the larger values result in noisier parameter estimates.
ProcessNoiseCovariance is a tunable property. You can change it when the object is in a locked
state.
Default: 0.1
AdaptationGain
Adaptation gain, γ, used in gradient recursive estimation algorithms, specified as a positive scalar.
Specify a large value for AdaptationGain when your measurements have a high signal-to-noise
ratio.
AdaptationGain is a tunable property. You can change it when the object is in a locked state.
Default: 1
NormalizationBias
                                                                                                 1-1065
1   Functions
          The normalized gradient algorithm divides the adaptation gain at each step by the square of the two-
          norm of the gradient vector. If the gradient is close to zero, this can cause jumps in the estimated
          parameters. NormalizationBias is the term introduced in the denominator to prevent these jumps.
          Increase NormalizationBias if you observe jumps in estimated parameters.
NormalizationBias is a tunable property. You can change it when the object is in a locked state.
Default: eps
History
Data history type defining which type of recursive algorithm you use, specified as:
          • 'Infinite' — Use an algorithm that aims to minimize the error between the observed and
            predicted outputs for all time steps from the beginning of the simulation.
          • 'Finite' — Use an algorithm that aims to minimize the error between the observed and
            predicted outputs for a finite number of past time steps.
          Algorithms with infinite history aim to produce parameter estimates that explain all data since the
          start of the simulation. These algorithms still use a fixed amount of memory that does not grow over
          time. The object provides multiple algorithms of the 'Infinite' History type. Specifying this
          option activates the EstimationMethod property with which you specify an algorithm.
          Algorithms with finite history aim to produce parameter estimates that explain only a finite number of
          past data samples. This method is also called sliding-window estimation. The object provides one
          algorithm of the 'Finite' type. Specifying this option activates the WindowLength property that
          sizes the window.
          For more information on recursive estimation methods, see “Recursive Algorithms for Online
          Parameter Estimation”.
          History is a nontunable property. It can be set only during object construction using Name,Value
          arguments and cannot be changed afterward.
Default: 'Infinite'
WindowLength
          Window size determining the number of time samples to use for the sliding-window estimation
          method, specified as a positive integer. Specify WindowLength only when History is Finite.
          Choose a window size that balances estimation performance with computational and memory burden.
          Sizing factors include the number and time variance of the parameters in your model. Always specify
          Window Length in samples, even if you are using frame-based input processing.
          Suitable window length is independent of whether you are using sample-based or frame-based input
          processing (see InputProcessing). However, when using frame-based processing, your window
          length must be greater than or equal to the number of samples (time steps) contained in the frame.
          WindowLength is a nontunable property. It can be set only during object construction using
          Name,Value arguments and cannot be changed afterward.
Default: 200
1-1066
                                                                                           recursiveAR
InputProcessing
Option for sample-based or frame-based input processing, specified as a character vector or string.
Your InputProcessing specification impacts the dimensions for the input and output signals when
using the step command:
[theta,EstimatedOutput] = step(obj,y)
• Sample-based
InputProcessing is a nontunable property. It can be set only during object construction using
Name,Value arguments and cannot be changed afterward.
Default: 'Sample-based'
Output Arguments
obj — System object for online parameter estimation of AR model
recursiveAR System object
System object for online parameter estimation of AR model, returned as a recursiveAR System
object. This object is created using the specified model orders and properties. Use step command to
estimate the coefficients of the AR model polynomials. You can then access the estimated coefficients
and parameter covariance using dot notation. For example, type obj.A to view the estimated A
polynomial coefficients.
More About
AR Model Structure
A(q)y(t) = e(t)
where,
                                −na
    A(q) = 1 + a1q−1 + … + anaq
Here,
• y(t)— Output at time t. Data is a time series that has no input channels and one output channel.
                                                                                              1-1067
1   Functions
          Tips
          • Starting in R2016b, instead of using the step command to update model parameter estimates,
            you can call the System object with input arguments, as if it were a function. For example,
            [A,EstimatedOutput] = step(obj,y) and [A,EstimatedOutput] = obj(y) perform
            equivalent operations.
          Extended Capabilities
          C/C++ Code Generation
          Generate C and C++ code using MATLAB® Coder™.
          See Also
          Recursive Polynomial Model Estimator | ar | clone | isLocked | recursiveARMA |
          recursiveARMAX | recursiveARX | recursiveBJ | recursiveLS | recursiveOE | release |
          reset | step
          Topics
          “Perform Online Parameter Estimation at the Command Line”
          “Validate Online Parameter Estimation at the Command Line”
          “What Is Online Estimation?”
          “Recursive Algorithms for Online Parameter Estimation”
Introduced in R2015b
1-1068
                                                                                          recursiveARMA
recursiveARMA
Create System object for online parameter estimation of ARMA model
Syntax
obj   =   recursiveARMA
obj   =   recursiveARMA(Orders)
obj   =   recursiveARMA(Orders,A0,C0)
obj   =   recursiveARMA( ___ ,Name,Value)
Description
Use recursiveARMA command for parameter estimation with real-time data. If all data necessary for
estimation is available at once, and you are estimating a time-invariant model, use the offline
estimation command, armax.
obj = recursiveARMA creates a System object for online parameter estimation of a default single
output ARMA model structure on page 1-1077. The default model structure has polynomials of order
1 and initial polynomial coefficient values eps.
After creating the object, use the step command to update model parameter estimates using
recursive estimation algorithms and real-time data.
obj = recursiveARMA(Orders,A0,C0) specifies the polynomial orders and initial values of the
polynomial coefficients. Specify initial values to potentially avoid local minima during estimation. If
the initial values are small compared to the default InitialParameterCovariance property value,
and you have confidence in your initial values, also specify a smaller
InitialParameterCovariance.
obj = recursiveARMA( ___ ,Name,Value) specifies additional attributes of the ARMA model
structure and recursive estimation algorithm using one or more Name,Value pair arguments.
Object Description
recursiveARMA creates a System object for online parameter estimation of single output ARMA
models using a recursive estimation algorithm.
A System object is a specialized MATLAB object designed specifically for implementing and
simulating dynamic systems with inputs that change over time. System objects use internal states to
store past behavior, which is used in the next computational step.
After you create a System object, you use commands to process data or obtain information from or
about the object. System objects use a minimum of two commands to process data — a constructor to
create the object and the step command to update object parameters using real-time data. This
separation of declaration from execution lets you create multiple, persistent, reusable objects, each
with different settings.
                                                                                               1-1069
1   Functions
          You can use the following commands with the online estimation System objects in System
          Identification Toolbox:
           Command                                             Description
           step                                                Update model parameter estimates using
                                                               recursive estimation algorithms and real-time
                                                               data.
          Use the recursiveARMA command to create an online estimation System object. Then estimate the
          ARMA model parameters (A and C) and output using the step command with output data y.
[A,C,EstimatedOutput] = step(obj,y)
Examples
obj = recursiveARMA;
          The ARMA model has a default structure with polynomials of order 1 and initial polynomial coefficient
          values, eps.
Load the time-series estimation data. In this example, use a static data set for illustration.
1-1070
                                                                                       recursiveARMA
for i = 1:numel(output)
[A,C,EstimatedOutput] = step(obj,output(i));
end
obj.C
ans = 1×2
1.0000 0.2315
obj.ParameterCovariance
ans = 2×2
10-3 ×
    0.6372     -0.0257
   -0.0257      0.0017
EstimatedOutput
EstimatedOutput = 11.8121
Create Online Estimation System Object for ARMA Model With Known Orders
na = 2;
nc = 1;
Create a System object for online estimation of an ARMA model with the specified orders.
Create Online Estimation System Object for ARMA Model With Known Initial Parameters
na = 2;
nc = 1;
                                                                                            1-1071
1   Functions
          Create a System object for online estimation of ARMA model with known initial polynomial
          coefficients.
          A0 = [1 0.5 0.3];
          C0 = [1 0.7];
          obj = recursiveARMA([na nc],A0,C0);
obj.InitialParameterCovariance = 0.1;
          InitialParameterCovariance represents the uncertainty in your guess for the initial parameters.
          Typically, the default InitialParameterCovariance (10000) is too large relative to the parameter
          values. This results in initial guesses being given less importance during estimation. If you have
          confidence in the initial parameter guesses, specify a smaller initial parameter covariance.
          Create a System object that uses the unnormalized gradient algorithm for online parameter
          estimation of an ARMA model.
          Input Arguments
          Orders — Model orders
          1-by-2 vector of integers
Model orders of an ARMA model on page 1-1077, specified as a 1-by-2 vector of integers, [na nc].
          Initial value of polynomial coefficients, specified as row vectors of real values with elements in order
          of ascending powers of q-1.
          • A0 — Initial guess for the coefficients of the polynomial A(q), specified as a 1-by-(na+1) vector
            with 1 as the first element.
          • C0 — Initial guess for the coefficients of the polynomial C(q), specified as a 1-by-(nc+1) vector
            with 1 as the first element.
                The coefficients in C0 must define a stable discrete-time polynomial with roots within a unit disk.
                For example,
                C0 = [1 0.5 0.5];
                all(abs(roots(C0))<1)
1-1072
                                                                                            recursiveARMA
ans =
Specifying as [], uses the default value of eps for the polynomial coefficients.
Note If the initial guesses are much smaller than the default InitialParameterCovariance,
10000, the initial guesses are given less importance during estimation. In that case, specify a smaller
initial parameter covariance.
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Properties
recursiveARMA System object properties consist of read-only and writable properties. The writable
properties are tunable and nontunable properties. The nontunable properties cannot be changed
when the object is locked, that is, after you use the step command.
Use Name,Value arguments to specify writable properties of recursiveARMA objects during object
creation. After object creation, use dot notation to modify the tunable properties.
obj = recursiveARMA;
obj.ForgettingFactor = 0.99;
Estimated coefficients of polynomial A(q), returned as a row vector of real values specified in order of
ascending powers of q-1.
A is a read-only property and is initially empty after you create the object. It is populated after you
use the step command for online parameter estimation.
Estimated coefficients of polynomial C(q), returned as a vector of real values specified in order of
ascending powers of q-1.
C is a read-only property and is initially empty after you create the object. It is populated after you
use the step command for online parameter estimation.
InitialA
Initial values for the coefficients of polynomial A(q) of order na, specified as a row vector of length na
+1, with 1 as the first element. Specify the coefficients in order of ascending powers of q-1.
                                                                                                  1-1073
1   Functions
          If the initial guesses are much smaller than the default InitialParameterCovariance, 10000, the
          initial guesses are given less importance during estimation. In that case, specify a smaller initial
          parameter covariance.
InitialA is a tunable property. You can change it when the object is in a locked state.
Default: [1 eps]
InitialC
          Initial values for the coefficients of polynomial C(q) of order nc, specified as a row vector of length nc
          +1, with 1 as the first element. Specify the coefficients in order of ascending powers of q-1.
          The coefficients in InitialC must define a stable discrete-time polynomial with roots within a unit
          circle. For example,
          InitialC = [1 0.5 0.5];
          all(abs(roots(InitialC))<1)
ans =
          If the initial guesses are much smaller than the default InitialParameterCovariance, 10000, the
          initial guesses are given less importance during estimation. In that case, specify a smaller initial
          parameter covariance.
InitialC is a tunable property. You can change it when the object is in a locked state.
Default: [1 eps]
ParameterCovariance
          ParameterCovariance is a read-only property and is initially empty after you create the object. It is
          populated after you use the step command for online parameter estimation.
InitialParameterCovariance
          • Real positive scalar, α — Covariance matrix is an N-by-N diagonal matrix, with α as the diagonal
            elements. N is the number of parameters to be estimated.
1-1074
                                                                                            recursiveARMA
• Vector of real positive scalars, [α1,...,αN] — Covariance matrix is an N-by-N diagonal matrix, with
  [α1,...,αN] as the diagonal elements.
• N-by-N symmetric positive-definite matrix.
Default: 10000
EstimationMethod
Recursive estimation algorithm used for online estimation of model parameters, specified as one of
the following values:
Forgetting factor and Kalman filter algorithms are more computationally intensive than gradient and
unnormalized gradient methods. However, they have better convergence properties. For information
about these algorithms, see “Recursive Algorithms for Online Parameter Estimation”.
EstimationMethod is a nontunable property. You cannot change it during execution, that is after
the object is locked using the step command. If you want to deploy code using MATLAB Coder,
EstimationMethod can only be assigned once.
Default: 'ForgettingFactor'
ForgettingFactor
Forgetting factor, λ, relevant for parameter estimation, specified as a scalar in the range (0,1].
Suppose that the system remains approximately constant over T0 samples. You can choose λ such
that:
            1
    T0 =
           1−λ
ForgettingFactor is a tunable property. You can change it when the object is in a locked state.
                                                                                                     1-1075
1   Functions
Default: 1
EnableAdapation
          • true or 1— The step command estimates the parameter values for that time step and updates
            the parameter values.
          • false or 0 — The step command does not update the parameters for that time step and instead
            outputs the last estimated value. You can use this option when your system enters a mode where
            the parameter values do not vary with time.
                Note If you set EnableAdapation to false, you must still execute the step command. Do not
                skip step to keep parameter values constant, because parameter estimation depends on current
                and past I/O measurements. step ensures past I/O data is stored, even when it does not update
                the parameters.
EnableAdapation is a tunable property. You can change it when the object is in a locked state.
Default: true
DataType
          Setting DataType to 'single' saves memory, but leads to loss of precision. Specify DataType
          based on the precision required by the target processor where you will deploy generated code.
          DataType is a nontunable property. It can only be set during object construction using Name,Value
          arguments and cannot be changed afterward.
Default: 'double'
ProcessNoiseCovariance
          • Real nonnegative scalar, α — Covariance matrix is an N-by-N diagonal matrix, with α as the
            diagonal elements.
          • Vector of real nonnegative scalars, [α1,...,αN] — Covariance matrix is an N-by-N diagonal matrix,
            with [α1,...,αN] as the diagonal elements.
          • N-by-N symmetric positive semidefinite matrix.
          Kalman filter algorithm treats the parameters as states of a dynamic system and estimates these
          parameters using a Kalman filter. ProcessNoiseCovariance is the covariance of the process noise
          acting on these parameters. Zero values in the noise covariance matrix correspond to estimating
1-1076
                                                                                           recursiveARMA
constant coefficients. Values larger than 0 correspond to time-varying parameters. Use large values
for rapidly changing parameters. However, the larger values result in noisier parameter estimates.
ProcessNoiseCovariance is a tunable property. You can change it when the object is in a locked
state.
Default: 0.1
AdaptationGain
Adaptation gain, γ, used in gradient recursive estimation algorithms, specified as a positive scalar.
Specify a large value for AdaptationGain when your measurements have a high signal-to-noise
ratio.
AdaptationGain is a tunable property. You can change it when the object is in a locked state.
Default: 1
NormalizationBias
The normalized gradient algorithm divides the adaptation gain at each step by the square of the two-
norm of the gradient vector. If the gradient is close to zero, this can cause jumps in the estimated
parameters. NormalizationBias is the term introduced in the denominator to prevent these jumps.
Increase NormalizationBias if you observe jumps in estimated parameters.
NormalizationBias is a tunable property. You can change it when the object is in a locked state.
Default: eps
Output Arguments
obj — System object for online parameter estimation of ARMA model
recursiveARMA System object
System object for online parameter estimation of ARMA model, returned as a recursiveARMA
System object. This object is created using the specified model orders and properties. Use step
command to estimate the coefficients of the ARMA model polynomials. You can then access the
estimated coefficients and parameter covariance using dot notation. For example, type obj.A to view
the estimated A polynomial coefficients.
More About
ARMA Model Structure
                                                                                                 1-1077
1   Functions
A(q)y(t) = C(q)e(t)
where,
                                              −na
                A(q) = 1 + a1q−1 + … + anaq
                                          −nc
                C(q) = 1 + c1q−1 + … + cncq
Here,
          • y(t)— Output at time t. Data is a time series that has no input channels and one output channel.
          • na — Number of A polynomial coefficients
          • nc — Number of C polynomial coefficients
          • e(t) — White-noise disturbance value at time t
          • q-1 — Time-shift operator
          Tips
          • Starting in R2016b, instead of using the step command to update model parameter estimates,
            you can call the System object with input arguments, as if it were a function. For example,
            [A,C,EstimatedOutput] = step(obj,y) and [A,C,EstimatedOutput] = obj(y)
            perform equivalent operations.
          Extended Capabilities
          C/C++ Code Generation
          Generate C and C++ code using MATLAB® Coder™.
          See Also
          Recursive Polynomial Model Estimator | armax | clone | isLocked | recursiveAR |
          recursiveARMAX | recursiveARX | recursiveBJ | recursiveLS | recursiveOE | release |
          reset | step
          Topics
          “Perform Online Parameter Estimation at the Command Line”
          “Validate Online Parameter Estimation at the Command Line”
          “What Is Online Estimation?”
          “Recursive Algorithms for Online Parameter Estimation”
Introduced in R2015b
1-1078
                                                                                          recursiveARMAX
recursiveARMAX
Create System object for online parameter estimation of ARMAX model
Syntax
obj   =   recursiveARMAX
obj   =   recursiveARMAX(Orders)
obj   =   recursiveARMAX(Orders,A0,B0,C0)
obj   =   recursiveARMAX( ___ ,Name,Value)
Description
Use recursiveARMAX command for parameter estimation with real-time data. If all data necessary
for estimation is available at once, and you are estimating a time-invariant model, use the offline
estimation command, armax.
obj = recursiveARMAX creates a System object for online parameter estimation of default single-
input single-output (SISO) ARMAX model structure on page 1-1088. The default model structure has
polynomials of order 1 and initial polynomial coefficient values eps.
After creating the object, use the step command to update model parameter estimates using
recursive estimation algorithms and real-time data.
obj = recursiveARMAX( ___ ,Name,Value) specifies additional attributes of the ARMAX model
structure and recursive estimation algorithm using one or more Name,Value pair arguments.
Object Description
recursiveARMAX creates a System object for online parameter estimation of SISO ARMAX models
using a recursive estimation algorithm.
A System object is a specialized MATLAB object designed specifically for implementing and
simulating dynamic systems with inputs that change over time. System objects use internal states to
store past behavior, which is used in the next computational step.
After you create a System object, you use commands to process data or obtain information from or
about the object. System objects use a minimum of two commands to process data — a constructor to
create the object and the step command to update object parameters using real-time data. This
separation of declaration from execution lets you create multiple, persistent, reusable objects, each
with different settings.
                                                                                                 1-1079
1   Functions
          You can use the following commands with the online estimation System objects in System
          Identification Toolbox:
           Command                                              Description
           step                                                 Update model parameter estimates using
                                                                recursive estimation algorithms and real-time
                                                                data.
          Use the recursiveARMAX command to create an online estimation System object. Then estimate the
          ARMAX model parameters (A, B, and C) and output using the step command with incoming input and
          output data, u, and y.
[A,B,C,EstimatedOutput] = step(obj,y,u)
Examples
obj = recursiveARMAX;
          The ARMAX model has a default structure with polynomials of order 1 and initial polynomial
          coefficient values, eps.
Load the estimation data. In this example, use a static data set for illustration.
1-1080
                                                                                     recursiveARMAX
ans = 1×2
1.0000 -0.8298
ans = 3×3
EstimatedOutput = -4.5595
Create System Object for ARMAX Model With Known Polynomial Orders
Create a System object for online estimation of ARMAX model with the specified orders and delays.
obj = recursiveARMAX([na nb nc nk]);
Create Online Estimation System Object for ARMAX Model With Known Initial Parameters
                                                                                            1-1081
1   Functions
          nc = 1;
          nk = 1;
          Create a System object for online estimation of ARMAX model with known initial polynomial
          coefficients.
          A0 = [1 0.5];
          B0 = [0 1 1];
          C0 = [1 0.5];
          obj = recursiveARMAX([na nb nc nk],A0,B0,C0);
obj.InitialParameterCovariance = 0.1;
          InitialParameterCovariance represents the uncertainty in your guess for the initial parameters.
          Typically, the default InitialParameterCovariance (10000) is too large relative to the parameter
          values. This results in initial guesses being given less importance during estimation. If you have
          confidence in the initial parameter guesses, specify a smaller initial parameter covariance.
          Create a System object that uses the Kalman filter algorithm for online parameter estimation of an
          ARMAX model.
          The ProcessNoiseCovariance property of obj is applicable only when the Kalman filter
          algorithm is used for estimation.
          Input Arguments
          Orders — Model orders and delays
          1-by-4 vector of integers
          Model orders and delays of an ARMAX model on page 1-1088, specified as a 1-by-4 vector of integers,
          [na nb nc nk].
          • na — Order of the polynomial A(q), specified as a nonnegative integer. na represents the number
            of poles in your system.
          • nb — Order of the polynomial B(q) + 1, specified as a positive integer. nb represents the number
            of zeroes in your system plus 1.
          • nc — Order of the polynomial C(q), specified as a nonnegative integer.
          • nk — Input-output delay, specified as a nonnegative integer. nk is number of input samples that
            occur before the input affects the output. nk is expressed as fixed leading zeros of the B
            polynomial.
1-1082
                                                                                          recursiveARMAX
Initial value of polynomial coefficients, specified as row vectors of real values with elements in order
of ascending powers of q-1.
• A0 — Initial guess for the coefficients of the polynomial A(q), specified as a 1-by-(na+1) vector
  with 1 as the first element.
• B0 — Initial guess for the coefficients of the polynomial B(q), specified as a 1-by-(nb+nk) vector
  with nk leading zeros.
• C0 — Initial guess for the coefficients of the polynomial C(q), specified as a 1-by-(nc+1) vector
  with 1 as the first element.
    The coefficients in C0 must define a stable discrete-time polynomial with roots within a unit disk.
    For example,
    C0 = [1 0.5 0.5];
    all(abs(roots(C0))<1)
ans =
Specifying as [], uses the default value of eps for the polynomial coefficients.
Note If the initial guesses are much smaller than the default InitialParameterCovariance,
10000, the initial guesses are given less importance during estimation. In that case, specify a smaller
initial parameter covariance.
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Properties
recursiveARMAX System object properties consist of read-only and writable properties. The writable
properties are tunable and nontunable properties. The nontunable properties cannot be changed
when the object is locked, that is, after you use the step command.
Estimated coefficients of polynomial A(q), returned as a row vector of real values specified in order of
ascending powers of q-1.
                                                                                                 1-1083
1   Functions
          A is a read-only property and is initially empty after you create the object. It is populated after you
          use the step command for online parameter estimation.
          Estimated coefficients of polynomial B(q), returned as a vector of real values specified in order of
          ascending powers of q-1.
          B is a read-only property and is initially empty after you create the object. It is populated after you
          use the step command for online parameter estimation.
          Estimated coefficients of polynomial C(q), returned as a vector of real values specified in order of
          ascending powers of q-1.
          C is a read-only property and is initially empty after you create the object. It is populated after you
          use the step command for online parameter estimation.
InitialA
          Initial values for the coefficients of polynomial A(q) of order na, specified as a row vector of length na
          +1, with 1 as the first element. Specify the coefficients in order of ascending powers of q-1.
          If the initial guesses are much smaller than the default InitialParameterCovariance, 10000, the
          initial guesses are given less importance during estimation. In that case, specify a smaller initial
          parameter covariance.
InitialA is a tunable property. You can change it when the object is in a locked state.
Default: [1 eps]
InitialB
          Initial values for the coefficients of polynomial B(q) of order nb-1, specified as a row vector of length
          nb+nk, with nk leading zeros. nk is the input-output delay. Specify the coefficients in order of
          ascending powers of q-1.
          If the initial guesses are much smaller than the default InitialParameterCovariance, 10000, the
          initial guesses are given less importance during estimation. In that case, specify a smaller initial
          parameter covariance.
InitialB is a tunable property. You can change it when the object is in a locked state.
Default: [0 eps]
InitialC
          Initial values for the coefficients of polynomial C(q) of order nc, specified as a row vector of length nc
          +1, with 1 as the first element. Specify the coefficients in order of ascending powers of q-1.
          The coefficients in InitialC must define a stable discrete-time polynomial with roots within a unit
          circle. For example,
1-1084
                                                                                          recursiveARMAX
ans =
If the initial guesses are much smaller than the default InitialParameterCovariance, 10000, the
initial guesses are given less importance during estimation. In that case, specify a smaller initial
parameter covariance.
InitialC is a tunable property. You can change it when the object is in a locked state.
Default: [1 eps]
ParameterCovariance
ParameterCovariance is a read-only property and is initially empty after you create the object. It is
populated after you use the step command for online parameter estimation.
InitialParameterCovariance
• Real positive scalar, α — Covariance matrix is an N-by-N diagonal matrix, with α as the diagonal
  elements. N is the number of parameters to be estimated.
• Vector of real positive scalars, [α1,...,αN] — Covariance matrix is an N-by-N diagonal matrix, with
  [α1,...,αN] as the diagonal elements.
• N-by-N symmetric positive-definite matrix.
Default: 10000
                                                                                                1-1085
1   Functions
EstimationMethod
          Recursive estimation algorithm used for online estimation of model parameters, specified as one of
          the following values:
          Forgetting factor and Kalman filter algorithms are more computationally intensive than gradient and
          unnormalized gradient methods. However, they have better convergence properties. For information
          about these algorithms, see “Recursive Algorithms for Online Parameter Estimation”.
          EstimationMethod is a nontunable property. You cannot change it during execution, that is after
          the object is locked using the step command. If you want to deploy code using MATLAB Coder,
          EstimationMethod can only be assigned once.
Default: 'ForgettingFactor'
ForgettingFactor
Forgetting factor, λ, relevant for parameter estimation, specified as a scalar in the range (0,1].
          Suppose that the system remains approximately constant over T0 samples. You can choose λ such
          that:
                         1
                 T0 =
                        1−λ
ForgettingFactor is a tunable property. You can change it when the object is in a locked state.
Default: 1
EnableAdapation
          • true or 1— The step command estimates the parameter values for that time step and updates
            the parameter values.
          • false or 0 — The step command does not update the parameters for that time step and instead
            outputs the last estimated value. You can use this option when your system enters a mode where
            the parameter values do not vary with time.
                Note If you set EnableAdapation to false, you must still execute the step command. Do not
                skip step to keep parameter values constant, because parameter estimation depends on current
1-1086
                                                                                         recursiveARMAX
   and past I/O measurements. step ensures past I/O data is stored, even when it does not update
   the parameters.
EnableAdapation is a tunable property. You can change it when the object is in a locked state.
Default: true
DataType
Setting DataType to 'single' saves memory, but leads to loss of precision. Specify DataType
based on the precision required by the target processor where you will deploy generated code.
DataType is a nontunable property. It can only be set during object construction using Name,Value
arguments and cannot be changed afterward.
Default: 'double'
ProcessNoiseCovariance
• Real nonnegative scalar, α — Covariance matrix is an N-by-N diagonal matrix, with α as the
  diagonal elements.
• Vector of real nonnegative scalars, [α1,...,αN] — Covariance matrix is an N-by-N diagonal matrix,
  with [α1,...,αN] as the diagonal elements.
• N-by-N symmetric positive semidefinite matrix.
Kalman filter algorithm treats the parameters as states of a dynamic system and estimates these
parameters using a Kalman filter. ProcessNoiseCovariance is the covariance of the process noise
acting on these parameters. Zero values in the noise covariance matrix correspond to estimating
constant coefficients. Values larger than 0 correspond to time-varying parameters. Use large values
for rapidly changing parameters. However, the larger values result in noisier parameter estimates.
ProcessNoiseCovariance is a tunable property. You can change it when the object is in a locked
state.
Default: 0.1
AdaptationGain
Adaptation gain, γ, used in gradient recursive estimation algorithms, specified as a positive scalar.
                                                                                                 1-1087
1   Functions
          Specify a large value for AdaptationGain when your measurements have a high signal-to-noise
          ratio.
AdaptationGain is a tunable property. You can change it when the object is in a locked state.
Default: 1
NormalizationBias
          The normalized gradient algorithm divides the adaptation gain at each step by the square of the two-
          norm of the gradient vector. If the gradient is close to zero, this can cause jumps in the estimated
          parameters. NormalizationBias is the term introduced in the denominator to prevent these jumps.
          Increase NormalizationBias if you observe jumps in estimated parameters.
NormalizationBias is a tunable property. You can change it when the object is in a locked state.
Default: eps
          Output Arguments
          obj — System object for online parameter estimation of ARMAX model
          recursiveARMAX System object
          System object for online parameter estimation of ARMAX model, returned as a recursiveARMAX
          System object. This object is created using the specified model orders and properties. Use step
          command to estimate the coefficients of the ARMAX model polynomials. You can then access the
          estimated coefficients and parameter covariance using dot notation. For example, type obj.A to view
          the estimated A polynomial coefficients.
          More About
          ARMAX Model Structure
The ARMAX (Autoregressive Moving Average with Extra Input) model structure is:
where
1-1088
                                                                                      recursiveARMAX
The parameters na, nb, and nc are the orders of the ARMAX model, and nk is the delay. q is the delay
operator. Specifically,
                                   −na
     A(q) = 1 + a1q−1 + … + anaq
                                   −nb + 1
     B(q) = b1 + b2q−1 + … + bnbq
                                −nc
     C(q) = 1 + c1q−1 + … + cncq
Tips
• Starting in R2016b, instead of using the step command to update model parameter estimates,
  you can call the System object with input arguments, as if it were a function. For example,
  [A,B,C,EstimatedOutput] = step(obj,y,u) and [A,B,C,EstimatedOutput] =
  obj(y,u) perform equivalent operations.
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
See Also
Recursive Polynomial Model Estimator | armax | clone | isLocked | recursiveAR |
recursiveARMA | recursiveARX | recursiveBJ | recursiveLS | recursiveOE | release |
reset | step
Topics
“Perform Online Parameter Estimation at the Command Line”
“Validate Online Parameter Estimation at the Command Line”
“What Is Online Estimation?”
“Recursive Algorithms for Online Parameter Estimation”
                                                                                            1-1089
1   Functions
Introduced in R2015b
1-1090
                                                                                         recursiveARX
recursiveARX
Create System object for online parameter estimation of ARX model
Syntax
obj   =   recursiveARX
obj   =   recursiveARX(Orders)
obj   =   recursiveARX(Orders,A0,B0)
obj   =   recursiveARX( ___ ,Name,Value)
Description
Use recursiveARX command for parameter estimation with real-time data. If all data necessary for
estimation is available at once, and you are estimating a time-invariant model, use the offline
estimation command, arx.
obj = recursiveARX creates a System object for online parameter estimation of a default ARX
model structure on page 1-1102. The default model structure has polynomials of order 1 and initial
polynomial coefficient values eps.
After creating the object, use the step command to update model parameter estimates using
recursive estimation algorithms and real-time data.
obj = recursiveARX(Orders) specifies the polynomial orders of the ARX model to be estimated.
obj = recursiveARX(Orders,A0,B0) specifies the polynomial orders and initial values of the
polynomial coefficients.
obj = recursiveARX( ___ ,Name,Value) specifies additional attributes of the ARX model
structure and recursive estimation algorithm using one or more Name,Value pair arguments.
Object Description
recursiveARX creates a System object for online parameter estimation of single-input single-output
(SISO) or multiple-input single-output (MISO) ARX models using a recursive estimation algorithm.
A System object is a specialized MATLAB object designed specifically for implementing and
simulating dynamic systems with inputs that change over time. System objects use internal states to
store past behavior, which is used in the next computational step.
After you create a System object, you use commands to process data or obtain information from or
about the object. System objects use a minimum of two commands to process data — a constructor to
create the object and the step command to update object parameters using real-time data. This
separation of declaration from execution lets you create multiple, persistent, reusable objects, each
with different settings.
You can use the following commands with the online estimation System objects in System
Identification Toolbox:
                                                                                              1-1091
1   Functions
           Command                                              Description
           step                                                 Update model parameter estimates using
                                                                recursive estimation algorithms and real-time
                                                                data.
          Use the recursiveARX command to create an online estimation System object. Then estimate the
          ARX model parameters (A and B) and output using the step command with incoming input and
          output data, u and y.
[A,B,EstimatedOutput] = step(obj,y,u)
Examples
Create a System object for online parameter estimation of a SISO ARX model.
obj = recursiveARX;
          The ARX model has a default structure with polynomials of order 1 and initial polynomial coefficient
          values, eps.
Load the estimation data. In this example, use a static data set for illustration.
1-1092
                                                                                        recursiveARX
ans = 1×2
0 0.7974
ans = 2×2
    0.0002      0.0001
    0.0001      0.0034
EstimatedOutput = -4.7766
Create System Object for SISO ARX Model With Known Initial Parameters
Create a System object for online estimation of SISO ARX model with known initial polynomial
coefficients.
A0 = [1 0.5];
B0 = [0 1 1];
obj = recursiveARX([na nb nk],A0,B0);
InitialParameterCovariance represents the uncertainty in your guess for the initial parameters.
Typically, the default InitialParameterCovariance (10000) is too large relative to the parameter
values. This results in initial guesses being given less importance during estimation. If you have
confidence in the initial parameter guesses, specify a smaller initial parameter covariance.
                                                                                               1-1093
1   Functions
Create System Object for MISO ARX Model With Known Initial Parameters
Specify orders and delays for ARX model with two inputs and one output.
          na = 1;
          nb = [2 1];
          nk = [1 3];
nb and nk are specified as row vectors of length equal to number of inputs, Nu.
          A0 = [1 0.5];
          B0 = [0 1 1 0; 0 0 0 0.8];
          B0 has Nu rows and max(nb+nk) columns. The i-th row corresponds to i-th input and is specified as
          having nk(i) zeros, followed by nb(i) initial values. Values after nb(i)+nk(i) are ignored.
Create a System object for online estimation of ARX model with known initial polynomial coefficients.
          Create a System object that uses the normalized gradient algorithm for online parameter estimation
          of an ARX model.
          Input Arguments
          Orders — Model orders and delays
          1-by-3 vector of integers | 1-by-3 vector of vectors
          Model orders and delays of an ARX model on page 1-1102, specified as a 1-by-3 vector of integers or
          vectors, [na nb nk].
                For MISO models, there are as many B(q) polynomials as the number of inputs. nb(i) is the order
                of ith polynomial Bi(q)+1 for the ith input.
          • nk — Input-output delay, specified as a 1–by-Nu vector of nonnegative integers. Nu is the number
            of inputs.
                For MISO models, there are as many B(q) polynomials as the number of inputs. nk(i) is the
                input-output delay time corresponding to the ith input.
1-1094
                                                                                              recursiveARX
Initial value of coefficients of A(q) and B(q) polynomials, specified as row vector and matrix or real
values, respectively. Specify the elements in order of ascending powers of q-1.
• A0 — Initial value for the coefficients of the polynomial A(q), specified as a 1-by-(na+1) row vector
  with 1 as the first element.
• B0 — Initial value for the coefficients of the polynomial B(q), specified as Nu-by-max(nb+nk)
  matrix. Nu is the number of inputs.
    For MISO models, there are as many B(q) polynomials as the number of inputs. The ith row of B0
    corresponds to the ith input and must contain nk(i) leading zeros, followed by nb(i) initial
    parameter values. Entries beyond nk(i)+nb(i) are ignored.
Specifying as [], uses the default value of eps for the polynomial coefficients.
If the initial parameter values are much smaller than InitialParameterCovariance, these initial
values are given less importance during estimation. Specify a smaller initial parameter covariance if
you have high confidence in the initial parameter values. This statement applies only for infinite-
history estimation. Finite-history estimation does not use InitialParameterCovariance.
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Use Name,Value arguments to specify writable properties on page 1-1095 of recursiveARX System
object during object creation. For example, obj = recursiveARX([2 2
1],'EstimationMethod','Gradient') creates a System object to estimate an ARX model using
the 'Gradient' recursive estimation algorithm.
Properties
recursiveARX System object properties consist of read-only and writable properties. The writable
properties are tunable and nontunable properties. The nontunable properties cannot be changed
when the object is locked, that is, after you use the step command.
Use Name,Value arguments to specify writable properties of recursiveARX objects during object
creation. After object creation, use dot notation to modify the tunable properties.
obj = recursiveARX;
obj.ForgettingFactor = 0.99;
Estimated coefficients of polynomial A(q), returned as a row vector of real values specified in order of
ascending powers of q-1.
A is a read-only property and is initially empty after you create the object. It is populated after you
use the step command for online parameter estimation.
                                                                                                  1-1095
1   Functions
          The ith row of B corresponds to the ith input and contains nk(i) leading zeros, followed by nb(i)
          estimated parameters, specified in order of ascending powers of q-1. Ignore zero entries beyond
          nk(i)+nb(i).
          B is a read-only property and is initially empty after you create the object. It is populated after you
          use the step command for online parameter estimation.
InitialA
          Initial values for the coefficients of polynomial A(q) of order na, specified as a row vector of length na
          +1, with 1 as the first element. Specify the coefficients in order of ascending powers of q-1.
          If the initial guesses are much smaller than the default InitialParameterCovariance, 10000, the
          initial guesses are given less importance during estimation. In that case, specify a smaller initial
          parameter covariance.
InitialA is a tunable property. You can change it when the object is in a locked state.
Default: [1 eps]
InitialB
          Initial values for the coefficients of polynomial B(q), specified as an Nu-by-max(nb+nk) matrix. Nu is
          the number of inputs.
          For MISO models, there are as many B(q) polynomials as the number of inputs. The ith row of B0
          corresponds to the ith input and must contain nk(i) zeros, followed by nb(i) initial parameter
          values. Entries beyond nk(i)+nb(i) are ignored.
          If the initial guesses are much smaller than the default InitialParameterCovariance, 10000, the
          initial guesses are given less importance during estimation. In that case, specify a smaller initial
          parameter covariance.
InitialB is a tunable property. You can change it when the object is in a locked state.
Default: [0 eps]
InitialOutputs
The InitialOutputs property provides a means of controlling the initial behavior of the algorithm.
When InitialOutputs is set to 0, the object populates the buffer with zeros.
          If the initial buffer is set to 0 or does not contain enough information, you see a warning message
          during the initial phase of your estimation. The warning should clear after a few cycles. The number
          of cycles it takes for sufficient information to be buffered depends upon the order of your polynomials
          and your input delays. If the warning persists, you should evaluate the content of your signals.
1-1096
                                                                                           recursiveARX
InitialOutputs is a tunable property. You can change InitialOutputs when the object is in a
locked state.
Default: 0
InitialInputs
Initial values of the inputs in the finite history window, specified as 0 or as a (W-1+max(nb)
+max(nk))-by-nu matrix, where W is the window length and nu is the number of inputs. nb is the
vector of B(q) polynomial orders and nk is vector of input delays that you specify when constructing
the recursiveARX object.
The InitialInputs property provides a means of controlling the initial behavior of the algorithm.
When the InitialInputs is set to 0, the object populates the buffer with zeros.
If the initial buffer is set to 0 or does not contain enough information, you see a warning message
during the initial phase of your estimation. The warning should clear after a few cycles. The number
of cycles it takes for sufficient information to be buffered depends upon the order of your polynomials
and your input delays. If the warning persists, you should evaluate the content of your signals.
InitialInputs is a tunable property. You can change InitialInputs when the object is in a
locked state.
Default: 0
ParameterCovariance
The interpretation of P depends on your settings for the History and EstimationMethod
properties.
• If History is Infinite, then your EstimationMethod selection results in one of the following:
                                                                                               1-1097
1   Functions
          ParameterCovariance is a read-only property and is initially empty after you create the object. It is
          populated after you use the step command for online parameter estimation.
InitialParameterCovariance
          • Real positive scalar, α — Covariance matrix is an N-by-N diagonal matrix, with α as the diagonal
            elements. N is the number of parameters to be estimated.
          • Vector of real positive scalars, [α1,...,αN] — Covariance matrix is an N-by-N diagonal matrix, with
            [α1,...,αN] as the diagonal elements.
          • N-by-N symmetric positive-definite matrix.
Default: 10000
EstimationMethod
          Recursive estimation algorithm used for online estimation of model parameters, specified as one of
          the following values:
          Forgetting factor and Kalman filter algorithms are more computationally intensive than gradient and
          unnormalized gradient methods. However, they have better convergence properties. For information
          about these algorithms, see “Recursive Algorithms for Online Parameter Estimation”.
These methods all use an infinite data history, and are available only when History is 'Infinite'.
          EstimationMethod is a nontunable property. You cannot change it during execution, that is, after
          the object is locked using the step command.
ForgettingFactor
Forgetting factor, λ, relevant for parameter estimation, specified as a scalar in the range (0,1].
          Suppose that the system remains approximately constant over T0 samples. You can choose λ such
          that:
                        1
                T0 =
                       1−λ
1-1098
                                                                                          recursiveARX
ForgettingFactor is a tunable property. You can change it when the object is in a locked state.
Default: 1
EnableAdapation
• true or 1— The step command estimates the parameter values for that time step and updates
  the parameter values.
• false or 0 — The step command does not update the parameters for that time step and instead
  outputs the last estimated value. You can use this option when your system enters a mode where
  the parameter values do not vary with time.
   Note If you set EnableAdapation to false, you must still execute the step command. Do not
   skip step to keep parameter values constant, because parameter estimation depends on current
   and past I/O measurements. step ensures past I/O data is stored, even when it does not update
   the parameters.
EnableAdapation is a tunable property. You can change it when the object is in a locked state.
Default: true
DataType
Setting DataType to 'single' saves memory, but leads to loss of precision. Specify DataType
based on the precision required by the target processor where you will deploy generated code.
DataType is a nontunable property. It can only be set during object construction using Name,Value
arguments and cannot be changed afterward.
Default: 'double'
ProcessNoiseCovariance
• Real nonnegative scalar, α — Covariance matrix is an N-by-N diagonal matrix, with α as the
  diagonal elements.
• Vector of real nonnegative scalars, [α1,...,αN] — Covariance matrix is an N-by-N diagonal matrix,
  with [α1,...,αN] as the diagonal elements.
                                                                                              1-1099
1   Functions
          Kalman filter algorithm treats the parameters as states of a dynamic system and estimates these
          parameters using a Kalman filter. ProcessNoiseCovariance is the covariance of the process noise
          acting on these parameters. Zero values in the noise covariance matrix correspond to estimating
          constant coefficients. Values larger than 0 correspond to time-varying parameters. Use large values
          for rapidly changing parameters. However, the larger values result in noisier parameter estimates.
          ProcessNoiseCovariance is a tunable property. You can change it when the object is in a locked
          state.
Default: 0.1
AdaptationGain
Adaptation gain, γ, used in gradient recursive estimation algorithms, specified as a positive scalar.
          Specify a large value for AdaptationGain when your measurements have a high signal-to-noise
          ratio.
AdaptationGain is a tunable property. You can change it when the object is in a locked state.
Default: 1
NormalizationBias
          The normalized gradient algorithm divides the adaptation gain at each step by the square of the two-
          norm of the gradient vector. If the gradient is close to zero, this can cause jumps in the estimated
          parameters. NormalizationBias is the term introduced in the denominator to prevent these jumps.
          Increase NormalizationBias if you observe jumps in estimated parameters.
NormalizationBias is a tunable property. You can change it when the object is in a locked state.
Default: eps
History
Data history type defining which type of recursive algorithm you use, specified as:
          • 'Infinite' — Use an algorithm that aims to minimize the error between the observed and
            predicted outputs for all time steps from the beginning of the simulation.
          • 'Finite' — Use an algorithm that aims to minimize the error between the observed and
            predicted outputs for a finite number of past time steps.
1-1100
                                                                                          recursiveARX
Algorithms with infinite history aim to produce parameter estimates that explain all data since the
start of the simulation. These algorithms still use a fixed amount of memory that does not grow over
time. The object provides multiple algorithms of the 'Infinite' History type. Specifying this
option activates the EstimationMethod property with which you specify an algorithm.
Algorithms with finite history aim to produce parameter estimates that explain only a finite number of
past data samples. This method is also called sliding-window estimation. The object provides one
algorithm of the 'Finite' type. Specifying this option activates the WindowLength property that
sizes the window.
For more information on recursive estimation methods, see “Recursive Algorithms for Online
Parameter Estimation”.
History is a nontunable property. It can be set only during object construction using Name,Value
arguments and cannot be changed afterward.
Default: 'Infinite'
WindowLength
Window size determining the number of time samples to use for the sliding-window estimation
method, specified as a positive integer. Specify WindowLength only when History is Finite.
Choose a window size that balances estimation performance with computational and memory burden.
Sizing factors include the number and time variance of the parameters in your model. Always specify
Window Length in samples, even if you are using frame-based input processing.
Suitable window length is independent of whether you are using sample-based or frame-based input
processing (see InputProcessing). However, when using frame-based processing, your window
length must be greater than or equal to the number of samples (time steps) contained in the frame.
WindowLength is a nontunable property. It can be set only during object construction using
Name,Value arguments and cannot be changed afterward.
Default: 200
InputProcessing
Option for sample-based or frame-based input processing, specified as a character vector or string.
Your InputProcessing specification impacts the dimensions for the input and output signals when
using the step command:
[theta,EstimatedOutput] = step(obj,y,u)
• Sample-based
                                                                                              1-1101
1   Functions
          InputProcessing is a nontunable property. It can be set only during object construction using
          Name,Value arguments and cannot be changed afterward.
Default: 'Sample-based'
          Output Arguments
          obj — System object for online parameter estimation of ARX model
          recursiveARX System object
          System object for online parameter estimation of ARX model, returned as a recursiveARX System
          object. This object is created using the specified model orders and properties. Use step command to
          estimate the coefficients of the ARX model polynomials. You can then access the estimated
          coefficients and parameter covariance using dot notation. For example, type obj.A to view the
          estimated A polynomial coefficients.
          More About
          ARX Model Structure
The parameters na and nb are the orders of the ARX model, and nk is the delay.
1-1102
                                                                                    recursiveARX
                               −na
    A(q) = 1 + a1q−1 + … + anaq
                                  −nb + 1
    B(q) = b1 + b2q−1 + … + bnbq
Tips
• Starting in R2016b, instead of using the step command to update model parameter estimates,
  you can call the System object with input arguments, as if it were a function. For example,
  [A,B,EstimatedOutput] = step(obj,y,u) and [A,B,EstimatedOutput] = obj(y,u)
  perform equivalent operations.
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
See Also
Recursive Polynomial Model Estimator | arx | clone | isLocked | recursiveAR | recursiveARMA |
recursiveARMAX | recursiveBJ | recursiveLS | recursiveOE | release | reset | step
Topics
“Perform Online Parameter Estimation at the Command Line”
“Validate Online Parameter Estimation at the Command Line”
“Online ARX Parameter Estimation for Tracking Time-Varying System Dynamics”
“What Is Online Estimation?”
“Recursive Algorithms for Online Parameter Estimation”
Introduced in R2015b
                                                                                        1-1103
1   Functions
          recursiveBJ
          Create System object for online parameter estimation of Box-Jenkins polynomial model
          Syntax
          obj   =   recursiveBJ
          obj   =   recursiveBJ(Orders)
          obj   =   recursiveBJ(Orders,B0,C0,D0,F0)
          obj   =   recursiveBJ( ___ ,Name,Value)
          Description
          Use recursiveBJ command for parameter estimation with real-time data. If all data necessary for
          estimation is available at once, and you are estimating a time-invariant model, use the offline
          estimation command, bj.
          obj = recursiveBJ creates a System object for online parameter estimation of a default single-
          input single-output (SISO) Box-Jenkins polynomial model structure on page 1-1114. The default model
          structure has polynomials of order 1 and initial polynomial coefficient values eps.
          After creating the object, use the step command to update model parameter estimates using
          recursive estimation algorithms and real-time data.
          obj = recursiveBJ( ___ ,Name,Value) specifies additional attributes of the Box-Jenkins model
          structure and recursive estimation algorithm using one or more Name,Value pair arguments.
          Object Description
          recursiveBJ creates a System object for online parameter estimation of SISO Box-Jenkins
          polynomial models using a recursive estimation algorithm.
          A System object is a specialized MATLAB object designed specifically for implementing and
          simulating dynamic systems with inputs that change over time. System objects use internal states to
          store past behavior, which is used in the next computational step.
          After you create a System object, you use commands to process data or obtain information from or
          about the object. System objects use a minimum of two commands to process data — a constructor to
          create the object and the step command to update object parameters using real-time data. This
          separation of declaration from execution lets you create multiple, persistent, reusable objects, each
          with different settings.
1-1104
                                                                                                 recursiveBJ
You can use the following commands with the online estimation System objects in System
Identification Toolbox:
Command                                               Description
step                                                  Update model parameter estimates using
                                                      recursive estimation algorithms and real-time
                                                      data.
Use the recursiveBJ command to create an online estimation System object. Then estimate the
Box-Jenkins polynomial model parameters (B, C, D, and F) and output using the step command with
incoming input and output data, u and y.
[B,C,D,F,EstimatedOutput] = step(obj,y,u)
Examples
Create a System object for online parameter estimation of a Box-Jenkins polynomial model.
obj = recursiveBJ;
The Box-Jenkins model has a default structure with polynomials of order 1 and initial polynomial
coefficient values, eps.
Load the estimation data. In this example, use a static data set for illustration.
                                                                                                   1-1105
1   Functions
          for i = 1:numel(input)
          [B,C,D,F,EstimatedOutput] = step(obj,output(i),input(i));
          end
obj.D
ans = 1×2
1.0000 -0.6876
obj.ParameterCovariance
ans = 4×4
EstimatedOutput
EstimatedOutput = -4.1905
Create System Object for Box-Jenkins Model With Known Orders and Delays
          nb    =   1;
          nc    =   1;
          nd    =   2;
          nf    =   1;
          nk    =   1;
          Create a System object for online estimation of Box-Jenkins model with the specified orders and
          delays.
1-1106
                                                                                           recursiveBJ
Create System Object for Box-Jenkins Model With Known Initial Parameters
nb   =   1;
nc   =   1;
nd   =   1;
nf   =   2;
nk   =   1;
Create a System object for online estimation of Box-Jenkins model with known initial polynomial
coefficients.
B0 = [0 1];
C0 = [1 0.5];
D0 = [1 0.9];
F0 = [1 0.7 0.8];
obj = recursiveBJ([nb nc nd nf nk],B0,C0,D0,F0);
obj.InitialParameterCovariance = 0.1;
InitialParameterCovariance represents the uncertainty in your guess for the initial parameters.
Typically, the default InitialParameterCovariance (10000) is too large relative to the parameter
values. This results in initial guesses being given less importance during estimation. If you have
confidence in the initial parameter guesses, specify a smaller initial parameter covariance.
Create a System object that uses the normalized gradient algorithm for online parameter estimation
of a Box-Jenkins model.
Input Arguments
Orders — Model orders and delays
1-by-5 vector of integers
Model orders and delays of a Box-Jenkins polynomial model on page 1-1114, specified as a 1-by-5
vector of integers, [nb nc nd nf nk].
                                                                                              1-1107
1   Functions
          Initial value of polynomial coefficients, specified as row vectors of real values with elements in order
          of ascending powers of q-1.
          • B0 — Initial guess for the coefficients of the polynomial B(q), specified as a 1-by-(nb+nk) vector
            with nk leading zeros.
          • C0 — Initial guess for the coefficients of the polynomial C(q), specified as a 1-by-(nc+1) vector
            with 1 as the first element.
                The coefficients in C0 must define a stable discrete-time polynomial with roots within a unit disk.
                For example,
                C0 = [1 0.5 0.5];
                all(abs(roots(C0))<1)
ans =
                      1
          • D0 — Initial guess for the coefficients of the polynomial D(q), specified as a 1-by-(nd+1) vector
            with 1 as the first element.
                The coefficients in D0 must define a stable discrete-time polynomial with roots within a unit disk.
                For example,
                D0 = [1 0.9 0.8];
                all(abs(roots(D0))<1)
ans =
                        1
          • F0 — Initial guess for the coefficients of the polynomial F(q), specified as a 1-by-(nf+1) vector
            with 1 as the first element.
                The coefficients in F0 must define a stable discrete-time polynomial with roots within a unit disk.
                For example,
                F0 = [1 0.5 0.5];
                all(abs(roots(F0))<1)
ans =
Specifying as [], uses the default value of eps for the polynomial coefficients.
          Note If the initial guesses are much smaller than the default InitialParameterCovariance,
          10000, the initial guesses are given less importance during estimation. In that case, specify a smaller
          initial parameter covariance.
1-1108
                                                                                                recursiveBJ
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Use Name,Value arguments to specify writable properties on page 1-1109 of recursiveBJ System
object during object creation. For example, obj = recursiveBJ([1 1 1 2
1],'EstimationMethod','Gradient') creates a System object to estimate a Box-Jenkins
polynomial model using the 'Gradient' recursive estimation algorithm.
Properties
recursiveBJ System object properties consist of read-only and writable properties. The writable
properties are tunable and nontunable properties. The nontunable properties cannot be changed
when the object is locked, that is, after you use the step command.
Use Name,Value arguments to specify writable properties of recursiveBJ objects during object
creation. After object creation, use dot notation to modify the tunable properties.
obj = recursiveBJ;
obj.ForgettingFactor = 0.99;
Estimated coefficients of polynomial B(q), returned as a vector of real values specified in order of
ascending powers of q-1.
B is a read-only property and is initially empty after you create the object. It is populated after you
use the step command for online parameter estimation.
Estimated coefficients of polynomial C(q), returned as a vector of real values specified in order of
ascending powers of q-1.
C is a read-only property and is initially empty after you create the object. It is populated after you
use the step command for online parameter estimation.
Estimated coefficients of polynomial D(q), returned as a vector of real values specified in order of
ascending powers of q-1.
D is a read-only property and is initially empty after you create the object. It is populated after you
use the step command for online parameter estimation.
Estimated coefficients of polynomial F(q), returned as a vector of real values specified in order of
ascending powers of q-1.
F is a read-only property and is initially empty after you create the object. It is populated after you
use the step command for online parameter estimation.
                                                                                                  1-1109
1   Functions
InitialB
          Initial values for the coefficients of polynomial B(q) of order nb-1, specified as a row vector of length
          nb+nk, with nk leading zeros. nk is the input-output delay. Specify the coefficients in order of
          ascending powers of q-1.
          If the initial guesses are much smaller than the default InitialParameterCovariance, 10000, the
          initial guesses are given less importance during estimation. In that case, specify a smaller initial
          parameter covariance.
InitialB is a tunable property. You can change it when the object is in a locked state.
Default: [0 eps]
InitialC
          Initial values for the coefficients of polynomial C(q) of order nc, specified as a row vector of length nc
          +1, with 1 as the first element. Specify the coefficients in order of ascending powers of q-1.
          The coefficients in InitialC must define a stable discrete-time polynomial with roots within a unit
          circle. For example,
          InitialC = [1 0.5 0.5];
          all(abs(roots(InitialC))<1)
ans =
          If the initial guesses are much smaller than the default InitialParameterCovariance, 10000, the
          initial guesses are given less importance during estimation. In that case, specify a smaller initial
          parameter covariance.
InitialC is a tunable property. You can change it when the object is in a locked state.
Default: [1 eps]
InitialD
          Initial values for the coefficients of polynomial D(q) of order nd, specified as a row vector of length nd
          +1, with 1 as the first element. Specify the coefficients in order of ascending powers of q-1.
          The coefficients in InitialD must define a stable discrete-time polynomial with roots within a unit
          circle. For example,
          InitialD = [1 0.9 0.8];
          all(abs(roots(InitialD))<1)
ans =
          If the initial guesses are much smaller than the default InitialParameterCovariance, 10000, the
          initial guesses are given less importance during estimation. In that case, specify a smaller initial
          parameter covariance.
InitialD is a tunable property. You can change it when the object is in a locked state.
1-1110
                                                                                                recursiveBJ
Default: [1 eps]
InitialF
Initial values for the coefficients of polynomial F(q) of order nf, specified as a row vector of length nf
+1, with 1 as the first element. Specify the coefficients in order of ascending powers of q-1.
The coefficients in InitialF must define a stable discrete-time polynomial with roots within a unit
circle. For example,
ans =
If the initial guesses are much smaller than the default InitialParameterCovariance, 10000, the
initial guesses are given less importance during estimation. In that case, specify a smaller initial
parameter covariance.
InitialF is a tunable property. You can change it when the object is in a locked state.
Default: [1 eps]
ParameterCovariance
ParameterCovariance is a read-only property and is initially empty after you create the object. It is
populated after you use the step command for online parameter estimation.
InitialParameterCovariance
• Real positive scalar, α — Covariance matrix is an N-by-N diagonal matrix, with α as the diagonal
  elements. N is the number of parameters to be estimated.
• Vector of real positive scalars, [α1,...,αN] — Covariance matrix is an N-by-N diagonal matrix, with
  [α1,...,αN] as the diagonal elements.
• N-by-N symmetric positive-definite matrix.
                                                                                                  1-1111
1   Functions
Default: 10000
EstimationMethod
          Recursive estimation algorithm used for online estimation of model parameters, specified as one of
          the following values:
          Forgetting factor and Kalman filter algorithms are more computationally intensive than gradient and
          unnormalized gradient methods. However, they have better convergence properties. For information
          about these algorithms, see “Recursive Algorithms for Online Parameter Estimation”.
          EstimationMethod is a nontunable property. You cannot change it during execution, that is after
          the object is locked using the step command. If you want to deploy code using MATLAB Coder,
          EstimationMethod can only be assigned once.
Default: 'ForgettingFactor'
ForgettingFactor
Forgetting factor, λ, relevant for parameter estimation, specified as a scalar in the range (0,1].
          Suppose that the system remains approximately constant over T0 samples. You can choose λ such
          that:
                        1
                T0 =
                       1−λ
ForgettingFactor is a tunable property. You can change it when the object is in a locked state.
Default: 1
1-1112
                                                                                            recursiveBJ
EnableAdapation
• true or 1— The step command estimates the parameter values for that time step and updates
  the parameter values.
• false or 0 — The step command does not update the parameters for that time step and instead
  outputs the last estimated value. You can use this option when your system enters a mode where
  the parameter values do not vary with time.
   Note If you set EnableAdapation to false, you must still execute the step command. Do not
   skip step to keep parameter values constant, because parameter estimation depends on current
   and past I/O measurements. step ensures past I/O data is stored, even when it does not update
   the parameters.
EnableAdapation is a tunable property. You can change it when the object is in a locked state.
Default: true
DataType
Setting DataType to 'single' saves memory, but leads to loss of precision. Specify DataType
based on the precision required by the target processor where you will deploy generated code.
DataType is a nontunable property. It can only be set during object construction using Name,Value
arguments and cannot be changed afterward.
Default: 'double'
ProcessNoiseCovariance
• Real nonnegative scalar, α — Covariance matrix is an N-by-N diagonal matrix, with α as the
  diagonal elements.
• Vector of real nonnegative scalars, [α1,...,αN] — Covariance matrix is an N-by-N diagonal matrix,
  with [α1,...,αN] as the diagonal elements.
• N-by-N symmetric positive semidefinite matrix.
Kalman filter algorithm treats the parameters as states of a dynamic system and estimates these
parameters using a Kalman filter. ProcessNoiseCovariance is the covariance of the process noise
acting on these parameters. Zero values in the noise covariance matrix correspond to estimating
constant coefficients. Values larger than 0 correspond to time-varying parameters. Use large values
for rapidly changing parameters. However, the larger values result in noisier parameter estimates.
                                                                                              1-1113
1   Functions
          ProcessNoiseCovariance is a tunable property. You can change it when the object is in a locked
          state.
Default: 0.1
AdaptationGain
Adaptation gain, γ, used in gradient recursive estimation algorithms, specified as a positive scalar.
          Specify a large value for AdaptationGain when your measurements have a high signal-to-noise
          ratio.
AdaptationGain is a tunable property. You can change it when the object is in a locked state.
Default: 1
NormalizationBias
          The normalized gradient algorithm divides the adaptation gain at each step by the square of the two-
          norm of the gradient vector. If the gradient is close to zero, this can cause jumps in the estimated
          parameters. NormalizationBias is the term introduced in the denominator to prevent these jumps.
          Increase NormalizationBias if you observe jumps in estimated parameters.
NormalizationBias is a tunable property. You can change it when the object is in a locked state.
Default: eps
          Output Arguments
          obj — System object for online parameter estimation of Box-Jenkins polynomial model
          recursiveBJ System object
          System object for online parameter estimation of Box-Jenkins polynomial model, returned as a
          recursiveBJ System object. This object is created using the specified model orders and properties.
          Use step command to estimate the coefficients of the Box-Jenkins model polynomials. You can then
          access the estimated coefficients and parameter covariance using dot notation. For example, type
          obj.F to view the estimated F polynomial coefficients.
          More About
          Box-Jenkins Polynomial Model Structure
1-1114
                                                                                       recursiveBJ
Tips
• Starting in R2016b, instead of using the step command to update model parameter estimates,
  you can call the System object with input arguments, as if it were a function. For example,
  [B,C,D,F,EstimatedOutput] = step(obj,y,u) and [B,C,D,F,EstimatedOutput] =
  obj(y,u) perform equivalent operations.
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
See Also
Recursive Polynomial Model Estimator | bj | clone | isLocked | recursiveAR | recursiveARMA |
recursiveARMAX | recursiveARX | recursiveLS | recursiveOE | release | reset | step
Topics
“Perform Online Parameter Estimation at the Command Line”
“Validate Online Parameter Estimation at the Command Line”
“What Is Online Estimation?”
“Recursive Algorithms for Online Parameter Estimation”
Introduced in R2015b
                                                                                         1-1115
1   Functions
          recursiveLS
          Create System object for online parameter estimation using recursive least squares algorithm
          Syntax
          obj   =   recursiveLS
          obj   =   recursiveLS(Np)
          obj   =   recursiveLS(Np,theta0)
          obj   =   recursiveLS( ___ ,Name,Value)
          Description
          Use the recursiveLS command for parameter estimation with real-time data. If all data necessary
          for estimation is available at once and you are estimating a time-invariant model, use mldivide, \.
          obj = recursiveLS creates a System object for online parameter estimation of a default single
          output system that is linear in estimated parameters. Such a system can be represented as:
y(t) = H(t)θ(t)+e(t).
          Here, y is the output, θ are the parameters, H are the regressors, and e is the white-noise
          disturbance. The default system has one parameter with initial parameter value 1.
          After creating the object, use the step command to update model parameter estimates using
          recursive least squares algorithms and real-time data. Alternatively, you can call the object directly.
          For more information, see “Tips” on page 1-1130.
          obj = recursiveLS(Np,theta0) also specifies the number of parameters and initial values of the
          parameters.
          obj = recursiveLS( ___ ,Name,Value) specifies additional attributes of the system and
          recursive estimation algorithm using one or more Name,Value pair arguments.
          Object Description
          recursiveLS creates a System object for online parameter estimation of a single output system that
          is linear in its parameters.
          A System object is a specialized MATLAB object designed specifically for implementing and
          simulating dynamic systems with inputs that change over time. System objects use internal states to
          store past behavior, which is used in the next computational step.
          After you create a System object, you use commands to process data or obtain information from or
          about the object. System objects use a minimum of two commands to process data — a constructor to
          create the object and the step command to update object parameters using real-time data. This
          separation of declaration from execution lets you create multiple, persistent, reusable objects, each
          with different settings.
1-1116
                                                                                           recursiveLS
You can use the following commands with the online estimation System objects in System
Identification Toolbox:
Command                                          Description
step                                             Update model parameter estimates using
                                                 recursive estimation algorithms and real-time
                                                 data.
Use the recursiveLS command to create an online estimation System object. Then estimate the
system parameters (theta) and output using the step command with regressors and incoming
output data, H and y.
[theta,EstimatedOutput] = step(obj,y,H)
Examples
Create System Object for Online Estimation Using Recursive Least Squares Algorithm
obj = recursiveLS
obj =
  recursiveLS with properties:
             NumberOfParameters:    1
                     Parameters:    []
              InitialParameters:    1
            ParameterCovariance:    []
                                                                                              1-1117
1   Functions
                InitialParameterCovariance:     10000
                          EstimationMethod:     'ForgettingFactor'
                          ForgettingFactor:     1
                          EnableAdaptation:     true
                                   History:     'Infinite'
                           InputProcessing:     'Sample-based'
                                  DataType:     'double'
y t = a1u t + a2u t − 1
Here,
Create a System object for online estimation using the recursive least squares algorithm.
obj = recursiveLS(2);
Load the estimation data, which for this example is a static data set.
          load iddata3
          input = z3.u;
          output = z3.y;
Create a variable to store u(t-1). This variable is updated at each time step.
oldInput = 0;
          Estimate the parameters and output using step and input-output data, maintaining the current
          regressor pair in H. Invoke the step function implicitly by calling the obj system object with input
          arguments.
          for i = 1:numel(input)
              H = [input(i) oldInput];
              [theta, EstimatedOutput] = obj(output(i),H);
              estimatedOut(i)= EstimatedOutput;
              theta_est(i,:) = theta;
              oldInput = input(i);
          end
          numSample = 1:numel(input);
          plot(numSample,output,'b',numSample,estimatedOut,'r--');
          legend('Measured Output','Estimated Output');
1-1118
                                                                      recursiveLS
plot(numSample,theta_est(:,1),numSample,theta_est(:,2))
title('Parameter Estimates for Recursive Least Squares Estimation')
legend("theta1","theta2")
                                                                        1-1119
1   Functions
theta_final = theta
theta_final = 2×1
                -1.5322
                -0.0235
          Use frame-based signals with the recursiveLS command. Machine interfaces often provide sensor
          data in frames containing multiple samples, rather than in individual samples. The recursiveLS
          object accepts these frames directly when you set InputProcessing to Frame-based.
          The object uses the same estimation algorithms for sample-based and frame-based input processing.
          The estimation results are identical. There are some special considerations, however, for working
          with frame-based inputs.
          This example is the frame-based version of the sample-based recursiveLS example in “Estimate
          Parameters of System Using Recursive Least Squares Algorithm” on page 1-1118.
1-1120
                                                                                            recursiveLS
y t = a1u t + a2u t − 1
Here,
Create a System object for online estimation using the recursive least squares algorithm.
obj_f = recursiveLS(2,'InputProcessing','Frame-Based');
Load the data, which contains input and output time series signals. Each signal consists of 30 frames
and each frame contains ten individual time samples.
numframes = 30
mframe = size(input,1)
mframe = 10
Initialize the regressor frame, which for a given frame, is of the form
        u1 u0
        u2 u1
Hf =             ,
         ⋮ ⋮
        u10 u9
Hframe = zeros(10,2);
For this first-order example, the regressor frame includes one point from the previous frame.
Initialize this point.
oldInput = 0;
Estimate the parameters and output using step and input-output data, maintaining the current
regressor frame in Hframe.
• The input and output arrays have three dimensions. The third dimension is the frame index, and
  the first two dimensions represent the contents of individual frames.
• Use the circshift function to populate the second column of Hframe with the past input value
  for each regressor pair by shifting the input vector by one position.
• Populate the Hframe element holding the oldest value, Hframe(1,2), with the regressor value
  stored from the previous frame.
• Invoke the step function implicitly by calling the obj system object with input arguments. The
  step function is compatible with frames, so no loop function within the frame is necessary.
                                                                                                1-1121
1   Functions
          • Save the most recent input value to use for the next frame calculation.
          EstimatedOutput = zeros(10,1,30);
          theta = zeros(2,30);
          for i = 1:numframes
              Hframe = [input(:,:,i) circshift(input(:,:,i),1)];
              Hframe(1,2) = oldInput;
              [theta(:,i), EstimatedOutput(:,:,i)] = obj_f(output(:,:,i),Hframe);
              oldInput = input(10,:,i);
          end
theta_final = 2×1
                -1.5322
                -0.0235
1-1122
                                                                                             recursiveLS
Specify Initial Parameters for Online Estimation Using Recursive Least Squares Algorithm
Create System object for online parameter estimation using recursive least squares algorithm of a
system with two parameters and known initial parameter values.
InitialParameterCovariance represents the uncertainty in your guess for the initial parameters.
Typically, the default InitialParameterCovariance (10000) is too large relative to the parameter
values. This results in initial guesses being given less importance during estimation. If you have
confidence in the initial parameter guesses, specify a smaller initial parameter covariance.
Input Arguments
Np — Number of parameters
positive integer
Note If the initial parameter values are much smaller than InitialParameterCovariance, these
initial values are given less importance during estimation. Specify a smaller initial parameter
covariance if you have high confidence in the initial parameter values. This statement applies only for
infinite-history estimation. Finite-history estimation does not use InitialParameterCovariance.
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Use Name,Value arguments to specify writable properties on page 1-1124 of recursiveLS System
object during object creation. For example, obj =
recursiveLS(2,'EstimationMethod','Gradient') creates a System object to estimate the
system parameters using the 'Gradient' recursive estimation algorithm.
                                                                                               1-1123
1   Functions
          Properties
          recursiveLS System object properties consist of read-only and writable properties. The writable
          properties are tunable and nontunable properties. The nontunable properties cannot be changed
          when the object is locked, that is, after you use the step command.
          Use Name,Value arguments to specify writable properties of recursiveLS objects during object
          creation. After object creation, use dot notation to modify the tunable properties.
          obj = recursiveLS;
          obj.ForgettingFactor = 0.99;
NumberOfParameters
Default: 1
Parameters
          Parameters is a read-only property and is initially empty after you create the object. It is populated
          after you use the step command for online parameter estimation.
InitialParameters
          If the initial parameter values are much smaller than InitialParameterCovariance, these initial
          values are given less importance during estimation. Specify a smaller initial parameter covariance if
          you have high confidence in initial parameter values. This statement applies only for infinite-history
          estimation. Finite-history estimation does not use InitialParameterCovariance.
          InitialParameters is a tunable property. You can change InitialParameters when the object is
          in a locked state.
Default: 1
InitialOutputs
          Initial values of the outputs buffer in finite-history estimation, specified as 0 or as a W-by-1 vector,
          where W is the window length.
The InitialOutputs property provides a means of controlling the initial behavior of the algorithm.
When InitialOutputs is set to 0, the object populates the buffer with zeros.
          If the initial buffer is set to 0 or does not contain enough information, you see a warning message
          during the initial phase of your estimation. The warning should clear after a few cycles. The number
1-1124
                                                                                                recursiveLS
of cycles it takes for sufficient information to be buffered depends upon the order of your polynomials
and your input delays. If the warning persists, you should evaluate the content of your signals.
InitialOutputs is a tunable property. You can change InitialOutputs when the object is in a
locked state.
Default: 0
InitialRegressors
The InitialRegressors property provides a means of controlling the initial behavior of the
algorithm.
When the InitialRegressors is set to 0, the object populates the buffer with zeros.
If the initial buffer is set to 0 or does not contain enough information, you see a warning message
during the initial phase of your estimation. The warning should clear after a few cycles. The number
of cycles it takes for sufficient information to be buffered depends upon the order of your polynomials
and your input delays. If the warning persists, you should evaluate the content of your signals.
InitialRegressors is a tunable property. You can change InitialRegressors when the object is
in a locked state.
Default: 0
ParameterCovariance
The interpretation of P depends on your settings for the History and EstimationMethod
properties.
• If History is Infinite, then your EstimationMethod selection results in one of the following:
                                                                                                   1-1125
1   Functions
                estimation process. However, the algorithm does compute the covariance for output so that you
                can use it for statistical evaluation.
          ParameterCovariance is a read-only property and is initially empty after you create the object. It is
          populated after you use the step command for online parameter estimation.
InitialParameterCovariance
          • Real positive scalar, α — Covariance matrix is an N-by-N diagonal matrix, with α as the diagonal
            elements. N is the number of parameters to be estimated.
          • Vector of real positive scalars, [α1,...,αN] — Covariance matrix is an N-by-N diagonal matrix, with
            [α1,...,αN] as the diagonal elements.
          • N-by-N symmetric positive-definite matrix.
Default: 10000
EstimationMethod
          Recursive least squares estimation algorithm used for online estimation of model parameters,
          specified as one of the following values:
          Forgetting factor and Kalman filter algorithms are more computationally intensive than gradient and
          unnormalized gradient methods. However, they have better convergence properties. For information
          about these algorithms, see “Recursive Algorithms for Online Parameter Estimation”.
These methods all use an infinite data history, and are available only when History is 'Infinite'.
          EstimationMethod is a nontunable property. You cannot change it during execution, that is, after
          the object is locked using the step command.
ForgettingFactor
Forgetting factor, λ, relevant for parameter estimation, specified as a scalar in the range (0,1].
          Suppose that the system remains approximately constant over T0 samples. You can choose λ such
          that:
1-1126
                                                                                         recursiveLS
            1
    T0 =
           1−λ
ForgettingFactor is a tunable property. You can change it when the object is in a locked state.
Default: 1
EnableAdapation
• true or 1— The step command estimates the parameter values for that time step and updates
  the parameter values.
• false or 0 — The step command does not update the parameters for that time step and instead
  outputs the last estimated value. You can use this option when your system enters a mode where
  the parameter values do not vary with time.
   Note If you set EnableAdapation to false, you must still execute the step command. Do not
   skip step to keep parameter values constant, because parameter estimation depends on current
   and past I/O measurements. step ensures past I/O data is stored, even when it does not update
   the parameters.
EnableAdapation is a tunable property. You can change it when the object is in a locked state.
Default: true
DataType
Setting DataType to 'single' saves memory, but leads to loss of precision. Specify DataType
based on the precision required by the target processor where you will deploy generated code.
DataType is a nontunable property. It can only be set during object construction using Name,Value
arguments and cannot be changed afterward.
Default: 'double'
ProcessNoiseCovariance
                                                                                            1-1127
1   Functions
          • Real nonnegative scalar, α — Covariance matrix is an N-by-N diagonal matrix, with α as the
            diagonal elements.
          • Vector of real nonnegative scalars, [α1,...,αN] — Covariance matrix is an N-by-N diagonal matrix,
            with [α1,...,αN] as the diagonal elements.
          • N-by-N symmetric positive semidefinite matrix.
          Kalman filter algorithm treats the parameters as states of a dynamic system and estimates these
          parameters using a Kalman filter. ProcessNoiseCovariance is the covariance of the process noise
          acting on these parameters. Zero values in the noise covariance matrix correspond to estimating
          constant coefficients. Values larger than 0 correspond to time-varying parameters. Use large values
          for rapidly changing parameters. However, the larger values result in noisier parameter estimates.
          ProcessNoiseCovariance is a tunable property. You can change it when the object is in a locked
          state.
Default: 0.1
AdaptationGain
Adaptation gain, γ, used in gradient recursive estimation algorithms, specified as a positive scalar.
          Specify a large value for AdaptationGain when your measurements have a high signal-to-noise
          ratio.
AdaptationGain is a tunable property. You can change it when the object is in a locked state.
Default: 1
NormalizationBias
          The normalized gradient algorithm divides the adaptation gain at each step by the square of the two-
          norm of the gradient vector. If the gradient is close to zero, this can cause jumps in the estimated
          parameters. NormalizationBias is the term introduced in the denominator to prevent these jumps.
          Increase NormalizationBias if you observe jumps in estimated parameters.
NormalizationBias is a tunable property. You can change it when the object is in a locked state.
Default: eps
History
Data history type defining which type of recursive algorithm you use, specified as:
1-1128
                                                                                           recursiveLS
• 'Infinite' — Use an algorithm that aims to minimize the error between the observed and
  predicted outputs for all time steps from the beginning of the simulation.
• 'Finite' — Use an algorithm that aims to minimize the error between the observed and
  predicted outputs for a finite number of past time steps.
Algorithms with infinite history aim to produce parameter estimates that explain all data since the
start of the simulation. These algorithms still use a fixed amount of memory that does not grow over
time. The object provides multiple algorithms of the 'Infinite' History type. Specifying this
option activates the EstimationMethod property with which you specify an algorithm.
Algorithms with finite history aim to produce parameter estimates that explain only a finite number of
past data samples. This method is also called sliding-window estimation. The object provides one
algorithm of the 'Finite' type. Specifying this option activates the WindowLength property that
sizes the window.
For more information on recursive estimation methods, see “Recursive Algorithms for Online
Parameter Estimation”.
History is a nontunable property. It can be set only during object construction using Name,Value
arguments and cannot be changed afterward.
Default: 'Infinite'
WindowLength
Window size determining the number of time samples to use for the sliding-window estimation
method, specified as a positive integer. Specify WindowLength only when History is Finite.
Choose a window size that balances estimation performance with computational and memory burden.
Sizing factors include the number and time variance of the parameters in your model. Always specify
Window Length in samples, even if you are using frame-based input processing.
Suitable window length is independent of whether you are using sample-based or frame-based input
processing (see InputProcessing). However, when using frame-based processing, your window
length must be greater than or equal to the number of samples (time steps) contained in the frame.
WindowLength is a nontunable property. It can be set only during object construction using
Name,Value arguments and cannot be changed afterward.
Default: 200
InputProcessing
Option for sample-based or frame-based input processing, specified as a character vector or string.
Your InputProcessing specification impacts the dimensions for the input and output signals when
using the step command:
                                                                                              1-1129
1   Functions
[theta,EstimatedOutput] = step(obj,y,H)
• Sample-based
          InputProcessing is a nontunable property. It can be set only during object construction using
          Name,Value arguments and cannot be changed afterward.
Default: 'Sample-based'
          Output Arguments
          obj — System object for online parameter estimation
          recursiveLS System object
          System object for online parameter estimation, returned as a recursiveLS System object. Use step
          command to estimate the parameters of the system. You can then access the estimated parameters
          and parameter covariance using dot notation. For example, type obj.Parameters to view the
          estimated parameters.
          Tips
          • Starting in R2016b, instead of using the step command to update model parameter estimates,
            you can call the System object with input arguments, as if it were a function. For example,
            [theta,EstimatedOutput] = step(obj,y,H) and [theta,EstimatedOutput] =
            obj(y,H) perform equivalent operations.
          Extended Capabilities
          C/C++ Code Generation
          Generate C and C++ code using MATLAB® Coder™.
          See Also
          Recursive Least Squares Estimator | clone | isLocked | mldivide | recursiveAR |
          recursiveARMA | recursiveARMAX | recursiveARX | recursiveBJ | recursiveOE | release |
          reset | step
          Topics
          “Perform Online Parameter Estimation at the Command Line”
1-1130
                                                                recursiveLS
Introduced in R2015b
                                                                  1-1131
1   Functions
          recursiveOE
          Create System object for online parameter estimation of Output-Error polynomial model
          Syntax
          obj   =   recursiveOE
          obj   =   recursiveOE(Orders)
          obj   =   recursiveOE(Orders,B0,F0)
          obj   =   recursiveOE( ___ ,Name,Value)
          Description
          Use recursiveOE command for parameter estimation with real-time data. If all data necessary for
          estimation is available at once, and you are estimating a time-invariant model, use the offline
          estimation command, oe.
          obj = recursiveOE creates a System object for online parameter estimation of a default single-
          input-single output (SISO) Output-Error model structure on page 1-1143. The default model structure
          has polynomials of order 1 and initial polynomial coefficient values eps.
          After creating the object, use the step command to update model parameter estimates using
          recursive estimation algorithms and real-time data.
          obj = recursiveOE(Orders,B0,F0) specifies the polynomial orders and initial values of the
          polynomial coefficients. Specify initial values to potentially avoid local minima during estimation. If
          the initial values are small compared to the default InitialParameterCovariance property value,
          and you have confidence in your initial values, also specify a smaller
          InitialParameterCovariance.
          obj = recursiveOE( ___ ,Name,Value) specifies additional attributes of the Output-Error model
          structure and recursive estimation algorithm using one or more Name,Value pair arguments.
          Object Description
          recursiveOE creates a System object for online parameter estimation of SISO Output-Error
          polynomial models using a recursive estimation algorithm.
          A System object is a specialized MATLAB object designed specifically for implementing and
          simulating dynamic systems with inputs that change over time. System objects use internal states to
          store past behavior, which is used in the next computational step.
          After you create a System object, you use commands to process data or obtain information from or
          about the object. System objects use a minimum of two commands to process data — a constructor to
          create the object and the step command to update object parameters using real-time data. This
          separation of declaration from execution lets you create multiple, persistent, reusable objects, each
          with different settings.
1-1132
                                                                                                recursiveOE
You can use the following commands with the online estimation System objects in System
Identification Toolbox:
Command                                               Description
step                                                  Update model parameter estimates using
                                                      recursive estimation algorithms and real-time
                                                      data.
Use the recursiveOE command to create an online estimation System object. Then estimate the
Output-Error polynomial model parameters (B and F) and output using the step command with
incoming input and output data, u and y.
[B,F,EstimatedOutput] = step(obj,y,u)
Examples
Create a System object for online parameter estimation of a Output-Error polynomial model using
recursive estimation algorithms.
obj = recursiveOE;
The Output-Error model has a default structure with polynomials of order 1 and initial polynomial
coefficient values, eps.
Load the estimation data. In this example, use a static data set for illustration.
                                                                                                   1-1133
1   Functions
          for i = 1:numel(input)
          [B,F,EstimatedOutput] = step(obj,output(i),input(i));
          end
obj.F
ans = 1×2
1.0000 -0.7618
obj.ParameterCovariance
ans = 2×2
                0.0024    0.0002
                0.0002    0.0001
EstimatedOutput
EstimatedOutput = -4.1866
Create System Object for Output-Error Model With Known Orders and Delays
          nb = 1;
          nf = 2;
          nk = 1;
          Create a System object for online estimation of Output-Error polynomial model with the specified
          orders and delays.
Create System Object for Output-Error Model With Known Initial Parameters
1-1134
                                                                                              recursiveOE
nb = 1;
nf = 2;
nk = 1;
Create a System object for online estimation of Output-Error model with known initial polynomial
coefficients.
B0 = [0 1];
F0 = [1 0.7 0.8];
obj = recursiveOE([nb nf nk],B0,F0);
obj.InitialParameterCovariance = 0.1;
InitialParameterCovariance represents the uncertainty in your guess for the initial parameters.
Typically, the default InitialParameterCovariance (10000) is too large relative to the parameter
values. This results in initial guesses being given less importance during estimation. If you have
confidence in the initial parameter guesses, specify a smaller initial parameter covariance.
Create a System object that uses the unnormalized gradient algorithm for online parameter
estimation of an Output-Error model.
Input Arguments
Orders — Model orders and delays
1-by-3 vector of integers
Model orders and delays of a Output-Error polynomial model on page 1-1143, specified as a 1-by-3
vector of integers, [nb nf nk].
Initial value of polynomial coefficients, specified as row vectors of real values with elements in order
of ascending powers of q-1.
• B0 — Initial guess for the coefficients of the polynomial B(q), specified as a 1-by-(nb+nk) vector
  with nk leading zeros.
• F0 — Initial guess for the coefficients of the polynomial F(q), specified as a 1-by-(nf+1) vector
  with 1 as the first element.
                                                                                                 1-1135
1   Functions
                The coefficients in F0 must define a stable discrete-time polynomial with roots within a unit disk.
                For example,
                F0 = [1 0.5 0.5];
                all(abs(roots(F0))<1)
ans =
Specifying as [], uses the default value of eps for the polynomial coefficients.
          Note If the initial parameter values are much smaller than InitialParameterCovariance, these
          initial values are given less importance during estimation. Specify a smaller initial parameter
          covariance if you have high confidence in the initial parameter values. This statement applies only for
          infinite-history estimation. Finite-history estimation does not use InitialParameterCovariance.
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
          Use Name,Value arguments to specify writable properties on page 1-1136 of recursiveOE System
          object during object creation. For example, obj = recursiveOE([1 2
          1],'EstimationMethod','Gradient') creates a System object to estimate a Output-Error
          polynomial model using the 'Gradient' recursive estimation algorithm.
          Properties
          recursiveOE System object properties consist of read-only and writable properties. The writable
          properties are tunable and nontunable properties. The nontunable properties cannot be changed
          when the object is locked, that is, after you use the step command.
          Use Name,Value arguments to specify writable properties of recursiveOE objects during object
          creation. After object creation, use dot notation to modify the tunable properties.
          obj = recursiveOE;
          obj.ForgettingFactor = 0.99;
          Estimated coefficients of polynomial B(q), returned as a vector of real values specified in order of
          ascending powers of q-1.
          B is a read-only property and is initially empty after you create the object. It is populated after you
          use the step command for online parameter estimation.
          Estimated coefficients of polynomial F(q), returned as a vector of real values specified in order of
          ascending powers of q-1.
1-1136
                                                                                               recursiveOE
F is a read-only property and is initially empty after you create the object. It is populated after you
use the step command for online parameter estimation.
InitialB
Initial values for the coefficients of polynomial B(q) of order nb-1, specified as a row vector of length
nb+nk, with nk leading zeros. nk is the input-output delay. Specify the coefficients in order of
ascending powers of q-1.
If the initial guesses are much smaller than the default InitialParameterCovariance, 10000, the
initial guesses are given less importance during estimation. In that case, specify a smaller initial
parameter covariance.
InitialB is a tunable property. You can change it when the object is in a locked state.
Default: [0 eps]
InitialF
Initial values for the coefficients of polynomial F(q) of order nf, specified as a row vector of length nf
+1, with 1 as the first element. Specify the coefficients in order of ascending powers of q-1.
The coefficients in InitialF must define a stable discrete-time polynomial with roots within a unit
circle. For example,
ans =
If the initial guesses are much smaller than the default InitialParameterCovariance, 10000, the
initial guesses are given less importance during estimation. In that case, specify a smaller initial
parameter covariance.
InitialF is a tunable property. You can change it when the object is in a locked state.
Default: [1 eps]
InitialOutputs
Initial values of the measured outputs buffer in finite-history estimation, specified as 0 or as a (W+nf)-
by-1 vector, where W is the window length and nf is the order of the polynomial F(q) that you specify
when constructing the object.
The InitialOutputs property provides a means of controlling the initial behavior of the algorithm.
When InitialOutputs is set to 0, the object populates the buffer with zeros.
If the initial buffer is set to 0 or does not contain enough information, you see a warning message
during the initial phase of your estimation. The warning should clear after a few cycles. The number
of cycles it takes for sufficient information to be buffered depends upon the order of your polynomials
and your input delays. If the warning persists, you should evaluate the content of your signals.
                                                                                                  1-1137
1   Functions
          InitialOutputs is a tunable property. You can change InitialOutputs when the object is in a
          locked state.
Default: 0
InitialInputs
          Initial values of the inputs in the finite history window, specified as 0 or as a (W+nb+nk-1)-by-1
          vector, where W is the window length. nb is the vector of B(q) polynomial orders and nk is vector of
          input delays that you specify when constructing the recursiveOE object.
The InitialInputs property provides a means of controlling the initial behavior of the algorithm.
When the InitialInputs is set to 0, the object populates the buffer with zeros.
          If the initial buffer is set to 0 or does not contain enough information, you see a warning message
          during the initial phase of your estimation. The warning should clear after a few cycles. The number
          of cycles it takes for sufficient information to be buffered depends upon the order of your polynomials
          and your input delays. If the warning persists, you should evaluate the content of your signals.
          InitialInputs is a tunable property. You can change InitialInputs when the object is in a
          locked state.
Default: 0
ParameterCovariance
          The interpretation of P depends on your settings for the History and EstimationMethod
          properties.
• If History is Infinite, then your EstimationMethod selection results in one of the following:
          ParameterCovariance is a read-only property and is initially empty after you create the object. It is
          populated after you use the step command for online parameter estimation.
1-1138
                                                                                              recursiveOE
InitialParameterCovariance
• Real positive scalar, α — Covariance matrix is an N-by-N diagonal matrix, with α as the diagonal
  elements. N is the number of parameters to be estimated.
• Vector of real positive scalars, [α1,...,αN] — Covariance matrix is an N-by-N diagonal matrix, with
  [α1,...,αN] as the diagonal elements.
• N-by-N symmetric positive-definite matrix.
Default: 10000
EstimationMethod
Recursive estimation algorithm used for online estimation of model parameters, specified as one of
the following values:
Forgetting factor and Kalman filter algorithms are more computationally intensive than gradient and
unnormalized gradient methods. However, they have better convergence properties. For information
about these algorithms, see “Recursive Algorithms for Online Parameter Estimation”.
These methods all use an infinite data history, and are available only when History is 'Infinite'.
EstimationMethod is a nontunable property. You cannot change it during execution, that is, after
the object is locked using the step command.
ForgettingFactor
Forgetting factor, λ, relevant for parameter estimation, specified as a scalar in the range (0,1].
Suppose that the system remains approximately constant over T0 samples. You can choose λ such
that:
            1
    T0 =
           1−λ
                                                                                                     1-1139
1   Functions
          • Setting λ < 1 implies that past measurements are less significant for parameter estimation and
            can be “forgotten”. Set λ < 1 to estimate time-varying coefficients.
ForgettingFactor is a tunable property. You can change it when the object is in a locked state.
Default: 1
EnableAdapation
          • true or 1— The step command estimates the parameter values for that time step and updates
            the parameter values.
          • false or 0 — The step command does not update the parameters for that time step and instead
            outputs the last estimated value. You can use this option when your system enters a mode where
            the parameter values do not vary with time.
                Note If you set EnableAdapation to false, you must still execute the step command. Do not
                skip step to keep parameter values constant, because parameter estimation depends on current
                and past I/O measurements. step ensures past I/O data is stored, even when it does not update
                the parameters.
EnableAdapation is a tunable property. You can change it when the object is in a locked state.
Default: true
DataType
          Setting DataType to 'single' saves memory, but leads to loss of precision. Specify DataType
          based on the precision required by the target processor where you will deploy generated code.
          DataType is a nontunable property. It can only be set during object construction using Name,Value
          arguments and cannot be changed afterward.
Default: 'double'
ProcessNoiseCovariance
          • Real nonnegative scalar, α — Covariance matrix is an N-by-N diagonal matrix, with α as the
            diagonal elements.
          • Vector of real nonnegative scalars, [α1,...,αN] — Covariance matrix is an N-by-N diagonal matrix,
            with [α1,...,αN] as the diagonal elements.
1-1140
                                                                                             recursiveOE
Kalman filter algorithm treats the parameters as states of a dynamic system and estimates these
parameters using a Kalman filter. ProcessNoiseCovariance is the covariance of the process noise
acting on these parameters. Zero values in the noise covariance matrix correspond to estimating
constant coefficients. Values larger than 0 correspond to time-varying parameters. Use large values
for rapidly changing parameters. However, the larger values result in noisier parameter estimates.
ProcessNoiseCovariance is a tunable property. You can change it when the object is in a locked
state.
Default: 0.1
AdaptationGain
Adaptation gain, γ, used in gradient recursive estimation algorithms, specified as a positive scalar.
Specify a large value for AdaptationGain when your measurements have a high signal-to-noise
ratio.
AdaptationGain is a tunable property. You can change it when the object is in a locked state.
Default: 1
NormalizationBias
The normalized gradient algorithm divides the adaptation gain at each step by the square of the two-
norm of the gradient vector. If the gradient is close to zero, this can cause jumps in the estimated
parameters. NormalizationBias is the term introduced in the denominator to prevent these jumps.
Increase NormalizationBias if you observe jumps in estimated parameters.
NormalizationBias is a tunable property. You can change it when the object is in a locked state.
Default: eps
History
Data history type defining which type of recursive algorithm you use, specified as:
• 'Infinite' — Use an algorithm that aims to minimize the error between the observed and
  predicted outputs for all time steps from the beginning of the simulation.
• 'Finite' — Use an algorithm that aims to minimize the error between the observed and
  predicted outputs for a finite number of past time steps.
                                                                                                 1-1141
1   Functions
          Algorithms with infinite history aim to produce parameter estimates that explain all data since the
          start of the simulation. These algorithms still use a fixed amount of memory that does not grow over
          time. The object provides multiple algorithms of the 'Infinite' History type. Specifying this
          option activates the EstimationMethod property with which you specify an algorithm.
          Algorithms with finite history aim to produce parameter estimates that explain only a finite number of
          past data samples. This method is also called sliding-window estimation. The object provides one
          algorithm of the 'Finite' type. Specifying this option activates the WindowLength property that
          sizes the window.
          For more information on recursive estimation methods, see “Recursive Algorithms for Online
          Parameter Estimation”.
          History is a nontunable property. It can be set only during object construction using Name,Value
          arguments and cannot be changed afterward.
Default: 'Infinite'
WindowLength
          Window size determining the number of time samples to use for the sliding-window estimation
          method, specified as a positive integer. Specify WindowLength only when History is Finite.
          Choose a window size that balances estimation performance with computational and memory burden.
          Sizing factors include the number and time variance of the parameters in your model. Always specify
          Window Length in samples, even if you are using frame-based input processing.
          Suitable window length is independent of whether you are using sample-based or frame-based input
          processing (see InputProcessing). However, when using frame-based processing, your window
          length must be greater than or equal to the number of samples (time steps) contained in the frame.
          WindowLength is a nontunable property. It can be set only during object construction using
          Name,Value arguments and cannot be changed afterward.
Default: 200
InputProcessing
Option for sample-based or frame-based input processing, specified as a character vector or string.
          Your InputProcessing specification impacts the dimensions for the input and output signals when
          using the step command:
[theta,EstimatedOutput] = step(obj,y,u)
• Sample-based
1-1142
                                                                                        recursiveOE
InputProcessing is a nontunable property. It can be set only during object construction using
Name,Value arguments and cannot be changed afterward.
Default: 'Sample-based'
Output Arguments
obj — System object for online parameter estimation of Output-Error polynomial model
recursiveOE System object
System object for online parameter estimation of SISO Output-Error polynomial model, returned as a
recursiveOE System object. This object is created using the specified model orders and properties.
Use step command to estimate the coefficients of the Output-Error model polynomials. You can then
access the estimated coefficients and parameter covariance using dot notation. For example, type
obj.B to view the estimated B polynomial coefficients.
More About
Output-Error Model Structure
             B(q)
    y(t) =        u(t − nk) + e(t)
             F(q)
Tips
• Starting in R2016b, instead of using the step command to update model parameter estimates,
  you can call the System object with input arguments, as if it were a function. For example,
  [B,F,EstimatedOutput] = step(obj,y,u) and [B,F,EstimatedOutput] = obj(y,u)
  perform equivalent operations.
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
                                                                                           1-1143
1   Functions
• For limitations, see “Generate Code for Online Parameter Estimation in MATLAB”.
          See Also
          Recursive Polynomial Model Estimator | clone | isLocked | oe | recursiveAR | recursiveARMA |
          recursiveARMAX | recursiveARX | recursiveBJ | recursiveLS | release | reset | step
          Topics
          “Perform Online Parameter Estimation at the Command Line”
          “Validate Online Parameter Estimation at the Command Line”
          “What Is Online Estimation?”
          “Recursive Algorithms for Online Parameter Estimation”
Introduced in R2015b
1-1144
                                                                                           release
release
Unlock online parameter estimation System object
Syntax
release(obj)
Description
release(obj) unlocks the online parameter estimation System object, obj. Use release to change
nontunable properties of the object.
Note You can use release on a System object in code generated using MATLAB Coder, but once
you release its resources, you cannot use that System object again.
Examples
Create a System object™ for online estimation of an ARMAX model with default properties.
obj = recursiveARMAX;
[A,B,C,EstimatedOutput] = step(obj,1,1);
L = isLocked(obj)
L = logical
   1
release(obj)
L = isLocked(obj)
L = logical
   0
                                                                                           1-1145
1   Functions
          Input Arguments
          obj — System object for online parameter estimation
          recursiveAR object | recursiveARMA object | recursiveARX object | recursiveARMAX object |
          recursiveOE object | recursiveBJ object | recursiveLS object
System object for online parameter estimation, created using one of the following commands:
          • recursiveAR
          • recursiveARMA
          • recursiveARX
          • recursiveARMAX
          • recursiveOE
          • recursiveBJ
          • recursiveLS
          See Also
          clone | isLocked | recursiveAR | recursiveARMA | recursiveARMAX | recursiveARX |
          recursiveBJ | recursiveLS | recursiveOE | reset | step
          Topics
          “Perform Online Parameter Estimation at the Command Line”
          “Validate Online Parameter Estimation at the Command Line”
          “What Is Online Estimation?”
Introduced in R2015b
1-1146
                                                                                               repsys
repsys
Replicate and tile models
Syntax
rsys = repsys(sys,[M N])
rsys = repsys(sys,N)
rsys = repsys(sys,[M N S1,...,Sk])
Description
rsys = repsys(sys,[M N]) replicates the model sys into an M-by-N tiling pattern. The resulting
model rsys has size(sys,1)*M outputs and size(sys,2)*N inputs.
rsys = repsys(sys,[M N S1,...,Sk]) replicates and tiles sys along both I/O and array
dimensions to produce a model array. The indices S specify the array dimensions. The size of the
array is [size(sys,1)*M, size(sys,2)*N, size(sys,3)*S1, ...].
Input Arguments
sys
Model to replicate.
Output Arguments
rsys
If you provide array dimensions S1,...,Sk, rsys is an array of dynamic systems which each have
size(sys,1)*M outputs and size(sys,2)*N inputs. The size of rsys is [size(sys,1)*M,
size(sys,2)*N, size(sys,3)*S1, ...].
Examples
                                                                                              1-1147
1   Functions
sys =
                  2
                -----
                s + 3
          Replicate the SISO transfer function to create a MIMO transfer function that has three inputs and
          two outputs.
rsys =
                          2
                 2:     -----
                        s + 3
                          2
                 2:     -----
                        s + 3
                          2
                 2:     -----
                        s + 3
1-1148
                                                                                                    repsys
Replicate the transfer function into a 3-by-4 array of two-input, one-output transfer functions.
size(rsys)
Tips
rsys = repsys(sys,N) produces the same result as rsys = repsys(sys,[N N]). To produce a
diagonal tiling, use rsys = sys*eye(N).
See Also
append
Introduced in R2010b
                                                                                                   1-1149
1   Functions
          resample
          Resample time-domain data by decimation or interpolation (requires Signal Processing Toolbox
          software)
          Syntax
          resample(data,P,Q)
          resample(data,P,Q,order)
          Description
          resample(data,P,Q) resamples data such that the data is interpolated by a factor P and then
          decimated by a factor Q. resample(z,1,Q) results in decimation by a factor Q.
          Input Arguments
          data
                 Name of time-domain iddata object. Can be input-output or time-series data.
Default: 10
Examples
          Increase the sampling rate of data by a factor of 1.5 and compare the resampled and the original data
          signals.
1-1150
                                                                                            resample
Algorithms
If you have installed the Signal Processing Toolbox software, resample calls the Signal Processing
Toolbox resample function. The algorithm takes into account the intersample characteristics of the
input signal, as described by data.InterSample.
See Also
idresamp
                                                                                            1-1151
1   Functions
          reset
          Reset online parameter estimation System object
          Syntax
          reset(obj)
          Description
          reset(obj) resets the states of a locked online parameter estimation System object, obj, to initial
          values and leaves the object locked. The states of the object are the estimated parameters and
          parameter covariance. Use reset if you are not satisfied with the estimation or if your system
          changes modes.
Examples
Load the estimation data. For this example, use a static data set for illustration.
          for i = 1:numel(input)
            [B,F,EstimatedOutput] = step(obj,output(i),input(i));
          end
obj
          obj =
            recursiveOE with properties:
                                         B:      [0 2.0014]
                                         F:      [1 -0.7639]
                                  InitialB:      [0 0.5000]
                                  InitialF:      [1 0.8000]
                       ParameterCovariance:      [2x2 double]
                InitialParameterCovariance:      [2x2 double]
                          EstimationMethod:      'ForgettingFactor'
                          ForgettingFactor:      1
                          EnableAdaptation:      true
1-1152
                                                                                                reset
                         History: 'Infinite'
                 InputProcessing: 'Sample-based'
                        DataType: 'double'
reset(obj)
The estimated parameters, B and F, and parameter covariance, ParameterCovariance are reset to
the initial values.
obj
obj =
  recursiveOE with properties:
                               B:   [0 0.5000]
                               F:   [1 0.8000]
                        InitialB:   [0 0.5000]
                        InitialF:   [1 0.8000]
             ParameterCovariance:   [2x2 double]
      InitialParameterCovariance:   [2x2 double]
                EstimationMethod:   'ForgettingFactor'
                ForgettingFactor:   1
                EnableAdaptation:   true
                         History:   'Infinite'
                 InputProcessing:   'Sample-based'
                        DataType:   'double'
Input Arguments
obj — System object for online parameter estimation
recursiveAR object | recursiveARMA object | recursiveARX object | recursiveARMAX object |
recursiveOE object | recursiveBJ object | recursiveLS object
System object for online parameter estimation, created using one of the following commands:
                                       C — Reset to InitialC
recursiveARX                           A — Reset to InitialA
                                       B — Reset to InitialB
recursiveARMAX                         A — Reset to InitialA
B — Reset to InitialB
C — Reset to InitialC
                                                                                              1-1153
1   Functions
                                               F — Reset to InitialF
           recursiveBJ                         B — Reset to InitialB
C — Reset to InitialC
D — Reset to InitialD
                                               F — Reset to InitialF
           recursiveLS                         Parameters — Reset to InitialParameters
          See Also
          clone | isLocked | recursiveAR | recursiveARMA | recursiveARMAX | recursiveARX |
          recursiveBJ | recursiveLS | recursiveOE | release | step
          Topics
          “Perform Online Parameter Estimation at the Command Line”
          “Validate Online Parameter Estimation at the Command Line”
          “What Is Online Estimation?”
Introduced in R2015b
1-1154
                                                                                              reshape
reshape
Change shape of model array
Syntax
sys = reshape(sys,s1,s2,...,sk)
sys = reshape(sys,[s1 s2 ... sk])
Description
sys = reshape(sys,s1,s2,...,sk) (or, equivalently, sys = reshape(sys,[s1 s2 ...
sk])) reshapes the LTI array sys into an s1-by-s2-by-...-by-sk model array. With either syntax, there
must be s1*s2*...*sk models in sys to begin with.
Examples
sys = rss(4,1,1,2,3);
size(sys)
sys1 = reshape(sys,6,1);
size(sys1)
See Also
ndims | size
                                                                                              1-1155
1   Functions
          resid
          Compute and test residuals
          Syntax
          resid(Data,sys)
          resid(Data,sys,Linespec)
          resid(Data,sys1,...,sysn)
          resid(Data,sys1,Linespec1,...,sysn,Linespecn)
[E,R] = resid(Data,sys)
          Description
          resid(Data,sys) computes the 1-step-ahead prediction errors (residuals) for an identified model,
          sys, and plots residual-input dynamics as one of the following, depending on the data inData:
          • For time-domain data, resid plots the autocorrelation of the residuals and the cross-correlation of
            the residuals with the input signals. The correlations are generated for lags -25 to 25. To specify a
            different maximum lag value, use residOptions. The 99% confidence region marking
            statistically insignificant correlations displays as a shaded region around the X-axis.
          • For frequency-domain data, resid plots a bode plot of the frequency response from the input
            signals to the residuals. The 99% confidence region marking statistically insignificant response is
            shown as a region around the X-axis.
          To change display options, right-click the plot to access the context menu. For more details about the
          menu, see “Tips” on page 1-1164.
          resid( ___ ,Options) specifies additional residual calculation options. Use Options with any of
          the previous syntaxes.
resid( ___ ,Type) specifies the plot type. Use Type with any of the previous syntaxes.
Examples
1-1156
                                                                                                    resid
load iddata1
data = z1;
Plot the autocorrelation of the residuals and cross-correlation between the residuals and the inputs.
resid(data,sys)
The correlations are calculated until the default maximum lag, 25. The 99% confidence region
marking statistically insignificant correlations displays as a shaded region around the X-axis.
data2 = fft(data);
Compute the residuals for identified model, sys, and the frequency-domain data. Plot the residual
response using red crosses.
resid(data2,sys,'rx')
                                                                                                  1-1157
1   Functions
          For frequency-domain data, resid plots the Bode plot showing frequency response from the input to
          the residuals.
load iddata1
sys2 = tfest(z1,2);
resid(z1,sys1,'b',sys2,'r')
1-1158
                                                                                                 resid
The cross-correlation between residuals of sys2 and the inputs lie in the 99% confidence band for all
lags.
load iddata1
opt = residOptions('MaxLag',35);
resid(z1,sys,opt,'ir')
                                                                                              1-1159
1   Functions
          Calculate the residuals and their autocorrelations and cross-correlations with inputs.
          [E,R] = resid(z7,sys);
          E is an iddata object with the residuals as output data and the inputs of validation data (z7) as input
          data. You can use E to identify error models and analyze the error dynamics.
1-1160
                                                                                                resid
plot(E)
Estimate impulse response between inputs and residuals. Plot them with a 3 standard deviation
confidence region.
I = impulseest(E);
showConfidence(impulseplot(I,20),3)
                                                                                           1-1161
1   Functions
          Input Arguments
          Data — Validation data
          iddata object
          Validation input-output data, specified as an iddata object. Data can have multiple input-output
          channels. When sys is linear, Data is time-domain or frequency-domain. When sys is nonlinear,
          Data is time-domain.
          System used for computing residuals, specified as an identified linear or nonlinear model.
          Example: idpoly
          Line style, marker symbol, and color, specified as a character vector. For more information, see plot
          in the MATLAB documentation. When Type is specified as 'corr', only the line style is used.
          Example: 'Linespec','kx'
1-1162
                                                                                                  resid
• 'corr' — Plots the autocorrelation of the residuals, e, and the cross-correlation of the residuals
  with the input signals, u. The correlations are generated for lags -25 to 25. Use residOptions to
  specify a different maximum lag value. The 99% confidence region marking statistically
  insignificant correlations is also shown as a shaded region around the X-axis. The computation of
  the confidence region is done assuming e to be white and independent of u.
   'corr' is default for time-domain data. This plot type is not available for frequency-domain data.
• 'ir' — Plots the impulse response up to lag 25 of a system from the input to the residuals. The
  impulseest command first estimates the impulse response model with e as output data and u as
  inputs. Then impulseest calculates the impulse response of the estimated model. The 99%
  confidence region marking statistically insignificant response displays as a shaded region. A low
  magnitude indicates a reliable model.
Output Arguments
E — Model residuals
iddata object
Model residuals, returned as an iddata object. The residuals are stored in E.OutputData, and the
inputs are stored in E.InputData. Use E to build models that describe the dynamics from the inputs
to the residuals. The dynamics are negligible if sys is a reliable identified model.
   For example, for a two-output, single-input model, Z = [e1,e2,u1]. Where, e1 is the residual of
   the first output, e2 is the residual of the second output, and u1 is the input. R is a 26-by-3-by-3
   matrix, where:
                                                                                               1-1163
1   Functions
          Tips
          • Right-clicking the plot opens the context menu, where you can access the following options:
                • Systems — Select systems to view the residual correlation or response plots. By default, all
                  systems are plotted.
                • Show Confidence Region — View the 99% confidence region marking statistically
                  insignificant correlations. Applicable only for the correlation plots.
                • Data Experiment — For multi-experiment data only. Toggle between data from different
                  experiments.
                • Characteristics — View data characteristics. Not applicable for correlation plots.
1-1164
                                                                                                  resid
References
[1] Ljung, L. System Identification: Theory for the User. Upper Saddle River, NJ: Prentice-Hall PTR,
        1999, Section 16.6.
See Also
compare | predict | residOptions | sim | simsd
Topics
“What Is Residual Analysis?”
                                                                                               1-1165
1   Functions
          residOptions
          Option set for resid
          Syntax
          opt = residOptions
          opt = residOptions(Name,Value)
          Description
          opt = residOptions creates the default option set for resid. Use dot notation to customize the
          option set, if needed.
          opt = residOptions(Name,Value) creates an option set with options specified by one or more
          Name,Value pair arguments. The options that you do not specify retain their default value.
Examples
opt = residOptions;
opt.MaxLag = 35;
Create an option set for resid that specifies initial condition as zero.
opt = residOptions('InitialCondition','z');
          Input Arguments
          Name-Value Pair Arguments
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
          Example: residOptions('InitialCondition','e')
1-1166
                                                                                               residOptions
Maximum positive lag for residual correlation and impulse response calculations, specified as the
comma-separated pair consisting of 'MaxLag' and a positive integer.
   For nonlinear grey-box models, only those initial states i that are designated as free in the model
   (sys.InitialStates(i).Fixed = false) are estimated. To estimate all the states of the
   model, first specify all the Nx states of the idnlgrey model sys as free.
   for i = 1:Nx
   sys.InitialStates(i).Fixed = false;
   end
   Similarly, to fix all the initial states to values specified in sys.InitialStates, first specify all
   the states as fixed in the sys.InitialStates property of the nonlinear grey-box model.
• 'd' — Similar to 'e', but absorbs nonzero delays into the model coefficients. The delays are first
  converted to explicit model states, and the initial values of those states are also estimated and
  returned.
       Field       Description
       Input       Input history, specified as a matrix with Nu columns, where Nu is the number of
                   input channels. For time series models, use []. The number of rows must be
                   greater than or equal to the model order.
       Output      Output history, specified as a matrix with Ny columns, where Ny is the number of
                   output channels. The number of rows must be greater than or equal to the model
                   order.
   For multi-experiment data, configure the initial conditions separately for each experiment by
   specifying InitialCondition as a structure array with Ne elements. To specify the same initial
   conditions for all experiments, use a single structure.
   The software uses data2state to map the historical data to states. If your model is not idss,
   idgrey, idnlgrey, or idnlarx, the software first converts the model to its state-space
   representation and then maps the data to states. If conversion of your model to idss is not
   possible, the estimated states are returned empty.
                                                                                                  1-1167
1   Functions
          • x0obj — Specification object created using idpar. Use this object for discrete-time state-space
            (idss and idgrey) and nonlinear grey-box (idnlgrey) models only. Use x0obj to impose
            constraints on the initial states by fixing their value or specifying minimum or maximum bounds.
          Removal of offset from time-domain input data during estimation, specified as the comma-separated
          pair consisting of 'InputOffset' and one of the following:
          • A column vector of positive integers of length Nu, where Nu is the number of inputs.
          • [] — Indicates no offset.
          • Nu-by-Ne matrix — For multi-experiment data, specify InputOffset as an Nu-by-Ne matrix. Nu
            is the number of inputs, and Ne is the number of experiments.
Each entry specified by InputOffset is subtracted from the corresponding input data.
          Removal of offset from time-domain output data during estimation, specified as the comma-separated
          pair consisting of 'OutputOffset' and one of the following:
Each entry specified by OutputOffset is subtracted from the corresponding output data.
          Weight of output for initial condition estimation, specified as the comma-separated pair consisting of
          'OutputWeight' and one of the following:
          • [] — No weighting is used. This option is the same as using eye(Ny) for the output weight. Ny is
            the number of outputs.
          • 'noise' — Inverse of the noise variance stored with the model.
          • Matrix of doubles — A positive semidefinite matrix of dimension Ny-by-Ny. Ny is the number of
            outputs.
          Output Arguments
          opt — Option set for resid
          residOptions option set
          See Also
          resid
1-1168
                       residOptions
Introduced in R2016a
                          1-1169
1   Functions
          residual
          Return measurement residual and residual covariance when using extended or unscented Kalman
          filter
          Syntax
          [Residual,ResidualCovariance] = residual(obj,y)
          [Residual,ResidualCovariance] = residual(obj,y,Um1,...,Umn)
          Description
          The residual command returns the difference between the actual and predicted measurements for
          extendedKalmanFilter and unscentedKalmanFilter objects. Viewing the residual provides a
          way for you to validate the performance of the filter. Residuals, also known as innovations, quantify
          the prediction error and drive the correction step in the extended and unscented Kalman filter update
          sequence. When using correct and predict to update the estimated Kalman filter state, use the
          residual command immediately before using the correct command.
          Use this syntax if the measurement function h that you specified in obj.MeasurementFcn has one of
          the following forms:
          Here, y(k), x(k), and v(k) are the measured output, states, and measurement noise of the system
          at time step k. The only inputs to h are the states and measurement noise.
Use this syntax if the measurement function h has one of the following forms:
1-1170
                                                                                                    residual
Examples
Estimate the states of a van der Pol oscillator using an extended Kalman filter algorithm and
measured output data. The oscillator has two states and one output.
Create an extended Kalman filter object for the oscillator. Use previously written and saved state
transition and measurement functions, vdpStateFcn.m and vdpMeasurementFcn.m. These
functions describe a discrete-approximation to a van der Pol oscillator with the nonlinearity
parameter mu equal to 1. The functions assume additive process and measurement noise in the
system. Specify the initial state values for the two states as [1;0]. This is the guess for the state value
at initial time k, based on knowledge of system outputs until time k-1, x[k k − 1].
obj = extendedKalmanFilter(@vdpStateFcn,@vdpMeasurementFcn,[1;0]);
Load the measured output data y from the oscillator. In this example, use simulated static data for
illustration. The data is stored in the vdp_data.mat file.
load vdp_data.mat y
Specify the process noise and measurement noise covariances of the oscillator.
obj.ProcessNoise = 0.01;
obj.MeasurementNoise = 0.16;
residBuf = [];
xcorBuf = [];
xpredBuf = [];
Implement the extended Kalman filter algorithm to estimate the states of the oscillator by using the
correct and predict commands. You first correct x[k k − 1] using measurements at time k to get
x[k k]. Then, you predict the state value at the next time step x[k + 1 k] using x[k k], the state
estimate at time step k that is estimated using measurements until time k.
To simulate real-time data measurements, use the measured data one time step at a time. Compute
the residual between the predicted and actual measurement to assess how well the filter is
performing and converging. Computing the residual is an optional step. When you use residual,
place the command immediately before the correct command. If the prediction matches the
measurement, the residual is zero.
After you perform the real-time commands for the time step, buffer the results so that you can plot
them after the run is complete.
for k = 1:size(y)
    [Residual,ResidualCovariance] = residual(obj,y(k));
    [CorrectedState,CorrectedStateCovariance] = correct(obj,y(k));
    [PredictedState,PredictedStateCovariance] = predict(obj);
      residBuf(k,:) = Residual;
      xcorBuf(k,:) = CorrectedState';
      xpredBuf(k,:) = PredictedState';
                                                                                                   1-1171
1   Functions
end
          When you use the correct command, obj.State and obj.StateCovariance are updated with
          the corrected state and state estimation error covariance values for time step k, CorrectedState
          and CorrectedStateCovariance. When you use the predict command, obj.State and
          obj.StateCovariance are updated with the predicted values for time step k+1, PredictedState
          and PredictedStateCovariance. When you use the residual command, you do not modify any
          obj properties.
          In this example, you used correct before predict because the initial state value was x[k k − 1], a
          guess for the state value at initial time k based on system outputs until time k-1. If your initial state
          value is x[k − 1 k − 1], the value at previous time k-1 based on measurements until k-1, then use the
          predict command first. For more information about the order of using predict and correct, see
          “Using predict and correct Commands” on page 1-201.
          plot(xcorBuf(:,1), xcorBuf(:,2))
          title('Estimated States')
          Plot the actual measurement, the corrected estimated measurement, and the residual. For the
          measurement function in vdpMeasurementFcn, the measurement is the first state.
          M = [y,xcorBuf(:,1),residBuf];
          plot(M)
1-1172
                                                                                                 residual
grid on
title('Actual and Estimated Measurements, Residual')
legend('Measured','Estimated','Residual')
The estimate tracks the measurement closely. After the initial transient, the residual remains
relatively small throughout the run.
Consider a nonlinear system with input u whose state x and measurement y evolve according to the
following state transition and measurement equations:
                                2
    y[k] = x[k] + 2 * u[k] + v[k]
The process noise w of the system is additive while the measurement noise v is nonadditive.
Create the state transition function and measurement function for the system. Specify the functions
with an additional input u.
f = @(x,u)(sqrt(x+u));
h = @(x,v,u)(x+2*u+v^2);
                                                                                                 1-1173
1   Functions
          f and h are function handles to the anonymous functions that store the state transition and
          measurement functions, respectively. In the measurement function, because the measurement noise
          is nonadditive, v is also specified as an input. Note that v is specified as an input before the
          additional input u.
          Create an extended Kalman filter object for estimating the state of the nonlinear system using the
          specified functions. Specify the initial value of the state as 1 and the measurement noise as
          nonadditive.
obj = extendedKalmanFilter(f,h,1,'HasAdditiveMeasurementNoise',false);
obj.MeasurementNoise = 0.01;
          You can now estimate the state of the system using the predict and correct commands. You pass
          the values of u to predict and correct, which in turn pass them to the state transition and
          measurement functions, respectively.
Correct the state estimate with measurement y[k]=0.8 and input u[k]=0.2 at time step k.
correct(obj,0.8,0.2)
predict(obj,0.2)
Retrieve the error, or residual, between the prediction and the measurement.
          Input Arguments
          obj — Extended or unscented Kalman filter
          extendedKalmanFilter object | unscentedKalmanFilter object
Extended or unscented Kalman filter, created using one of the following commands:
          Measured system output at the current time step, specified as an N-element vector, where N is the
          number of measurements.
          Additional input arguments to the measurement function of the system, specified as input arguments
          of any type. The measurement function h is specified in the MeasurementFcn or
          MeasurementLikelihoodFcn property of obj. If the function requires input arguments in addition
          to the state and measurement noise values, you specify these inputs in the residual command
1-1174
                                                                                                residual
syntax. The residual command passes these inputs to the measurement or the measurement
likelihood function to calculate estimated outputs. You can specify multiple arguments.
For instance, suppose that your measurement or measurement likelihood function calculates the
estimated system output y using system inputs u and current time k, in addition to the state x. The
Um1 and Um2 terms are therefore u(k) and k. These inputs result in the estimated output
y(k) = h(x(k),u(k),k)
Before you perform online state estimation correction at time step k, specify these additional inputs
in the residual command syntax:
[Residual,ResidualCovariance] = residual(obj,y,u(k),k);
For an example showing how to use additional input arguments, see “Specify State Transition and
Measurement Functions with Additional Inputs” on page 1-1173.
Output Arguments
Residual — Residual between current and predicted measurement
scalar | vector
Residual covariance, returned as an N-by-N matrix where N is the number of measured outputs.
See Also
correct | extendedKalmanFilter | predict | unscentedKalmanFilter
Topics
“Nonlinear State Estimation Using Unscented Kalman Filter and Particle Filter”
“Generate Code for Online State Estimation in MATLAB”
“What Is Online Estimation?”
“Extended and Unscented Kalman Filter Algorithms for Online State Estimation”
“Validate Online State Estimation at the Command Line”
Introduced in R2019b
                                                                                               1-1175
1   Functions
          retrend
          Add offsets or trends to data signals
          Syntax
          data = retrend(data_d,T)
          Description
          data = retrend(data_d,T) returns a data object data by adding the trend information T to each
          signal in data_d. data_d is a time-domain iddata object. T is an TrendInfo object.
Examples
Subtract means from input-output signals, estimate a linear model, and retrend the simulated output.
load dryer2
data = iddata(y2,u2,0.08);
[data_d,T] = detrend(data,0);
m = arx(data_d,[2 2 1]);
y_sim = sim(m,data_d(:,[],:));
y_tot = retrend(y_sim,T);
          See Also
          TrendInfo | detrend | getTrend
          Topics
          “Handling Offsets and Trends in Data”
Introduced in R2009a
1-1176
                                                                                                    roe
roe
(To be removed) Estimate recursively output-error models (IIR-filters)
Syntax
thm = roe(z,nn,adm,adg)
[thm,yhat,P,phi,psi] = roe(z,nn,adm,adg,th0,P0,phi0,psi0)
Description
The parameters of the output-error model structure
             B(q)
    y(t) =        u(t − nk) + e(t)
             F(q)
The input-output data are contained in z, which is either an iddata object or a matrix z = [y u]
where y and u are column vectors. nn is given as
nn = [nb nf nk]
where nb and nf are the orders of the output-error model, and nk is the delay. Specifically,
Only single-input, single-output models are handled by roe. Use rpem for the multiple-input case.
The estimated parameters are returned in the matrix thm. The kth row of thm contains the
parameters associated with time k; that is, they are based on the data in the rows up to and including
row k in z.
Each row of thm contains the estimated parameters in the following order.
thm(k,:) = [b1,...,bnb,f1,...,fnf]
yhat is the predicted value of the output, according to the current model; that is, row k of yhat
contains the predicted value of y(k) based on all past data.
The actual algorithm is selected with the two arguments adg and adm. These are described under
rarx.
                                                                                               1-1177
1   Functions
          The input argument th0 contains the initial value of the parameters, a row vector consistent with the
          rows of thm. The default value of th0 is all zeros.
          The arguments P0 and P are the initial and final values, respectively, of the scaled covariance matrix
          of the parameters. The default value of P0 is 104 times the unit matrix. The arguments phi0, psi0,
          phi, and psi contain initial and final values of the data vector and the gradient vector, respectively.
          The sizes of these depend on the chosen model orders. The normal choice of phi0 and psi0 is to use
          the outputs from a previous call to roe with the same model orders. (This call could be a dummy call
          with default input arguments.) The default values of phi0 and psi0 are all zeros.
          Note that the function requires that the delay nk be larger than 0. If you want nk = 0, shift the input
          sequence appropriately and use nk = 1.
          Algorithms
          The general recursive prediction error algorithm (11.44) of Ljung (1999) is implemented. See also
          “Recursive Algorithms for Online Parameter Estimation”.
          See Also
          nkshift | recursiveOE | rpem | rplr
          Topics
          “Recursive Algorithms for Online Parameter Estimation”
1-1178
                                                                                                    rpem
rpem
Estimate general input-output models using recursive prediction-error minimization method
Syntax
thm = rpem(z,nn,adm,adg)
[thm,yhat,P,phi,psi] = rpem(z,nn,adm,adg,th0,P0,phi0,psi0)
Description
rpem is not compatible with MATLAB Coder or MATLAB Compiler™. For the special cases of ARX,
AR, ARMA, ARMAX, Box-Jenkins, and Output-Error models, use recursiveARX, recursiveAR,
recursiveARMA, recursiveARMAX, recursiveBJ, and recursiveOE, respectively.
nn = [na nb nc nd nf nk]
where na, nb, nc, nd, and nf are the orders of the model, and nk is the delay. For multiple-input
systems, nb, nf, and nk are row vectors giving the orders and delays of each input. See “What Are
Polynomial Models?” for an exact definition of the orders.
The estimated parameters are returned in the matrix thm. The kth row of thm contains the
parameters associated with time k; that is, they are based on the data in the rows up to and including
row k in z. Each row of thm contains the estimated parameters in the following order.
thm(k,:) = [a1,a2,...,ana,b1,...,bnb,...
  c1,...,cnc,d1,...,dnd,f1,...,fnf]
For multiple-input systems, the B part in the above expression is repeated for each input before the C
part begins, and the F part is also repeated for each input. This is the same ordering as in m.par.
yhat is the predicted value of the output, according to the current model; that is, row k of yhat
contains the predicted value of y(k) based on all past data.
The actual algorithm is selected with the two arguments adg and adm:
• adm = 'ff' and adg = lam specify the forgetting factor algorithm with the forgetting factor
  λ=lam. This algorithm is also known as recursive least squares (RLS). In this case, the matrix P
  has the following interpretation: R2/2 * P is approximately equal to the covariance matrix of the
  estimated parameters.R2 is the variance of the innovations (the true prediction errors e(t)).
                                                                                               1-1179
1   Functions
                adm ='ug' and adg = gam specify the unnormalized gradient algorithm with gain gamma =
                gam. This algorithm is also known as the normalized least mean squares (LMS).
                adm ='ng' and adg = gam specify the normalized gradient or normalized least mean squares
                (NLMS) algorithm. In these cases, P is not applicable.
                adm ='kf' and adg =R1 specify the Kalman filter based algorithm with R2=1 and R1 = R1. If the
                variance of the innovations e(t) is not unity but R2; then R2* P is the covariance matrix of the
                parameter estimates, while R1 = R1 /R2 is the covariance matrix of the parameter changes.
          The input argument th0 contains the initial value of the parameters, a row vector consistent with the
          rows of thm. The default value of th0 is all zeros.
          The arguments P0 and P are the initial and final values, respectively, of the scaled covariance matrix
          of the parameters. The default value of P0 is 104 times the unit matrix. The arguments phi0, psi0,
          phi, and psi contain initial and final values of the data vector and the gradient vector, respectively.
          The sizes of these depend on the chosen model orders. The normal choice of phi0 and psi0 is to use
          the outputs from a previous call to rpem with the same model orders. (This call could be a dummy
          call with default input arguments.) The default values of phi0 and psi0 are all zeros.
          Note that the function requires that the delay nk be larger than 0. If you want nk = 0, shift the input
          sequence appropriately and use nk = 1.
          Examples
          Estimate Model Parameters Using Recursive Prediction-Error Minimization
          Estimate the parameters using forgetting factor algorithm with forgetting factor 0.99.
          EstimatedParameters = rpem(z1,[na nb nc nd nf nk],'ff',0.99);
1-1180
                                                                                                rpem
compare(z1,sys);
Algorithms
The general recursive prediction error algorithm (11.44) of Ljung (1999) is implemented. See also
“Recursive Algorithms for Online Parameter Estimation”.
See Also
nkshift | recursiveAR | recursiveARMA | recursiveARMAX | recursiveARX | recursiveBJ |
recursiveOE | rplr
Topics
“What Is Online Estimation?”
“Recursive Algorithms for Online Parameter Estimation”
                                                                                             1-1181
1   Functions
          rplr
          Estimate general input-output models using recursive pseudolinear regression method
          Syntax
          thm = rplr(z,nn,adm,adg)
[thm,yhat,P,phi] = rplr(z,nn,adm,adg,th0,P0,phi0)
          Description
          rplr is not compatible with MATLAB Coder or MATLAB Compiler.
          This is a direct alternative to rpem and has essentially the same syntax. See rpem for an explanation
          of the input and output arguments.
          rplr differs from rpem in that it uses another gradient approximation. See Section 11.5 in Ljung
          (1999). Several of the special cases are well-known algorithms.
          When applied to ARMAX models, (nn = [na nb nc 0 0 nk]), rplr gives the extended least
          squares (ELS) method. When applied to the output-error structure (nn = [0 nb 0 0 nf nk]), the
          method is known as HARF in the adm = 'ff' case and SHARF in the adm = 'ng' case.
rplr can also be applied to the time-series case in which an ARMA model is estimated with:
          z = y
          nn = [na nc]
          Examples
          Estimate Output-Error Model Parameters Using Recursive Pseudolinear Regression
          na    =   0;
          nb    =   2;
          nc    =   0;
          nd    =   0;
          nf    =   2;
          nk    =   1;
load iddata1 z1
Estimate the parameters using forgetting factor algorithm, with forgetting factor 0.99.
1-1182
                                                                                    rplr
References
For more information about HARF and SHARF, see Chapter 11 in Ljung (1999).
See Also
nkshift | recursiveAR | recursiveARMA | recursiveARMAX | recursiveARX | recursiveBJ |
recursiveOE | rpem
Topics
“What Is Online Estimation?”
“Recursive Algorithms for Online Parameter Estimation”
                                                                                1-1183
1   Functions
          rsample
          Random sampling of linear identified systems
          Syntax
          sys_array = rsample(sys,N)
          sys_array = rsample(sys,N,sd)
          Description
          sys_array = rsample(sys,N) creates N random samples of the identified linear system, sys.
          sys_array contains systems with the same structure as sys, whose parameters are perturbed about
          their nominal values, based on the parameter covariance.
          sys_array = rsample(sys,N,sd) specifies the standard deviation level, sd, for perturbing the
          parameters of sys.
          Input Arguments
          sys
Identifiable system.
Default: 10
sd
Default: 1
          Output Arguments
          sys_array
          If sys is an array of models, then the size of sys_array is equal to [size(sys) N]. There are N
          randomized samples for each model in sys.
          The parameters of the samples in sys_array vary from the original identifiable model within 1
          standard deviation of their nominal values.
Examples
1-1184
                                                                         rsample
N = 20;
sys_array = rsample(sys,N);
opt = bodeoptions;
opt.PhaseMatching = 'on';
figure;
bodeplot(sys_array,'g',sys,'r.',opt)
figure;
stepplot(sys_array,'g',sys,'r.-')
                                                                         1-1185
1   Functions
          Randomly sample the estimated model. Specify the standard deviation level for perturbing the model
          parameters.
          N = 20;
          sd = 2;
          sys_array = rsample(sys,N,sd);
          figure;
          bode(sys_array);
1-1186
                                                                                          rsample
load iddata1 z1
sys = armax(z1,[2 2 2 1]);
Randomly sample the ARMAX model. Perturb the model parameters up to 2 standard deviations.
N = 20;
sd = 2;
sys_array = rsample(sys,N,sd);
                                                                                          1-1187
1   Functions
          To view the confidence region, right click the plot, and choose Characteristics > Confidence
          Region.
          Tips
          • For systems with large parameter uncertainties, the randomized systems may contain unstable
            elements. These unstable elements may make it difficult to analyze the properties of the identified
            system. Execution of analysis commands, such as step, bode, sim, etc., on such systems can
            produce unreliable results. Instead, use a dedicated Monte-Carlo analysis command, such as
            simsd.
          See Also
          bode | init | iopzmap | noise2meas | noisecnv | simsd | step | translatecov
Introduced in R2012a
1-1188
                                                                                              saturation
saturation
Create a saturation nonlinearity estimator object
Syntax
NL = saturation
NL = saturation('LinearInterval',[a,b])
Description
NL = saturation creates a default saturation nonlinearity estimator object for estimating
Hammerstein-Wiener models. The linear interval is set to [NaN NaN]. The initial value of the linear
interval is determined from the estimation data range during estimation using nlhw. Use dot notation
to customize the object properties, if needed.
Object Description
saturation is an object that stores the saturation nonlinearity estimator for estimating
Hammerstein-Wiener models.
Use saturation to define a nonlinear function y = F(x, θ), where y and x are scalars, and θ
represents the parameters a and b that define the linear interval, [a,b].
    a ≤ x < b              F(x) = x
    a > x                   F(x) = a
    b ≤ x                   F(x) = b
                                                                                               1-1189
1   Functions
Examples
NL = saturation;
NL.LinearInterval = [-4,5];
Load data.
          load twotankdata;
          z = iddata(y,u,0.2,'Name','Two tank system');
          z1 = z(1:1000);
1-1190
                                                                                              saturation
m = nlhw(z1,[2 3 0],InputNL,[]);
load motorizedcamera;
z = iddata(y,u,0.02,'Name','Motorized Camera','TimeUnit','s');
Orders = [ones(2,6),ones(2,6),ones(2,6)];
InputNL = saturation;
OutputNL = [deadzone,wavenet];
sys = nlhw(z,Orders,InputNL,OutputNL);
To see the shape of the estimated input and output nonlinearities, plot the nonlinearities.
plot(sys)
                                                                                               1-1191
1   Functions
Click on the input and output nonlinearity blocks on the top of the plot to see the nonlinearities.
          Input Arguments
          [a,b] — Linear interval
          [NaN NaN] (default) | 2–element row vector
          The saturation nonlinearity is initialized at the interval [a,b]. The interval values are adjusted to the
          estimation data by nlhw. To remove the lower limit, set a to -Inf. The lower limit is not adjusted
1-1192
                                                                                              saturation
during estimation. To remove the upper limit, set b to Inf. The upper limit is not adjusted during
estimation.
When the interval is [NaN NaN], the initial value of the linear interval is determined from the
estimation data range during estimation using nlhw.
Example: [-2 1]
Properties
LinearInterval
Output Arguments
NL — Saturation nonlinearity estimator object
saturation object
See Also
nlhw
Introduced in R2007a
                                                                                                  1-1193
1   Functions
          segment
          Segment data and estimate models for each segment
          Syntax
          segm = segment(z,nn)
[segm,V,thm,R2e] = segment(z,nn,R2,q,R1,M,th0,P0,ll,mu)
          Description
          segment builds models of AR, ARX, or ARMAX/ARMA type,
          assuming that the model parameters are piecewise constant over time. It results in a model that has
          split the data record into segments over which the model remains constant. The function models
          signals and systems that might undergo abrupt changes.
          The argument nn defines the model order. For the ARMAX model
          nn = [na nb nc nk];
          where na, nb, and nc are the orders of the corresponding polynomials. See “What Are Polynomial
          Models?”. Moreover, nk is the delay. If the model has several inputs, nb and nk are row vectors,
          giving the orders and delays for each input.
          The output argument segm is a matrix, where the kth row contains the parameters corresponding to
          time k. This is analogous to output estimates returned by the recursiveARX and recursiveARMAX
          estimators. The output argument thm of segment contains the corresponding model parameters that
          have not yet been segmented. Each row of thm contains the parameter estimates at the
          corresponding time instant. These estimates are formed by weighting together the parameters of
          M (default: 5) different time-varying models, with the participating models changing at every time
          step. Consider segment as an alternative to the online estimation commands when you are not
          interested in continuously tracking the changes in parameters of a single model, but need to detect
          abrupt changes in the system dynamics.
1-1194
                                                                                                    segment
The output argument V contains the sum of the squared prediction errors of the segmented model. It
is a measure of how successful the segmentation has been.
The input argument R2 is the assumed variance of the innovations e(t) in the model. The default value
of R2, R2 = [], is that it is estimated. Then the output argument R2e is a vector whose kth element
contains the estimate of R2 at time k.
The argument q is the probability that the model exhibits an abrupt change at any given time. The
default value is 0.01.
R1 is the assumed covariance matrix of the parameter jumps when they occur. The default value is
the identity matrix with dimension equal to the number of estimated parameters.
M is the number of parallel models used in the algorithm (see below). Its default value is 5.
th0 is the initial value of the parameters. Its default is zero. P0 is the initial covariance matrix of the
parameters. The default is 10 times the identity matrix.
ll is the guaranteed life of each of the models. That is, any created candidate model is not abolished
until after at least ll time steps. The default is ll = 1. Mu is a forgetting parameter that is used in
the scheme that estimates R2. The default is 0.97.
The most critical parameter for you to choose is R2. It is usually more robust to have a reasonable
guess of R2 than to estimate it. Typically, you need to try different values of R2 and evaluate the
results. (See the example below.) sqrt(R2) corresponds to a change in the value y(t) that is normal,
giving no indication that the system or the input might have changed.
Examples
y = sin([1:50]/3)';
u = ones(size(y));
R2 = 0.1;
Segment the signal and estimate an ARX model for each segment. Use the simple model
y(t) = b1u(t − 1), where b1 is the model parameter describing the piecewise constant level of the
estimated output, y(t).
plot([segm,y])
                                                                                                    1-1195
1   Functions
          Vary the value of R2 to change the estimated noise variance. Decreasing R2 increases the number of
          segments produced for this model.
          load iddemo6m.mat z
          z = iddata(z(:,1),z(:,2));
          plot(z)
1-1196
                                                                                                segment
This data contains a change in time delay from 2 to 1, which is difficult to detect by examining the
data.
nn = [1 2 1];
Segment the data and estimate ARX models for each segment. Specify an estimated noise variance of
0.1.
seg = segment(z,nn,0.1);
plot(seg)
legend('a','b1','b2');
                                                                                                1-1197
1   Functions
          The data has been divided into two segments, as indicated by the change in model parameters around
          sample number 19. The increase in b1, along with a corresponding decrease in b2, shows the change
          in model delay.
          Limitations
          segment is not compatible with MATLAB Coder or MATLAB Compiler.
          Algorithms
          The algorithm is based on M parallel models, each recursively estimated by an algorithm of Kalman
          filter type. Each model is updated independently, and its posterior probability is computed. The time-
          varying estimate thm is formed by weighting together the M different models with weights equal to
          their posterior probability. At each time step the model (among those that have lived at least ll
          samples) that has the lowest posterior probability is abolished. A new model is started, assuming that
          the system parameters have changed, with probability q, a random jump from the most likely among
          the models. The covariance matrix of the parameter change is set to R1.
          After all the data are examined, the surviving model with the highest posterior probability is tracked
          back and the time instances where it jumped are marked. This defines the different segments of the
          data. (If no models had been abolished in the algorithm, this would have been the maximum
          likelihood estimates of the jump instances.) The segmented model segm is then formed by smoothing
          the parameter estimate, assuming that the jump instances are correct. In other words, the last
          estimate over a segment is chosen to represent the whole segment.
1-1198
                           segment
See Also
Topics
“Data Segmentation”
                           1-1199
1   Functions
          selstruc
          Select model order for single-output ARX models
          Syntax
          nn = selstruc(v)
[nn,vmod] = selstruc(v,c)
Description
          Note Use selstruc for single-output systems only. selstruc supports both single-input and
          multiple-input systems.
          selstruc is a function to help choose a model structure (order) from the information contained in
          the matrix v obtained as the output from arxstruc or ivstruc.
          The default value of c is 'plot'. The plot shows the percentage of the output variance that is not
          explained by the model as a function of the number of parameters used. Each value shows the best fit
          for that number of parameters. By clicking in the plot you can examine which orders are of interest.
          When you click Select, the variable nn is exported to the workspace as the optimal model structure
          for your choice of number of parameters. Several choices can be made.
                                    2d
                V mod = log V 1 +
                                    N
                             2d
                = log(V) +      ,N ≫ d
                             N
          where V is the loss function, d is the total number of parameters in the structure in question, and N is
                                                                      2d
          the number of data points used for the estimation. log(V) +     is the Akaike's Information Criterion
                                                                       N
          (AIC). See aic for more details.
          c = 'mdl' returns in nn the structure that minimizes Rissanen's Minimum Description Length
          (MDL) criterion.
                                dlog(N)
                V mod = V 1 +
                                   N
                                                                                         cd
          When c equals a numerical value, the structure that minimizes V mod = V 1 +
                                                                                         N
is selected.
          The output argument vmod has the same format as v, but it contains the logarithms of the
          accordingly modified criteria.
1-1200
                                                                                            selstruc
Examples
load iddata1;
ze = z1(1:150);
zv = z1(151:300);
Generate model-order combinations for estimation, specifying ranges for model orders and delays.
NN = struc(1:3,1:2,2:4);
Estimate ARX models using the instrumental variable method, and compute the loss function for each
model order combination.
V = ivstruc(ze,zv,NN);
Select the model order with the best fit to the validation data.
order = selstruc(V,0);
M = iv4(ze,order);
load   co2data;
Ts =   0.5; % Sample time is 0.5 min
ze =   iddata(Output_exp1,Input_exp1,Ts);
zv =   iddata(Output_exp2,Input_exp2,Ts);
• na = 2:4
• nb = 2:5 for the first input, and 1 or 4 for the second input.
• nk = 1:4 for the first input, and 0 for the second input.
NN = struc(2:4,2:5,[1 4],1:4,0);
V = arxstruc(ze,zv,NN);
Select the model order with the best fit to the validation data.
order = selstruc(V,0);
                                                                                           1-1201
1   Functions
M = arx(ze,order);
1-1202
                                                                                                      set
set
Set or modify model properties
Syntax
set(sys,'Property',Value)
set(sys,'Property1',Value1,'Property2',Value2,...)
sysnew = set( ___ )
set(sys,'Property')
Description
set is used to set or modify the properties of a dynamic system model using property name/property
value pairs.
set(sys,'Property',Value) assigns the value Value to the property of the model sys.
'Property' can be the full property name (for example, 'UserData') or any unambiguous case-
insensitive abbreviation (for example, 'user'). The specified property must be compatible with the
model type. For example, if sys is a transfer function, Variable is a valid property but StateName
is not. For a complete list of available system properties for any linear model type, see the reference
page for that model type. This syntax is equivalent to sys.Property = Value.
sysnew = set( ___ ) returns the modified dynamic system model, and can be used with any of the
previous syntaxes.
Examples
Create a SISO state-space model with matrices A, B, C, and D equal to 1, 2, 3, and 4, respectively.
sys = ss(1,2,3,4);
Modify the properties of the model. Add an input delay of 0.1 second, label the input as torque, and
set the D matrix to 0.
set(sys,'InputDelay',0.1,'InputName','torque','D',0);
get(sys)
                   A: 1
                   B: 2
                   C: 3
                                                                                                 1-1203
1   Functions
                            D:   0
                            E:   []
                       Scaled:   0
                    StateName:   {''}
                    StateUnit:   {''}
                InternalDelay:   [0x1 double]
                   InputDelay:   0.1000
                  OutputDelay:   0
                           Ts:   0
                     TimeUnit:   'seconds'
                    InputName:   {'torque'}
                    InputUnit:   {''}
                   InputGroup:   [1x1 struct]
                   OutputName:   {''}
                   OutputUnit:   {''}
                  OutputGroup:   [1x1 struct]
                        Notes:   [0x1 string]
                     UserData:   []
                         Name:   ''
                 SamplingGrid:   [1x1 struct]
          Tips
          For discrete-time transfer functions, the convention used to represent the numerator and
          denominator depends on the choice of variable (see tf for details). Like tf, the syntax for set
          changes to remain consistent with the choice of variable. For example, if the Variable property is
          set to 'z' (the default),
                          z+2
                hz =
                       z2 + 3z + 4
set(h,'Variable','z^-1'),
          now interprets the row vectors [1 2] and [1 3 4] as the polynomials 1 + 2z−1 and 1 + 3z−1 + 4z−2
          and produces:
                              1 + 2z−1
                h z−1 =                   = zh z
                          1 + 3z−1 + 4z−2
          Note Because the resulting transfer functions are different, make sure to use the convention
          consistent with your choice of variable.
1-1204
                                                                                             set
See Also
frd | get | idfrd | idgrey | idnlarx | idnlgrey | idnlhw | idpoly | idproc | idss | idtf | ss |
tf | zpk
                                                                                        1-1205
1   Functions
          setcov
          Set parameter covariance data in identified model
          Syntax
          sys = setcov(sys0,cov)
          Description
          sys = setcov(sys0,cov) sets the parameter covariance of identified model sys0 as cov.
          The model parameter covariance is calculated and stored automatically when a model is estimated.
          Therefore, you do not need to set the parameter covariance explicitly for estimated models. Use this
          function for analysis, such as to study how the parameter covariance affects the response of a model
          obtained by explicit construction.
          Input Arguments
          sys0
Identified model.
          Identified model, specified as an idtf, idss, idgrey, idpoly, idproc, or idnlgrey model. You
          cannot set the covariance for nonlinear black-box models (idnlarx and idnlhw).
cov
cov(Free,Free) = T*inv(R'*R)*T'.
Default:
          Output Arguments
          sys
Identified model.
1-1206
                                                                                                  setcov
The values of all the properties of sys are the same as those in sys0, except for the parameter
covariance values which are modified as specified by cov.
Examples
                 4
    sys0 =
             s2 + 2s + 1
cov = zeros(np);
den_index = 2:3;
cov(den_index,den_index) = diag([0.04 0.001]);
cov is a covariance matrix with nonzero entries for the denominator parameters.
sys = setcov(sys0,cov);
See Also
getcov | rsample | setpvec | sim
Introduced in R2012a
                                                                                              1-1207
1   Functions
          setinit
          Set initial states of idnlgrey model object
          Syntax
          model = setinit(model,Property,Values)
          Description
          model = setinit(model,Property,Values) sets the values of the Property field of the
          InitialStates model property. Property can be 'Name', 'Unit', 'Value', 'Minimum',
          'Maximum', and 'Fixed'.
          Input Arguments
          model
                Name of the idnlgrey model object.
          Property
                Name of the InitialStates model property field, such as 'Name', 'Unit', 'Value',
                'Minimum', 'Maximum', and 'Fixed'.
          Values
                Values of the specified property Property. Values are an Nx-by-1 cell array of values, where Nx
                is the number of states.
          See Also
          getinit | getpar | idnlgrey | setpar
Introduced in R2007a
1-1208
                                                                                               setoptions
setoptions
Set plot options for response plot
Syntax
setoptions(h, PlotOpts)
setoptions(h, 'Property1', 'value1', ...)
setoptions(h, PlotOpts, 'Property1', 'value1', ...)
Description
setoptions(h, PlotOpts) sets preferences for response plot using the plot handle. h is the plot
handle, PlotOpts is a plot options handle containing information about plot options.
• Use getoptions, which accepts a plot handle and returns a plot options handle.
   p = getoptions(h)
• Create a default plot options handle using one of the following commands:
For example,
p = bodeoptions
help bodeoptions
For a list of the properties and values available for each plot type, see “Properties and Values
Reference” (Control System Toolbox).
                                                                                                   1-1209
1   Functions
Examples
                          1
                H(s) =
                         s+1
h = bodeplot(sys);
p = getoptions(h);
p.FreqUnits = 'Hz';
setoptions(h,p);
1-1210
                                                          setoptions
See Also
getoptions
Introduced in R2012a
                                                           1-1211
1   Functions
          idParametric/setpar
          Set attributes such as values and bounds of linear model parameters
          Syntax
          sys1   =   setpar(sys,'value',value)
          sys1   =   setpar(sys,'free',free)
          sys1   =   setpar(sys,'bounds',bounds)
          sys1   =   setpar(sys,'label',label)
          Description
          sys1 = setpar(sys,'value',value) sets the parameter values of the model sys. For model
          arrays, use setpar separately on each model in the array.
Examples
          load iddata8;
          init_data = z8(1:100);
          na = 1;
          nb = [1 1 1];
          nc = 1;
          nk = [0 0 0];
          sys = armax(init_data,[na nb nc nk]);
          m = idproc('P2DUZI');
          m.Kp = 1;
1-1212
                                                                                 idParametric/setpar
m.Tw =   100;
m.Zeta   = .3;
m.Tz =   10;
m.Td =   0.4;
m = setpar(m,'free',[1 1 1 1 0]);
load iddata8;
init_data = z8(1:100);
na = 1;
nb = [1 1 1];
nc = 1;
nk = [0 0 0];
sys = armax(init_data,[na nb nc nk]);
Set the minimum and maximum bounds for the parameters. Each row represents the bounds for a
single parameter. The first value in each row specifies the minimum bound and the second value
specifies the maximum bound.
load iddata8;
init_data = z8(1:100);
na = 1;
nb = [1 1 1];
nc = 1;
nk = [0 0 0];
sys = armax(init_data,[na nb nc nk]);
sys = setpar(sys,'label','default');
getpar(sys,'label')
                                                                                           1-1213
1   Functions
                {'B0(1)'}
                {'B0(2)'}
                {'B0(3)'}
                {'C1'   }
          Input Arguments
          sys — Identified linear model
          idss | idproc | idgrey | idtf | idpoly
Identified linear model, specified as an idss, idproc, idgrey, idtf, or idpoly model object.
          Minimum and maximum bounds on parameters, specified as a double matrix of size nparams(sys)-
          by-2. The first column specifies the minimum bound and the second column the maximum bound.
          Parameter labels, specified as a cell array of character vectors. The cell array is of length
          nparams(sys). For example, {'a1','a3'}, if nparams(sys) is two.
Use 'default' to assign default labels, A1, A2..., B1,B2,..., to the parameters.
          Output Arguments
          sys1 — Model with specified values of parameter attributes
          idss | idproc | idgrey | idtf | idpoly
          Model with specified values of parameter attributes. The model sys you specify as the input to
          setpar gets updated with the specified parameter attribute values.
          See Also
          getpar | setcov | setpvec
Introduced in R2013b
1-1214
                                                                                             setpar
setpar
Set initial parameter values of idnlgrey model object
Syntax
setpar(model,property,values)
Input Arguments
model
   Name of the idnlgrey model object.
property
   Name of the Parameters model property field, such as 'Name', 'Unit', 'Value', 'Minimum',
   or 'Maximum'.
   Default: 'Value'.
values
   Values of the specified property Property. values are an Np-by-1 cell array of values, where Np
   is the number of parameters.
Description
setpar(model,property,values) sets the model parameter values in the property field of the
Parameters model property. property can be 'Name', 'Unit', 'Value', 'Minimum', and
'Maximum'.
See Also
getinit | getpar | idnlgrey | setinit
Introduced in R2007a
                                                                                           1-1215
1   Functions
          setPolyFormat
          Specify format for B and F polynomials of multi-input polynomial model
          Syntax
          modelOut = setPolyFormat(modelIn,’double’)
          modelOut = setPolyFormat(modelIn,’cell’)
          Description
          modelOut = setPolyFormat(modelIn,’double’) converts the B and F polynomials of a multi-
          input polynomial model, modelIn, to double matrices.
          By default, the B and F polynomials of an idpoly model are cell arrays. For MATLAB scripts written
          before R2012a, convert the cell arrays to double matrices for backward compatibility using this
          syntax. For example:
          MATLAB data files saved before R2012a store idpoly models with their B and F polynomials
          represented as double matrices. If these models were previously set to operate in backward-
          compatibility mode, they are not converted to use cell arrays when loaded. Convert these models to
          use cell arrays using this syntax. For example:
Examples
load iddata8;
m1 = arx(z8,[3 [2 2 1] [1 1 1]]);
m2 = setPolyFormat(m1,'double');
Extract pole and zero information from the model using matrix syntax.
          Poles1 = roots(m2.F(1,:));
          Zeros1 = roots(m2.B(1,:));
1-1216
                                                                                       setPolyFormat
Input Arguments
modelIn — Polynomial model
idpoly object
Polynomial model, specified as an idpoly object. The B and F polynomials of modelIn are either:
• Cell arrays with Nu elements, where Nu is the number of model inputs, with each element
  containing a double vector. This configuration is the default.
• Double matrices with Nu rows. This configuration applies to backward-compatible idpoly models
  stored in MATLAB data files before R2012a.
Output Arguments
modelOut — Polynomial model
idpoly object
   modelOut.B(1,:);
• Cell array syntax after using modelOut = setPolyFormat(modelIn,'cell'). For example:
modelOut.B{1};
After using modelOut = setPolyFormat(modelIn,'cell'), you can resave the converted model
in cell array format. For example:
Tips
• To verify the current format of the B and F polynomials for a given idpoly model, enter:
class(model.B)
ans =
double
                                                                                             1-1217
1   Functions
ans =
cell
          See Also
          get | idpoly | polydata | set | tfdata
          Topics
          “Extracting Numerical Model Data”
Introduced in R2010a
1-1218
                                                                                               setpvec
setpvec
Modify value of model parameters
Syntax
sys = setpvec(sys0,par)
sys = setpvec(sys0,par,'free')
Description
sys = setpvec(sys0,par) modifies the value of the parameters of the identified model sys0 to
the value specified by par.
par must be of length nparams(sys0). nparams(sys0) returns a count of all the parameters of
sys0.
sys = setpvec(sys0,par,'free') modifies the value of all the free estimation parameters of
sys0 to the value specified by par.
Input Arguments
sys0
Identified model, specified as an idtf, idss, idgrey, idpoly, idproc, idnlarx, idnlhw, or
idnlgrey object.
par
If sys0 is an array of models, then specify par as a cell array with an entry corresponding to each
model in sys0.
Output Arguments
sys
Identified model obtained from sys0 by updating the values of the specified parameters.
                                                                                               1-1219
1   Functions
Examples
          Define a parameter vector and use it to set the model parameters. The second parameter is set to
          NaN, indicating that its value is unknown.
          par = [1;NaN;0];
          sys = setpvec(sys0,par);
Define a parameter vector and use it to set the free model parameters.
          par = [1;2;1];
          sys = setpvec(sys0,par,'free');
          See Also
          getpvec | nparams | setcov
Introduced in R2012a
1-1220
                                                                                                    sgrid
sgrid
Generate s-plane grid of constant damping factors and natural frequencies
Syntax
sgrid
sgrid(zeta,wn)
sgrid( ___ ,'new')
sgrid(AX, ___ )
Description
sgrid generates a grid of constant damping factors from 0 to 1 in steps of 0.1 and natural
frequencies from 0 to 10 rad/sec in steps of one rad/sec for pole-zero and root locus plots. sgrid then
plots the grid over the current axis. sgrid creates the grid over the plot if the current axis contains a
continuous s-plane root locus diagram or pole-zero map.
sgrid(zeta,wn) plots a grid of constant damping factor and natural frequency lines for the
damping factors and natural frequencies in the vectors zeta and wn, respectively. sgrid(zeta,wn)
creates the grid over the plot if the current axis contains a continuous s-plane root locus diagram or
pole-zero map.
Alternatively, you can select Grid from the context menu to generate the same s-plane grid.
sgrid( ___ ,'new') clears the current axes first and sets hold on.
sgrid(AX, ___ ) plots the s-plane grid on the Axes or UIAxes object in the current figure with the
handle AX. Use this syntax when creating apps with sgrid in the App Designer.
Examples
              2s2 + 5s + 1
     H(s) =
              s2 + 2s + 3
rlocus(H)
                                                                                                 1-1221
1   Functions
sgrid
1-1222
                                                                                              sgrid
Input Arguments
zeta — Damping ratio
vector
AX — Object handle
Axes object | UIAxes object
Object handle, specified as an Axes or UIAxes object. Use AX to create apps with sgrid in the App
Designer.
See Also
pzmap | rlocus | zgrid
                                                                                           1-1223
1   Functions
          showConfidence
          Display confidence regions on response plots for identified models
          Syntax
          showConfidence(plot_handle)
          showConfidence(plot_handle,sd)
          Description
          showConfidence(plot_handle) displays the confidence region on the response plot, with handle
          plot_handle, for an identified model.
          Input Arguments
          plot_handle
          plot_handle is the handle for the response plot of an identified model on which the confidence
          region is displayed. It is obtained as an output of one of the following plot commands: bodeplot,
          stepplot, impulseplot, nyquistplot, or iopzplot.
sd
          Standard deviation of the confidence region. A common choice is 3 standard deviations, which gives
          99.7% significance.
Default: getoptions(plot_handle,'ConfidenceRegionNumberSD')
Examples
Show the confidence bounds on the bode plot of an identified ARX model.
          load iddata1 z1
          sys = arx(z1, [2 2 1]);
          h = bodeplot(sys);
1-1224
                                                                                        showConfidence
z1 is an iddata object that contains time domain system response data. sys is an idpoly model
containing the identified polynomial model. h is the plot handle for the bode response plot of sys.
showConfidence(h);
                                                                                               1-1225
1   Functions
Show the confidence bounds on the bode plot of an identified ARX model.
          load iddata1 z1
          sys = arx(z1, [2 2 1]);
          h = bodeplot(sys);
1-1226
                                                                                        showConfidence
z1 is an iddata object that contains time domain system response data. sys is an idpoly model
containing the identified polynomial model. h is the plot handle for the bode response plot of sys.
sd = 2;
showConfidence(h,sd);
                                                                                               1-1227
1   Functions
sd specifies the number of standard deviations for the confidence region displayed on the plot.
          Alternatives
          You can interactively turn on the confidence region display on a response plot. Right-click the
          response plot, and select Characteristics > Confidence Region.
          See Also
          bodeplot | impulseplot | iopzplot | nyquistplot | stepplot
Introduced in R2012a
1-1228
                                                                                                      sigmoidnet
       sigmoidnet
       Class representing sigmoid network nonlinearity estimator for nonlinear ARX and Hammerstein-
       Wiener models
       Syntax
       s=sigmoidnet('NumberOfUnits',N)
       s=sigmoidnet(Property1,Value1,...PropertyN,ValueN)
       Description
       sigmoidnet is an object that stores the sigmoid network nonlinear estimator for estimating
       nonlinear ARX and Hammerstein-Wiener models.
You can use the constructor to create the nonlinearity object, as follows:
Use evaluate(s,x) to compute the value of the function defined by the sigmoidnet object s at x.
       sigmoidnet Properties
       You can include property-value pairs in the constructor to specify the object.
       After creating the object, you can use get or dot notation to access the object property values. For
       example:
You can also use the set function to set the value of particular properties. For example:
For example:
sigmoidnet(H,'NumberOfUnits',5)
                                                                                                        1-1229
1   Functions
For example:
                                        sigmoidnet(H,'LinearTerm','on')
Parameters                              A structure containing the parameters in the nonlinear expansion, as follows:
                                        Typically, the values of this structure are set by estimating a model with a
                                        sigmoidnet nonlinearity.
          Examples
          Use sigmoidnet to specify the nonlinear estimator in nonlinear ARX and Hammerstein-Wiener
          models. For example:
m=nlarx(Data,Orders,sigmoidnet('num',5));
          Tips
          Use sigmoidnet to define a nonlinear function y = F(x), where y is scalar and x is an m-dimensional
          row vector. The sigmoid network function is based on the following expansion:
                            1
                f (z) =             .
                          e−z + 1
          P and Q are m-by-p and m-by-q projection matrices. The projection matrices P and Q are determined
          by principal component analysis of estimation data. Usually, p=m. If the components of x in the
          estimation data are linearly dependent, then p<m. The number of columns of Q, q, corresponds to the
          number of components of x used in the sigmoid function.
1-1230
                                                                                          sigmoidnet
When used in a nonlinear ARX model, q is equal to the size of the NonlinearRegressors property
of the idnlarx object. When used in a Hammerstein-Wiener model, m=q=1 and Q is a scalar.
r is a 1-by-m vector and represents the mean value of the regressor vector computed from estimation
data.
L is a p-by-1 vector.
Algorithms
sigmoidnet uses an iterative search technique for estimating parameters.
See Also
nlarx | nlhw
Introduced in R2007a
                                                                                            1-1231
1   Functions
          sim
          Simulate response of identified model
          Syntax
          y = sim(sys,udata)
          y = sim(sys,udata,opt)
sim( ___ )
          Description
          y = sim(sys,udata) returns the simulated response of an identified model using the input data,
          udata. By default, zero initial conditions are used for all model types except idnlgrey, in which
          case the initial conditions stored internally in the model are used.
          y = sim(sys,udata,opt) uses the option set, opt, to configure the simulation option, including
          the specification of initial conditions.
[y,y_sd] = sim( ___ ) returns the estimated standard deviation, y_sd, of the simulated response.
[y,y_sd,x] = sim( ___ ) returns the state trajectory, x, for state-space models.
          [y,y_sd,x,x_sd] = sim( ___ ) returns the standard deviation of the state trajectory, x_sd, for
          state-space models.
Examples
load iddata2 z2
sys = ssest(z2,3);
Simulate the identified model using the input channels from the estimation data.
y = sim(sys,z2);
1-1232
                                                                                                    sim
Create a simulation option set to add noise to the simulated model response.
opt1 = simOptions('AddNoise',true);
Default Gaussian white noise is filtered by the noise transfer function of the model and added to the
simulated model response.
You can also add your own noise signal, e, using the NoiseData option.
e = randn(length(z2.u),1);
opt2 = simOptions('AddNoise',true,'NoiseData',e);
Load data.
load iddata1 z1
Estimate a state-space model, and return the value of the estimated initial state.
[sys,x0] = ssest(z1,2,estimOpt);
Simulate the model, and obtain the model response and standard deviation.
[y,y_sd] = sim(sys,z1,simOpt);
                                                                                               1-1233
1   Functions
          load iddata1 z1
          sys = ssest(z1,2);
[y,y_sd,x] = sim(sys,z1);
          load iddata1 z1
          sys = ssest(z1,2);
opt = simOptions('InitialCondition',[1;2]);
Calculate the standard deviations of simulated response, y_sd, and state trajectory, x_sd.
[y,y_sd,x,x_sd] = sim(sys,z1,opt);
          load iddata2 z2
          sys = tfest(z2,3);
          sys is an idtf model that encapsulates the third-order transfer function estimated for the measured
          data z2.
sim(sys,z2)
1-1234
                                                                                                 sim
Simulate a single-input single-output nonlinear ARX model around a known equilibrium point, with an
input level of 1 and output level of 10.
load iddata2
M = nlarx(z2,[2 2 1],'treepartition');
Estimate current states of model based on past data. Specify as many past samples as there are lags
in the input and output variables (2 here).
x0 = data2state(M,struct('Input',ones(2,1),'Output',10*ones(2,1)));
opt = simOptions('InitialCondition',x0);
sim(M,z2,opt)
                                                                                             1-1235
1   Functions
Continue the simulation of a nonlinear ARX model from the end of a previous simulation run.
          load iddata2
          M = nlarx(z2,[2 2 1],'treepartition');
          Simulate the model using the first half of the input data z2. Start the simulation from zero initial
          states.
          u1 = z2(1:200,[]);
          opt1 = simOptions('InitialCondition','zero');
          ys1 = sim(M,u1,opt1);
          Start another simulation using the second half of the input data z2. Use the same states of the model
          from the end of the first simulation.
u2 = z2(201:end,[]);
          To set the initial states for the second simulation correctly, package input u1 and output ys1 from the
          first simulation into one iddata object. Pass this data as initial conditions for the next simulation.
1-1236
                                                                                                     sim
firstSimData = [ys1,u1];
opt2 = simOptions('InitialCondition',firstSimData);
ys2 = sim(M,u2,opt2);
Verify the two simulations by comparing to a complete simulation using all the input data z2. First,
extract the whole set of input data.
uTotal = z2(:,[]);
opt3 = simOptions('InitialCondition','zero');
ysTotal = sim(M,uTotal,opt3);
Plot the three responses ys1, ys2 and ysTotal. ys1 should be equal to first half of ysTotal. ys2
should be equal to the second half of ysTotal.
plot(ys1,'b',ys2,'g',ysTotal,'k*')
The plot shows that the three responses ys1, ys2, and ysTotal overlap as expected.
Estimate initial states of model M such that, the response best matches the output in data set z2.
load iddata2;
                                                                                               1-1237
1   Functions
          Estimate the initial states of M to best fit z2.y in the simulated response.
          x0 = findstates(M,z2,Inf);
          Compare the simulated model output ysim with the output signal in z2.
          time = z2.SamplingInstants;
          plot(time,ysim,time,z2.y,'.')
Simulate Model Near Steady State with Known Input and Unknown Output
          Start simulation of a model near steady state, where the input is known to be 1, but the output is
          unknown.
1-1238
                                                                                                  sim
M = nlarx(z2,[4 3 2],'wavenet');
Determine equilibrium state values for input 1 and unknown target output.
x0 = findop(M,'steady',1, NaN);
opt = simOptions('InitialCondition',x0);
sim(M,z2.u,opt)
load iddata2
M = nlhw(z2,[4 3 2],[],'pwlinear');
Compute steady-state operating point values corresponding to an input level of 1 and an unknown
output level.
                                                                                           1-1239
1   Functions
x0 = findop(M,'steady',1,NaN);
          Load time series data, and estimate an AR model using the least-squares approach.
          load iddata9 z9
          sys = ar(z9,6,'ls');
          For time series data, specify the desired simulation length, N = 200 using an N-by-0 input data set.
          data = iddata([],zeros(200,0),z9.Ts);
          Set the initial conditions to use the initial samples of the time series as historical output samples.
          IC = struct('Input',[],'Output',z9.y(1:6));
          opt = simOptions('InitialCondition',IC);
1-1240
                                                                                                     sim
Use historical input-output data as a proxy for initial conditions when simulating your model. You first
simulate using the sim command and specify the historical data using the simOptions option set.
You then reproduce the simulated output by manually mapping the historical data to initial states.
load iddata7 z7
sys = n4sid(z7,5);
zA = z7(1:15);
zB = z7(16:end);
uSim = zB;
                                                                                                1-1241
1   Functions
          Simulation requires initial conditions. The signal values in zA are the historical data, that is, they are
          the input and output values for the time immediately preceding data in zB. Use zA as a proxy for the
          required initial conditions.
          IO = struct('Input',zA.InputData,'Output',zA.OutputData);
          opt = simOptions('InitialCondition',IO);
ysim = sim(sys,uSim,opt);
          Now reproduce the output by manually mapping the historical data to initial states of sys. To do so,
          use the data2state command.
xf = data2state(sys,zA);
          xf contains the state values of sys at the time instant immediately after the most recent data sample
          in zA.
          opt2 = simOptions('InitialCondition',xf);
          ysim2 = sim(sys,uSim,opt2);
Plot the output of the sim command ysim and the manually computed results ysim2.
plot(ysim,'b',ysim2,'--r')
1-1242
                                                                                                    sim
Input Arguments
sys — Identified model
identified linear model | identified nonlinear model
Simulation input data, specified as an iddata object or a matrix. sim uses the input channels from
this object as the simulation inputs. For time-domain simulation of discrete-time systems, you can also
specify udata as a matrix with columns that correspond to each input channel.
If sys is a linear model, you can use either time-domain or frequency-domain data. If sys is a
nonlinear model, you can only use time-domain data.
If sys is a time-series model, that is a model with no inputs, specify udata as an Ns-by-0 signal,
where Ns is the wanted number of simulation output samples. For example, to simulate 100 output
samples, specify udata as follows.
udata = iddata([],zeros(100,0),Ts);
If you do not have data from an experiment, use idinput to generate signals with various
characteristics.
                                                                                                 1-1243
1   Functions
Simulation options, specified as a simOptions option set for setting the following options:
          • Initial conditions
          • Input/output offsets
          • Additive noise
          Output Arguments
          y — Simulated response
          iddata object | matrix
          Simulated response for sys, returned as an iddata object or matrix, depending on how you specify
          udata. For example, if udata is an iddata object, then so is y.
          If udata represents time-domain data, then y is the simulated response for the time vector
          corresponding to udata.
          If udata represents frequency-domain data, U(ω), then y contains the Fourier transform of the
          corresponding sampled time-domain output signal. This signal is the product of the frequency
          response of sys, G(ω), and U(ω).
          Estimated standard deviation of the simulated response for linear models or nonlinear grey-box
          models, returned as an Ns-by-Ny matrix, where Ns is the number of samples and Ny is the number of
          outputs. The software computes the standard deviation by taking into account the model parameter
          covariance, initial state covariance, and additive noise covariance. The additive noise covariance is
          stored in the NoiseVariance property of the model.
y_sd is derived using first order sensitivity considerations (Gauss approximation formula).
          Estimated state trajectory for state-space models, returned as an Ns-by-Nx matrix, where Ns is the
          number of samples and Nx is the number of states.
          x is only relevant if sys is an idss, idgrey, or idnlgrey model. If sys is not a state-space model, x
          is returned as [].
          Estimated standard deviation of state trajectory for state-space models, returned as an Ns-by-Nx
          matrix, where Ns is the number of samples and Nx is the number of states. The software computes
          the standard deviation by taking into account the model parameter covariance, initial state
1-1244
                                                                                                    sim
covariance, and additive noise covariance. The additive noise covariance is stored in the
NoiseVariance property of the model.
x_sd is only relevant if sys is an idss, idgrey, or idnlgrey model. If sys is not a state-space
model, x_sd is returned as [].
Tips
• When the initial conditions of the estimated model and the system that measured the validation
  data set are different, the simulated and measured responses may also differ, especially at the
  beginning of the response. To minimize this difference, estimate the initial state values using
  findstates and use the estimated values to set the InitialCondition option using
  simOptions. For an example, see “Match Model Response to Output Data” on page 1-1237.
Algorithms
Simulation means computing the model response using input data and initial conditions. sim
simulates the following system:
Here,
                                                                                                1-1245
1   Functions
          • δu is an optional input offset subtracted from the input signal, u(t), before the input is used to
            simulate the model. Specify an input offset by setting the InputOffset option using
            simOptions.
          • δy is an optional output offset added to the output response, y(t), after simulation. Specify an
            output offset by setting the OutputOffset option using simOptions.
          For more information on specifying simulation initial conditions, input and output offsets, and noise
          signal data, see simOptions. For multiexperiment data, you can specify these options separately for
          each experiment.
          Alternatives
          • Use simsd for a Monte-Carlo method of computing the standard deviation of the response.
          • sim extends lsim to facilitate additional features relevant to identified models:
To obtain the simulated response without any of the preceding operations, use lsim.
          See Also
          compare | findstates | forecast | idinput | lsim | predict | simOptions | simsd | step
          Topics
          “Simulate and Predict Identified Model Output”
          “Simulation and Prediction at the Command Line”
1-1246
                                                                                    simOptions
simOptions
Option set for sim
Syntax
opt = simOptions
opt = simOptions(Name,Value)
Description
opt = simOptions creates the default option set for sim.
opt = simOptions(Name,Value) creates an option set with the options specified by one or more
Name,Value pair arguments.
Examples
opt = simOptions;
Create noise data for a simulation with 500 input data samples and two outputs.
noiseData = randn(500,2);
opt = simOptions;
opt.AddNoise = true;
opt.NoiseData = noiseData;
                                                                                      1-1247
1   Functions
Use historical input-output data as a proxy for initial conditions when simulating your model.
load iddata7 z7
          zA = z7(1:15);
          zB = z7(16:end);
uSim = zB;
          Simulation requires initial conditions. The signal values in zA are the historical data, that is, they are
          the input and output values for the time immediately preceding data in zB. Use zA as a proxy for the
          required initial conditions.
          IO = struct('Input',zA.InputData,'Output',zA.OutputData);
          opt = simOptions('InitialCondition',IO);
ysim = sim(sys,uSim,opt);
          To understand how the past data is mapped to the initial states of the model, see “Understand Use of
          Historical Data for Model Simulation” on page 1-1241.
          Input Arguments
          Name-Value Pair Arguments
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
          Example: 'AddNoise',true','InputOffset',[5;0] adds default Gaussian white noise to the
          response model and specifies an input offset of 5 for the first of two model inputs.
1-1248
                                                                                             simOptions
   For multi-experiment data, specify a matrix with Ne columns, where Ne is the number of
   experiments, to configure the initial conditions separately for each experiment. Otherwise, use a
   column vector to specify the same initial conditions for all experiments.
   Use this option for state-space models (idss and idgrey) only.
• Structure with the following fields, which contain the historical input and output values for a time
  interval immediately before the start time of the data used in the simulation:
       Field       Description
       Input       Input history, specified as a matrix with Nu columns, where Nu is the number of
                   input channels. For time-series models, use []. The number of rows must be
                   greater than or equal to the model order.
       Output      Output history, specified as a matrix with Ny columns, where Ny is the number of
                   output channels. The number of rows must be greater than or equal to the model
                   order.
   For an example, see “Use Historical Data to Specify Initial Conditions for Model Simulation” on
   page 1-1248.
   For multi-experiment data, configure the initial conditions separately for each experiment by
   specifying InitialCondition as a structure array with Ne elements. To specify the same initial
   conditions for all experiments, use a single structure.
   The software uses data2state to map the historical data to states. If your model is not idss,
   idgrey, idnlgrey, or idnlarx, the software first converts the model to its state-space
   representation and then maps the data to states. If conversion of your model to idss is not
   possible, the estimated states are returned empty.
• 'model' — Use this option for idnlgrey models only. The software sets the initial states to the
  values specified in the sys.InitialStates property of the model sys.
• [] — Corresponds to zero initial conditions for all models except idnlgrey. For idnlgrey
  models, the software treats [] as 'model' and specifies the initial states as
  sys.InitialStates.
Use this option only for state-space models (idss and idgrey) when 'InitialCondition' is
specified as a column vector. Use this option to account for initial condition uncertainty when
computing the standard deviation of the simulated response of a model.
                                                                                               1-1249
1   Functions
          Input signal offset, specified as a column vector of length Nu. Use [] if there are no input offsets.
          Each element of InputOffset is subtracted from the corresponding input data before the input is
          used to simulate the model.
          Output signal offset, specified as a column vector of length Ny. Use [] if there are no output offsets.
          Each element of OutputOffset is added to the corresponding simulated output response of the
          model.
          Noise addition toggle, specified as a logical value indicating whether to add noise to the response
          model.
          Here,G is the transfer function from the input, u(t), to the output, y(t), and H is the noise transfer
          function.
          Output Arguments
          opt — Option set for sim command
          simOptions option set
1-1250
                                                                   simOptions
See Also
sim
Introduced in R2012a
                                                                     1-1251
1   Functions
          simsd
          Simulate linear models with uncertainty using Monte Carlo method
          Syntax
          simsd(sys,udata)
          simsd(sys,udata,N)
          simsd(sys,udata,N,opt)
          y = simsd( ___ )
          [y,y_sd] = simsd( ___ )
          Description
          simsd simulates linear models using the Monte Carlo method. The command performs multiple
          simulations using different values of the uncertain parameters of the model, and different realizations
          of additive noise and simulation initial conditions. simsd uses Monte Carlo techniques to generate
          response uncertainty, whereas sim generates the uncertainty using the Gauss Approximation
          Formula.
          simsd(sys,udata) simulates and plots the response of 10 perturbed realizations of the identified
          model sys. Simulation input data udata is used to compute the simulated response.
          The parameters of the perturbed realizations of sys are consistent with the parameter covariance of
          the original model, sys. If sys does not contain parameter covariance information, the 10 simulated
          responses are identical. For information about how the parameter covariance information is used to
          generate the perturbed models, see “Generating Perturbations of Identified Model” on page 1-1259.
          simsd(sys,udata,N) simulates and plots the response of N perturbed realizations of the identified
          model sys.
          simsd(sys,udata,N,opt) simulates the system response using the simulation behavior specified
          in the option set opt. Use opt to specify uncertainties in the initial conditions and include the effect
          of additive disturbances.
          The simulated responses are all identical if sys does not contain parameter covariance information,
          and you do not specify additive noise or covariance values for initial states. You specify these values
          in the AddNoise and X0Covariance options of opt.
          y = simsd( ___ ) returns the N simulation results in y as a cell array. No simulated response plot is
          produced. Use with any of the input argument combinations in the previous syntaxes.
          [y,y_sd] = simsd( ___ ) also returns the estimated standard deviation y_sd for the simulated
          response.
Examples
1-1252
                                                                                                 simsd
load iddata1 z1
sys = ssest(z1,3);
Simulate the response of the estimated model using the Monte Carlo method and input estimation
data, and plot the response.
simsd(sys,z1);
The blue line plots the simulated response of the original nominal model sys. The green lines plot the
simulated response of 10 perturbed realizations of sys.
Simulate an estimated model using the Monte Carlo method for a specified number of model
perturbations.
                                                                                              1-1253
1   Functions
          Estimate a second-order state-space model using estimation data. Obtain sys in the observability
          canonical form.
          load iddata3 z3
          sys = ssest(z3,2,'Form','canonical');
          Compute the simulated response of the estimated model using the Monte Carlo method, and plot the
          responses. Specify the number of random model perturbations as 20.
          N = 20;
          simsd(sys,z3,N)
          The blue line plots the simulated response of the original nominal model sys. The green lines plot the
          simulated response of the 20 perturbed realizations of sys.
          You can also obtain the simulated response for each perturbation of sys. No plot is generated when
          you use this syntax.
y = simsd(sys,z3,N);
          y is the simulated response, returned as a cell array of N+1 elements. y{1} contains the nominal
          response for sys. The remaining elements contain the simulated response for the N perturbed
          realizations.
1-1254
                                                                                                     simsd
load iddata9 z9
sys = ar(z9,6,'ls');
For time series data, specify the desired simulation length, Ns = 200 using an Ns-by-0 input data set.
data = iddata([],zeros(200,0),z9.Ts);
Set the initial conditions to use the initial samples of the time series as historical output samples. The
past data is mapped to the initial states of each perturbed system individually.
IC = struct('Input',[],'Output',z9.y(1:6));
opt = simsdOptions('InitialCondition',IC);
Simulate the model using Monte Carlo method and specified initial conditions. Specify the number of
random model perturbations as 20.
simsd(sys,data,20,opt)
                                                                                                  1-1255
1   Functions
          The blue line plots the simulated response of the original nominal model sys. The green lines plot the
          simulated response of the 20 perturbed realizations of sys.
          load iddata3
          ze = z3(1:200);
          zsim = z3(201:256);
          Estimate a second-order state-space model sys using estimation data. Specify that no parameter
          covariance data is generated. Obtain sys in the observability canonical form.
          opt = ssestOptions('EstimateCovariance',false);
          sys = ssest(ze,2,'Form','canonical',opt);
          Set the initial conditions for simulating the estimated model. Specify initial state values x0 for the
          two states and also the covariance of initial state values x0Cov. The covariance is specified as a 2-
          by-2 matrix because there are two states.
          x0 = [1.2; -2.4];
          x0Cov = [0.86 -0.39; -0.39 1.42];
          opt = simsdOptions('InitialCondition',x0,'X0Covariance',x0Cov);
          Simulate the model using Monte Carlo method and specified initial conditions. Specify the number of
          random model perturbations as 100.
simsd(sys,zsim,100,opt)
1-1256
                                                                                                 simsd
The blue line plots the simulated response of the original nominal model sys. The green lines plot the
simulated response of the 100 perturbed realizations of sys. The software uses a different realization
of the initial states to simulate each perturbed model. Initial states are drawn from a Gaussian
distribution with mean InitialCondition and covariance X0Covariance.
load iddata1 z1
sys = ssest(z1,2);
Create a default option set for simsd, and modify the option set to add noise.
opt = simsdOptions;
opt.AddNoise = true;
Compute the simulated response of the estimated model using the Monte Carlo method. Specify the
number of random model perturbations as 20, and simulate the model using the specified option set.
                                                                                              1-1257
1   Functions
[y,y_sd] = simsd(sys,z1,20,opt);
          y is the simulated response, returned as a cell array of 21 elements. y{1} contains the nominal,
          noise-free response for sys. The remaining elements contain the simulated response for the 20
          perturbed realizations of sys with additive disturbances added to each response.
          y_sd is the estimated standard deviation of simulated response, returned as an iddata object with
          no inputs. The standard deviations are computed from the 21 simulated outputs. To access the
          standard deviation, use y_sd.OutputData.
          Input Arguments
          sys — Model to be simulated
          parametric linear identified model
          Model to be simulated, specified as one of the following parametric linear identified models: idtf,
          idproc, idpoly, idss, or idgrey.
          To generate the set of simulated responses, the software perturbs the parameters of sys in a way
          that is consistent with the parameter covariance information. Use getcov to examine the parameter
          uncertainty for sys. For information about how the perturbed models are generated from sys, see
          rsample.
          The simulated responses are all identical if sys does not contain parameter covariance information
          and you do not specify additive noise or covariance values for initial states. You specify these values
          in the AddNoise and X0Covariance options of opt.
          • iddata object — Input data can be either time-domain or frequency-domain. The software uses
            only the input channels of the iddata object.
                If sys is a time series model, that is, a model with no inputs, specify udata as an Ns-by-0 signal,
                where Ns is the wanted number of simulation output samples for each of the N perturbed
                realizations of sys. For example, to simulate 100 output samples, specify udata as follows.
udata = iddata([],zeros(100,0),Ts);
                For an example, see “Simulate Time Series Model Using Monte Carlo Method” on page 1-1254.
          • matrix — For simulation of discrete-time systems using time-domain data only. Columns of the
            matrix correspond to each input channel.
          If you do not have data from an experiment, use idinput to generate signals with various
          characteristics.
1-1258
                                                                                                 simsd
Simulation options for simulating models using Monte Carlo methods, specified as a simsdOptions
option set. You can use this option set to specify:
• Input and output signal offsets — Specify an offset to remove from the input signal and an offset to
  add to the response of sys.
• Initial condition handling — Specify initial conditions for simulation and their covariance. For
  state-space and linear grey-box models (idss and idgrey), if you want to simulate the effect of
  uncertainty in initial states, set the InitialCondition option to a double vector, and specify its
  covariance using the X0Covariance option. For an example, see “Study Effect of Initial Condition
  Uncertainty on Model Response” on page 1-1256.
• Addition of noise to simulated data — If you want to include the influence of additive disturbances,
  specify the AddNoise option as true. For an example, see “Study Effect of Additive Disturbance
  on Response Uncertainty” on page 1-1257.
Output Arguments
y — Simulated response
cell array
Simulated response, returned as a cell array of N+1 elements. y{1} contains the nominal response
for sys. The remaining elements contain the simulated response for the N perturbed realizations.
The command performs multiple simulations using different values of the uncertain parameters of the
model, and different realizations of additive noise and simulation initial conditions. Thus, the
simulated responses are all identical if sys does not contain parameter covariance information and
you do not specify additive noise and covariance values for initial states in opt.
Estimated standard deviation of simulated response, returned as an iddata object. The standard
deviation is computed as the sample standard deviation of the y ensemble:
                 N+1
             1                    2
    y_sd =
             N   ∑     (y 1 − y i )
                 i=2
Here y{1} is the nominal response for sys, and y{i} (i = 2:N+1) are the simulated responses for
the N perturbed realizations of sys.
More About
Generating Perturbations of Identified Model
The software generates N perturbations of the identified model sys and then simulates the response
of each of these perturbations. The parameters of the perturbed realizations of sys are consistent
with the parameter covariance of the original model sys. The parameter covariance of sys gives
information about the distribution of the parameters. However, for some parameter values, the
resulting perturbed systems can be unstable. To reduce the probability of generation of unrealistic
systems, the software prescales the parameter covariance.
                                                                                              1-1259
1   Functions
          If Δp is the parameter covariance for the parameters p of sys, then the simulated output f(p+Δp) of a
          perturbed model as a first-order approximation is:
                                       ∂f
                f (p + Δp) = f (p) +      Δp
                                       ∂p
          The simsd command first scales Δp by a scaling factor s (approximately 0.1%) to generate perturbed
          systems with parameters (p+sΔp). The command then computes f(p+sΔp), the simulated response of
          these perturbed systems. Where,
                                          ∂f
                f (p + sΔp) = f (p) + s      Δp
                                          ∂p
                                       1
                f (p + Δp) = f (p) +     f (p + sΔp) − f (p)
                                       s
Note This scaling is not applied to the free delays of idproc or idtf models.
          If you specify the AddNoise option of simsdOptions as true, the software adds different
          realizations of the noise sequence to the noise-free responses of the perturbed system. The
          realizations of the noise sequence are consistent with the noise component of the model.
          For state-space models, if you specify the covariance of initial state values in X0Covariance option
          of simsdOptions, different realizations of the initial states are used to simulate each perturbed
          model. Initial states are drawn from a Gaussian distribution with mean InitialCondition and
          covariance X0Covariance.
          See Also
          getcov | rsample | showConfidence | sim | simsdOptions
1-1260
                                                                                     simsdOptions
simsdOptions
Option set for simsd
Syntax
opt = simsdOptions
opt = simsdOptions(Name,Value)
Description
opt = simsdOptions creates the default option set for simsd.
opt = simsdOptions(Name,Value) creates an option set with the options specified by one or
more Name,Value pair arguments.
Examples
opt = simsdOptions;
opt = simsdOptions;
opt.AddNoise = true;
When you use this option set and simsd command to simulate the response of a model sys. The
command returns the perturbed realizations of sys with additive disturbances added to each
response.
                                                                                         1-1261
1   Functions
          Input Arguments
          Name-Value Pair Arguments
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
          Example: opt = simsdOptions('AddNoise',true','InputOffset',[5;0]) adds default
          Gaussian white noise to the response model, and specifies an input offset of 5 for the first of two
          model inputs.
                For multi-experiment data, specify a matrix with Ne columns, where Ne is the number of
                experiments, to configure the initial conditions separately for each experiment. Otherwise, use a
                column vector to specify the same initial conditions for all experiments.
                Use this option for state-space models (idss and idgrey) only. You can also specify the
                covariance of the initial state vector in X0Covariance.
          • Structure with the following fields, which contain the historical input and output values for a time
            interval immediately before the start time of the data used in the simulation:
                   Field       Description
                   Input       Input history, specified as a matrix with Nu columns, where Nu is the number of
                               input channels. For time-series models, use []. The number of rows must be
                               greater than or equal to the model order.
                   Output      Output history, specified as a matrix with Ny columns, where Ny is the number of
                               output channels. The number of rows must be greater than or equal to the model
                               order.
                For multi-experiment data, you can configure the initial conditions separately for each experiment
                by specifying InitialCondition as a structure array with Ne elements. Otherwise, use a single
                structure to specify the same initial conditions for all experiments.
                The software uses data2state to map the historical data to states. If your model is not idss or
                idgrey, the software first converts the model to its state-space representation and then maps the
                data to states. If conversion of your model to idss is not possible, the estimated states are
                returned empty.
1-1262
                                                                                            simsdOptions
Use this option for state-space models (idss and idgrey) when 'InitialCondition' is specified
as a numerical column vector X0. When you specify this option, the software uses a different
realization of the initial states to simulate each perturbed model. Initial states are drawn from a
Gaussian distribution with mean InitialCondition and covariance X0Covariance.
Input signal offset, specified as a column vector of length Nu. Use [] if there are no input offsets.
Each element of InputOffset is subtracted from the corresponding input data before the input is
used to simulate the model.
Output signal offset, specified as a column vector of length Ny. Use [] if there are no output offsets.
Each element of OutputOffset is added to the corresponding simulated output response of the
model.
Noise addition toggle, specified as a logical value indicating whether to add noise to the response
model. Set NoiseModel to true to study the effect of additive disturbances on the response. A
different realization of the noise sequence, consistent with the noise component of the perturbed
system, is added to the noise-free response of that system.
Output Arguments
opt — Option set for simsd command
simsdOptions option set
See Also
simsd
                                                                                                1-1263
1   Functions
Introduced in R2012a
1-1264
                                                                                                   size
size
Query output/input/array dimensions of input–output model and number of frequencies of FRD model
Syntax
size(sys)
d = size(sys)
Ny = size(sys,1)
Nu = size(sys,2)
Sk = size(sys,2+k)
Nf = size(sys,'frequency')
Description
When invoked without output arguments, size(sys) returns a description of type and the input-
output dimensions of sys. If sys is a model array, the array size is also described. For identified
models, the number of free parameters is also displayed. The lengths of the array dimensions are also
included in the response to size when sys is a model array.
d = size(sys) returns:
• The row vector d = [Ny Nu] for a single dynamic model sys with Ny outputs and Nu inputs
• The row vector d = [Ny Nu S1 S2 ... Sp] for an S1-by-S2-by-...-by-Sp array of dynamic
  models with Ny outputs and Nu inputs
Sk = size(sys,2+k) returns the length of the k-th array dimension when sys is a model array.
Examples
Create a 3-by-1 model array of random state-space models with 3 outputs, 2 inputs, and 5 states.
sys = rss(5,3,2,3);
size(sys)
                                                                                             1-1265
1   Functions
          type = {'p1d','p2';'p3uz','p0'};
          sys = idproc(type);
          Each element of the type cell array describes the model structure for the corresponding input-output
          pair.
Query the input-output dimensions and number of free parameters in the model.
size(sys)
          See Also
          isempty | issiso | ndims | nparams
1-1266
                                                                                                   spa
spa
Estimate frequency response with fixed frequency resolution using spectral analysis
Syntax
G = spa(data)
G = spa(data,winSize,freq)
G = spa(data,winSize,freq,MaxSize)
Description
G = spa(data) estimates frequency response (with uncertainty) and noise spectrum from time- or
frequency-domain data. data is an iddata or idfrd object and can be complex valued. G is as an
idfrd object. For time-series data, G is the estimated spectrum and standard deviation.
Information about the estimation results and options used is stored in the model's Report property.
Report has the following fields:
• Status — Summary of the model status, which indicates whether the model was created by
  construction or obtained by estimation.
• Method — Estimation command used.
• WindowSize — Size of the Hann window.
• DataUsed — Attributes of the data used for estimation. Structure with the following fields:
Examples
                                                                                                1-1267
1   Functions
          Estimate frequency response with fixed resolution at 128 equally spaced, logarithmic frequency
          values between 0 (excluded) and π.
          load iddata3;
          g = spa(z3);
          bode(g)
          Plot the Bode response and disturbance spectrum with confidence interval of 3 standard deviations.
          h = bodeplot(g);
          showConfidence(h,3)
1-1268
                          spa
figure
h = spectrumplot(g);
showConfidence(h,3)
                       1-1269
1   Functions
          More About
          Frequency Response Function
          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.
          To better understand the frequency response function, consider the following description of a linear,
          dynamic system:
          where u(t) and y(t) are the input and output signals, respectively. G(q) is called the transfer function
          of the system—it captures the system dynamics that take the input to the output. The notation
          G(q)u(t) represents the following operation:
                               ∞
                G(q)u(t) =     ∑    g(k)u(t − k)
                              k=1
1-1270
                                                                                                        spa
G(q) is the frequency-response function, which is evaluated on the unit circle, G(q=eiw).
Together, G(q=eiw) and the output noise spectrum Φ v(ω) are the frequency-domain description of the
system.
The frequency-response function estimated using the Blackman-Tukey approach is given by the
following equation:
                Φ yu ω
    G N eiω =
                Φu ω
In this case, ^ represents approximate quantities. For a derivation of this equation, see the chapter
on nonparametric time- and frequency-domain methods in System Identification: Theory for the User,
Second Edition, by Lennart Ljung, Prentice Hall PTR, 1999.
The output noise spectrum (spectrum of v(t)) is given by the following equation:
                                      2
                           Φ yu ω
    Φv ω = Φy ω −
                               Φu ω
This equation for the noise spectrum is derived by assuming the linear relationship
y(t) = G(q)u(t) + v(t), that u(t) is independent of v(t), and the following relationships between the
spectra:
                       2
    Φy(ω) = G eiω       Φu(ω) + Φv(ω)
                ∞
    Φv(ω) ≡     ∑      Rv(τ)e−iwτ
              τ = −∞
v(t) = H(q)e(t)
where e(t) is the white noise with variance λ and the noise power spectrum is given by the following
equation:
                           2
    Φv(ω) = λ H eiω
Algorithms
spa applies the Blackman-Tukey spectral analysis method by following these steps:
                                                                                                  1-1271
1   Functions
                where W M(τ) is the Hann window with a width (lag size) of M. You can specify M to control the
                frequency resolution of the estimate, which is approximately equal 2π/M rad/sample time.
                By default, this operation uses 128 equally spaced frequency values between 0 (excluded) and π,
                where w = [1:128]/128*pi/Ts and Ts is the sample time of that data set. The default lag size
                of the Hann window is M = min(length(data)/10,30). For default frequencies, uses fast
                Fourier transforms (FFT)—which is more efficient than for user-defined frequencies.
                Note M =γ is in Table 6.1 of Ljung (1999). Standard deviations are on pages 184 and 188 in
                Ljung (1999).
          3     Compute the frequency-response function G N eiω and the output noise spectrum Φ v(ω).
                               Φ yu ω
                G N eiω =
                                Φu ω
                                ∞
                Φv(ω) ≡        ∑        Rv(τ)e−iwτ
                           τ = −∞
          spectrum is the spectrum matrix for both the output and the input channels. That is, if z =
          [data.OutputData, data.InputData], spectrum contains as spectrum data the matrix-valued
          power spectrum of z.
                       M
                S=     ∑        Ez t + m z t ′W M Ts exp −iωm
                     m= −M
1-1272
                                                                                                spa
References
Ljung, L. System Identification: Theory for the User, Second Ed., Prentice Hall PTR, 1999.
See Also
bode | etfe | freqresp | idfrd | spafdr | spectrum
Topics
“Estimate Impulse-Response Models at the Command Line”
“Spectrum Normalization”
                                                                                             1-1273
1   Functions
          spafdr
          Estimate frequency response and spectrum using spectral analysis with frequency-dependent
          resolution
          Syntax
          g = spafdr(data)
          g = spafdr(data,Resol,w)
          Description
          g = spafdr(data) estimates the input-to-output frequency response G(ω) and noise spectrum Φυ of
          the general linear model
          where Φυ(ω) is the spectrum of υ(t). data contains the output-input data as an iddata object. The
          data can be complex valued, and either time or frequency domain. It can also be an idfrd object
          containing frequency-response data. g is an idfrd object with the estimate of G eiω at the
          frequencies ω specified by row vector w. g also includes information about the spectrum estimate of
          Φυ(ω) at the same frequencies. Both results are returned with estimated covariances, included in g.
          The normalization of the spectrum is the same as described in spa.
          Information about the estimation results and options used is stored in the model's Report property.
          Report has the following fields:
          • Status — Summary of the model status, which indicates whether the model was created by
            construction or obtained by estimation.
          • Method — Estimation command used.
          • WindowSize — Frequency resolution.
          • DataUsed — Attributes of the data used for estimation. Structure with the following fields:
Frequencies
          The frequency variable w is either specified as a row vector of frequencies in rad/TimeUnit, where
          TimeUnit refers to the TimeUnit property of data, or as a cell array {wmin,wmax}. In the latter
1-1274
                                                                                                  spafdr
case the covered frequencies will be 50 logarithmically spaced points from wmin to wmax. You can
change the number of points to NP by entering {wmin,wmax,NP}.
Omitting w or entering it as an empty matrix gives the default value, which is 100 logarithmically
spaced frequencies between the smallest and largest frequency in data. For time-domain data, the
                          2π     π
default range goes from       to , where Ts is the sample time of data and N is the number of data
                         NTs     Ts
points.
Resolution
The argument Resol defines the frequency resolution of the estimates. The resolution (measured in
rad/TimeUnit) is the size of the smallest detail in the frequency function and the spectrum that is
resolved by the estimate. The resolution is a tradeoff between obtaining estimates with fine, reliable
details, and suffering from spurious, random effects: The finer the resolution, the higher the variance
in the estimate. Resol can be entered as a scalar (measured in rad/TimeUnit), which defines the
resolution over the whole frequency interval. It can also be entered as a row vector of the same
length as w. Then Resol(k) is the local, frequency-dependent resolution around frequency w(k).
The default value of Resol, obtained by omitting it or entering it as the empty matrix, is Resol(k) =
2(w(k+1)-w(k)), adjusted upwards, so that a reasonable estimate is guaranteed. In all cases, the
resolution is returned in the variable g.Report.WindowSize.
Algorithms
If the data is given in the time domain, it is first converted to the frequency domain. Then averages of
Y(w)Conj(U(w)) and U(w)Conj(U(w)) are formed over the frequency ranges w, corresponding to
the desired resolution around the frequency in question. The ratio of these averages is then formed
for the frequency-function estimate, and corresponding expressions define the noise spectrum
estimate.
See Also
bode | etfe | freqresp | idfrd | nyquist | spa | spectrum
                                                                                                1-1275
1   Functions
          spectrum
          Output power spectrum of time series models
          Syntax
          spectrum(sys)
          spectrum(sys,{wmin, wmax})
          spectrum(sys,w)
          spectrum(sys1,...,sysN,w)
          ps = spectrum(sys,w)
          [ps,w] = spectrum(sys)
          [ps,w,sdps] = spectrum(sys)
          Description
          spectrum(sys) creates an output power spectrum plot of the identified time series model sys. The
          frequency range and number of points are chosen automatically.
y(t) = He(t)
Where, e(t) is a Gaussian white noise and y(t) is the observed output.
spectrum plots abs(H'H), scaled by the variance of e(t) and the sample time.
Where, u(t) is the measured input, e(t) is a Gaussian white noise and y(t) is the observed output.
In this case, spectrum plots the spectrum of the disturbance component He(t).
          spectrum(sys,{wmin, wmax}) creates a spectrum plot for frequencies ranging from wmin to
          wmax.
spectrum(sys,w) creates a spectrum plot using the frequencies specified in the vector w.
You can specify a color, line style and marker for each model. For example:
spectrum(sys1,'r',sys2,'y--',sys3,'gx');
          ps = spectrum(sys,w) returns the power spectrum amplitude of sys for the specified
          frequencies, w. No plot is drawn on the screen.
          [ps,w] = spectrum(sys) returns the frequency vector, w, for which the output power spectrum is
          plotted.
1-1276
                                                                                            spectrum
[ps,w,sdps] = spectrum(sys) returns the estimated standard deviations of the power spectrum.
For discrete-time models with sample time Ts, spectrum uses the transformation z =
exp(j*w*Ts) to map the unit circle to the real frequency axis. The spectrum is only plotted for
frequencies smaller than the Nyquist frequency pi/Ts, and the default value 1 (time unit) is assumed
when Ts is unspecified.
Input Arguments
sys
Identified model.
y(t) = He(t)
Where, e(t) is a Gaussian white noise and y(t) is the observed output.
Where, u(t) is the measured input, e(t) is a Gaussian white noise and y(t) is the observed output.
wmin
Minimum frequency of the frequency range for which the output power spectrum is plotted.
wmax
Maximum frequency of the frequency range for which the output power spectrum is plotted.
sys1,...,sysN
Output Arguments
ps
If sys has Ny outputs, then ps is an array of size [Ny Ny length(w)]. Where ps(:,:,k)
corresponds to the power spectrum for the frequency at w(k).
                                                                                            1-1277
1   Functions
sdps
Examples
sys = n4sid(z1,2);
spectrum(sys);
1-1278
                                                                                              spectrum
load iddata9 z9
sys = ar(z9,4,'ls');
spectrum(sys);
Create an input consisting of five sinusoids spread over the whole frequency interval. Compare the
spectrum of this signal with that of its square. The frequency splitting (the square having spectral
support at other frequencies) reveals the nonlinearity involved.
                                                                                               1-1279
1   Functions
          u2 = iddata([],u2,1,'per',100);
          spectrum(etfe(u),'r*',etfe(u2),'+')
          See Also
          ar | armax | arx | bode | forecast | freqresp | nlarx
Introduced in R2012a
1-1280
                                                                                  spectrumoptions
spectrumoptions
Option set for spectrumplot
Syntax
opt = spectrumoptions
opt = spectrumoptions('identpref')
Description
opt = spectrumoptions creates the default option set for spectrumplot. Use dot notation to
customize the option set, if needed.
opt = spectrumoptions('identpref') initializes the plot options with the System Identification
Toolbox preferences. Use this syntax to change a few plot options but otherwise use your toolbox
preferences.
Examples
plot_options = spectrumoptions;
plot_options.FreqUnits = 'Hz';
plot_options.FreqScale = 'linear';
plot_options.Xlim = {[0 20]};
plot_options.MagUnits = 'abs';
Estimate an AR model.
load iddata9 z9
sys = ar(z9,4);
spectrumplot(sys,plot_options);
                                                                                         1-1281
1   Functions
opt = spectrumoptions('identpref');
          Output Arguments
          opt — Option set for spectrumplot
          spectrumpoptions option set
1-1282
                                                            spectrumoptions
Field                   Description
Title, XLabel, YLabel   Text and style for axes labels and plot title,
                        specified as a structure array with the following
                        fields:
                                                                   1-1283
1   Functions
           Field                Description
           TickLabel            Tick label style, specified as a structure array
                                with the following fields:
                                Default: 'off'
           GridColor            Color of the grid lines, specified as one of the
                                following: vector of RGB values in the range
                                [0,1] | character vector of color name | 'none'.
                                For example, for yellow color, specify as one of
                                the following: [1 1 0], 'yellow', or 'y'.
                                Default: [0.15,0.15,0.15]
           XLimMode, YLimMode   Axes limit modes, specified as one of the
                                following values:
                                Default: 'auto'
           XLim, YLim           Axes limits, specified as an array of the form
                                [min,max]
           IOGrouping           Grouping of input-output pairs in the plot,
                                specified as one of the following values: 'none' |
                                'inputs'| 'outputs'|'all'
Default: 'none'
1-1284
                                                                   spectrumoptions
Field                         Description
InputLabels, OutputLabels     Input and output label styles, specified as a
                              structure array with the following fields:
                              Default: 'on'
ConfidenceRegionNumberSD      Number of standard deviations to use to plot the
                              response confidence region.
Default: 1
                                                                          1-1285
1   Functions
           Field       Description
           FreqUnits   Frequency units, specified as one of the following
                       values:
                       • 'Hz'
                       • 'rad/second'
                       • 'rpm'
                       • 'kHz'
                       • 'MHz'
                       • 'GHz'
                       • 'rad/nanosecond'
                       • 'rad/microsecond'
                       • 'rad/millisecond'
                       • 'rad/minute'
                       • 'rad/hour'
                       • 'rad/day'
                       • 'rad/week'
                       • 'rad/month'
                       • 'rad/year'
                       • 'cycles/nanosecond'
                       • 'cycles/microsecond'
                       • 'cycles/millisecond'
                       • 'cycles/hour'
                       • 'cycles/day'
                       • 'cycles/week'
                       • 'cycles/month'
                       • 'cycles/year'
Default: 'rad/s'
                       Default: 'log'
           MagUnits    Magnitude units, specified as one of the following
                       values: 'dB' | 'abs'
Default: 'dB'
1-1286
                                                                              spectrumoptions
Field                                      Description
MagScale                                   Magnitude scale, specified as one of the following
                                           values: 'linear' | 'log'
                                           Default: 'linear'
MagLowerLimMode                            Enables a lower magnitude limit, specified as one
                                           of the following values: 'auto' | 'manual'
                                           Default: 'auto'
MagLowerLim                                Lower magnitude limit, specified as data type
                                           double.
See Also
getoptions | identpref | setoptions | spectrumplot
Introduced in R2012a
                                                                                      1-1287
1   Functions
          spectrumplot
          Plot disturbance spectrum of linear identified models
          Syntax
          spectrumplot(sys)
          spectrumplot(sys,line_spec)
          spectrumplot(sys1,line_spec1,...,sysN,line_specN)
          spectrumplot(ax, ___ )
          spectrumplot( ___ ,plot_options)
          spectrumplot(sys,w)
          h = spectrumplot( ___ )
          Description
          spectrumplot(sys) plots the disturbance spectrum of the model, sys. The software chooses the
          number of points on the plot and the plot frequency range.
          If sys is a time-series model, its disturbance spectrum is the same as the model output spectrum. You
          generally use this function with time-series models.
          spectrumplot(sys,line_spec) uses line_spec to specify the line type, marker symbol, and
          color.
          spectrumplot(ax, ___ ) plots into the axes with handle ax. All input arguments described for the
          previous syntaxes also apply here.
          spectrumplot( ___ ,plot_options) uses plot_options to specify options such as plot title,
          frequency units, etc. All input arguments described for the previous syntaxes also apply here.
          • If w is specified as a 2-element cell array, {wmin, wmax}, the plot spans the frequency range
            {wmin, wmax}.
          • If w is specified as vector, the spectrum is plotted for the specified frequencies.
          h = spectrumplot( ___ ) returns the handle to the spectrum plot. You use the handle to customize
          the plot. All input arguments described for the previous syntaxes also apply here.
1-1288
                                                                                            spectrumplot
Input Arguments
sys
Default:
line_spec
Line style, marker, and color of both the line and marker, specified as a character vector. For example,
'b', 'b+:'.
ax
You can obtain the current axes handle by using the function, gca.
plot_options
You use the command, spectrumoptions, to create plot_options. For more information, type
help spectrumoptions.
Frequency range.
Output Arguments
h
Examples
load iddata9 z9
sys = ar(z9,4);
                                                                                                1-1289
1   Functions
spectrumplot(sys);
          load iddata9 z9
          sys = ar(z9,4);
Specify the line width and marker style for the spectrum plot.
spectrumplot(sys,'k*--');
1-1290
                                                                                 spectrumplot
'k*--', specifies a dashed line (--) that is black (k), with star markers (*).
load iddata9 z9
sys1 = ar(z9,4);
sys2 = ar(z9,2);
spectrumplot(sys1,'b*-',sys2,'g^:');
legend('sys1','sys2');
                                                                                     1-1291
1   Functions
          load iddata9 z9
          sys1 = ar(z9,4);
          spectrumplot(sys1);
1-1292
                                                                    spectrumplot
ax = gca;
Plot the output spectrum for another model on the specified axes.
sys2 = ar(z9,2);
hold on;
spectrumplot(ax,sys2,'r*--');
legend('sys1','sys2');
                                                                        1-1293
1   Functions
          plot_options = spectrumoptions;
          plot_options.FreqUnits = 'Hz';
          plot_options.FreqScale = 'linear';
          plot_options.Xlim = {[0 20]};
          plot_options.MagUnits = 'abs';
Estimate an AR model.
          load iddata9 z9
          sys = ar(z9,4);
spectrumplot(sys,plot_options);
1-1294
                                                                          spectrumplot
load iddata9 z9
sys = ar(z9,4);
Specify the frequency range for the output spectrum plot for the model.
spectrumplot(sys,{1,1000});
                                                                              1-1295
1   Functions
The 2-element cell array {1,1000} specifies the frequency range from 1 rad/s to 1000 rad/s.
          load iddata9 z9
          sys = ar(z9,4);
h = spectrumplot(sys);
1-1296
                                                                            spectrumplot
setoptions(h,'FreqUnits','Hz','FreqScale','linear','Xlim',{[0 20]},'MagUnits','abs');
                                                                                1-1297
1   Functions
          See Also
          Axes | Chart Line | getoptions | setoptions | showConfidence | spectrum | spectrumoptions
Introduced in R2012b
1-1298
                                                                                                 ss2ss
ss2ss
State coordinate transformation for state-space model
Syntax
sysT = ss2ss(sys,T)
Description
Given a state-space model sys with equations
    ẋ = Ax + Bu
    y = Cx + Du
     dx
        = Ax + Bu + Ke
     dt
      y = Cx + Du + e
(or their discrete-time counterpart), ss2ss performs the similarity transformation x = Tx on the state
vector x and produces the equivalent state-space model sysT with equations.
    ẋ = T AT −1x + TBu
    y = CT −1x + Du
sysT = ss2ss(sys,T) returns the transformed state-space model sysT given sys and the state
coordinate transformation T. The model sys must be in state-space form and the matrix T must be
invertible. ss2ss is applicable to both continuous- and discrete-time models.
Examples
Perform a similarity transform to improve the conditioning of the A matrix.
[T,~] = balance(sys.A)
sysb = ss2ss(sys,inv(T))
See Also
balreal | canon
                                                                                              1-1299
1   Functions
          ssdata
          Access state-space model data
          Syntax
          [a,b,c,d] = ssdata(sys)
          [a,b,c,d,Ts] = ssdata(sys)
          Description
          [a,b,c,d] = ssdata(sys) extracts the matrix (or multidimensional array) data A, B, C, D from
          the state-space model (LTI array) sys. If sys is a transfer function or zero-pole-gain model (LTI
          array), it is first converted to state space. See ss for more information on the format of state-space
          model data.
If sys appears in descriptor form (nonempty E matrix), an equivalent explicit form is first derived.
          If sys has internal delays, A, B, C, D are obtained by first setting all internal delays to zero (creating a
          zero-order Padé approximation). For some systems, setting delays to zero creates singular algebraic
          loops, which result in either improper or ill-defined, zero-delay approximations. For these systems,
          ssdata cannot display the matrices and returns an error. This error does not imply a problem with
          the model sys itself.
          For generalized state-space (genss) models, ssdata returns the state-space models evaluated at the
          current, nominal value of all control design blocks. To access the dependency of a genss model on its
          static control design blocks, use the A, B, C, and D properties of the model.
You can access the remaining LTI properties of sys with get or by direct referencing. For example:
sys.statename
For arrays of state-space models with variable numbers of states, use the syntax:
[a,b,c,d] = ssdata(sys,'cell')
to extract the state-space matrices of each model as separate cells in the cell arrays a, b, c, and d.
          See Also
          dssdata | get | getDelayModel | idssdata | set | ss | tfdata | zpkdata
1-1300
                                                                                                        ssest
ssest
Estimate state-space model using time-domain or frequency-domain data
Syntax
sys = ssest(data,nx)
sys = ssest(data,nx,Name,Value)
sys = ssest( ___ ,opt)
sys = ssest(data,init_sys)
sys = ssest(data,init_sys,opt)
Description
Estimate a State-Space Model
sys = ssest(data,nx) estimates a continuous-time state-space model sys of order nx, using data
data that can be in the time domain or the frequency domain. sys is a model of the following form:
A, B, C, D, and K are state-space matrices. u(t) is the input, y(t) is the output, e(t) is the disturbance,
and x(t) is the vector of nx states.
All entries of A, B, C, and K are free estimable parameters by default. D is fixed to zero by default,
meaning that there is no feedthrough, except for static systems (nx = 0).
sys = ssest( ___ ,opt) incorporates an option set opt that specifies options such as estimation
objective, handling of initial conditions, regularization, and numerical search method used for
estimation. You can specify opt after any of the previous input-argument combinations.
Configure Initial Parameters
sys = ssest(data,init_sys) uses the state-space model init_sys to configure the initial
parameterization.
[sys,x0] = ssest( ___ ) returns the value of initial states computed during estimation. You can
use this syntax with any of the previous input-argument combinations.
                                                                                                    1-1301
1   Functions
Examples
State-Space Model
Estimate a state-space model and compare its response with the measured output.
load iddata1 z1
          nx = 4;
          sys = ssest(z1,nx);
compare(z1,sys)
          The plot shows that the fit percentage between the simulated model and the estimation data is
          greater than 70%.
You can view more information about the estimation by exploring the idss property sys.Report.
sys.Report
1-1302
                                                                                                    ssest
ans =
          Status:    'Estimated using SSEST with prediction focus'
          Method:    'SSEST'
    InitialState:    'zero'
        N4Weight:    'CVA'
       N4Horizon:    [6 10 10]
             Fit:    [1x1 struct]
      Parameters:    [1x1 struct]
     OptionsUsed:    [1x1 idoptions.ssest]
       RandState:    []
        DataUsed:    [1x1 struct]
     Termination:    [1x1 struct]
For example, find out more information about the termination conditions.
sys.Report.Termination
The report includes information on the number of iterations and the reason the estimation stopped
iterating.
Load the input-output data z1, which is stored in an iddata object. This is the same data used to
estimate a fourth-order model in “State-Space Model” on page 1-1302.
load iddata1 z1
Determine the optimal model order by specifying argument nx as a range from 1:10.
nx = 1:10;
sys = ssest(z1,nx);
An automatically generated plot shows the Hankel singular values for models of the orders specified
by nx.
                                                                                             1-1303
1   Functions
          States with relatively small Hankel singular values can be safely discarded. The suggested default
          order choice is 2.
Select the model order in the Chosen Order list and click Apply.
          Identify a fourth-order state-space model of the data. Specify a known delay of 2 seconds for the first
          input and 0 seconds for the second input.
          nx = 4;
          sys = ssest(z7(1:300),nx,'InputDelay',[2;0]);
          Modify the canonical form of the A, B, and C matrices, include a feedthrough term in the D matrix,
          and eliminate disturbance-model estimation in the K matrix.
Load input-output data and estimate a fourth-order system using the ssest default options.
          load iddata1 z1
          sys1 = ssest(z1,4);
Specify the companion form and compare the A matrix with the default A matrix.
1-1304
                                                           ssest
sys2 = ssest(z1,4,'Form','companion');
A1 = sys1.A
A1 = 4×4
A2 = sys2.A
A2 = 4×4
103 ×
         0          0          0    -7.1122
    0.0010          0          0    -0.9547
         0     0.0010          0    -0.3263
         0          0     0.0010    -0.0033
sys3 = ssest(z1,4,'Feedthrough',1);
D1 = sys1.D
D1 = 0
D3 = sys3.D
D3 = 0.0339
sys4 = ssest(z1,4,'DisturbanceModel','none');
K1 = sys1.K
K1 = 4×1
    0.0520
    0.0973
    0.0151
    0.0270
K4 = sys4.K
K4 = 4×1
     0
     0
     0
     0
                                                         1-1305
1   Functions
          ssest can handle initial states using one of several methods. By default, ssest chooses the method
          automatically based on your estimation data. You can choose the method yourself by modifying the
          option set using ssestOptions.
          Load the input-output data z1 and estimate a second-order state-space model sys using the default
          options. Use the syntax that returns initial states x0.
          load iddata1 z1
          [sys,x0] = ssest(z1,2);
          x0
x0 = 2×1
                0
                0
          By default, the estimation is performed using the 'auto' setting for InitialState. Find out which
          method ssest applied by reviewing the value of InitialState in sys.Report.
sys.Report.InitialState
          ans =
          'zero'
          The software applied the 'zero' method, meaning that the software set the initial states to zero
          instead of estimating them. This selection is consistent with the 0 values returned for x0.
          Specify that ssest estimate the initial states instead as independent parameters using the
          'estimate' setting. Use ssestOptions to create a modified option set and specify that option set
          to estimate a new model.
          opt = ssestOptions('InitialState','estimate');
          [sys1,x0] = ssest(z1,2,opt);
          x0
x0 = 2×1
                0.0068
                0.0052
          Obtain a regularized fifth-order state-space model for a second-order system from a narrow
          bandwidth signal.
1-1306
                                                                                              ssest
Create the transfer function model used for generating the estimation data (true system).
opt = ssestOptions('SearchMethod','lm');
m = ssest(eData,5,'form','modal','DisturbanceModel','none','Ts',eData.Ts,opt);
opt.Regularization.Lambda = 10;
mr = ssest(eData,5,'form','modal','DisturbanceModel','none','Ts',eData.Ts,opt);
compare(eData,m,mr);
impulse(trueSys,m,mr,50);
legend('trueSys','m','mr');
                                                                                            1-1307
1   Functions
          Estimate a state-space model of measured input-output data. Configure the parameter constraints
          and initial values for estimation using a state-space model.
Setting all entries of K to 0 creates an idss model with no state disturbance element.
          Use the Structure property to fix the values of some of the model parameters. Configure the model
          so that B and K are fixed, and only the nonzero entries of A are estimable.
          init_sys.Structure.A.Free = (A~=0);
          init_sys.Structure.B.Free = false;
          init_sys.Structure.K.Free = false;
1-1308
                                                                                                  ssest
Load the measured data and estimate a state-space model using the parameter constraints and initial
values specified by init_sys.
Input Arguments
data — Estimation data
iddata object | frd object | idfrd object
For time-domain estimation, data must be an iddata object containing the input and output signal
values.
Estimation data must be uniformly sampled. By default, the software sets the sample time of the
model to the sample time of the estimation data.
For multiexperiment data, the sample times and intersample behavior of all the experiments must
match.
The domain of your data determines the type of model you can estimate.
Order of the estimated model, specified as a nonnegative integer or as a vector containing a range of
positive integers.
• If you already know what order you want your estimated model to have, specify nx as a scalar.
• If you want to compare a range of potential orders to choose the most effective order for your
  estimated model, specify the range in nx. ssest creates a Hankel singular-value plot that shows
  the relative energy contributions of each state in the system. States with relatively small Hankel
  singular values contribute little to the accuracy of the model and can be discarded with little
                                                                                              1-1309
1   Functions
                impact. The index of the highest state you retain is the model order. The plot window includes a
                suggestion for the order to use. You can accept this suggestion or enter a different order. For an
                example, see “Determine Optimal Estimated Model Order” on page 1-1303.
                If you do not specify nx, or if you specify nx as best, the software automatically chooses nx from
                the range 1:10.
          • If you are identifying a static system, set nx to 0.
Estimation options, specified as an ssestOptions option set. Options specified by opt include:
          • Estimation objective
          • Handling of initial conditions
          • Regularization
          • Numerical search method used for estimation
          For examples showing how to use opt, see “Estimate Initial States as Independent Parameters” on
          page 1-1305 and “Estimate State-Space Model Using Regularization” on page 1-1306.
          Linear system that configures the initial parameterization of sys, specified as an idss model or as a
          structure. You obtain init_sys by either performing an estimation using measured data or by direct
          construction.
          If init_sys is an idss model, ssest uses the parameter values of init_sys as the initial guess for
          estimating sys. For information on how to specify idss, see “Estimate State-Space Models with
          Structured Parameterization”. ssest honors constraints on the parameters of init_sys, such as
          fixed coefficients and minimum/maximum bounds.
          Use the Structure property of init_sys to configure initial parameter values and constraints for
          the A, B, C, D, and K matrices. For example:
                To set more complex constraints, such as interdependence of coefficients, use grey-box estimation
                using greyest and idgrey.
You must assign finite initial values for all matrix parameters.
          If init_sys is not a state-space (idss) model, the software first converts init_sys to an idss
          model. ssest uses the parameters of the resulting model as the initial guess for estimation.
1-1310
                                                                                                ssest
If you do not specify opt and init_sys was obtained by estimation, then the software uses
estimation options from init_sys.Report.OptionsUsed.
For an example, see “Estimate Partially Known State-Space Model Using Structured Estimation” on
page 1-1308.
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Example: sys = ssest(data,nx,'Ts',0.1)
Sample time of the estimated model, specified as the comma-separated pair consisting of 'Ts' and
either 0 or a positive scalar.
Input delay for each input channel, specified as the comma-separated pair consisting of
'InputDelay' and a numeric vector.
• For continuous-time models, specify 'InputDelay' in the time units stored in the TimeUnit
  property.
• For discrete-time models, specify 'InputDelay' in integer multiples of the sample time Ts. For
  example, setting 'InputDelay' to 3 specifies a delay of three sampling periods.
For a system with Nu inputs, set InputDelay to an Nu-by-1 vector. Each entry of this vector is a
numerical value that represents the input delay for the corresponding input channel. For an example,
see “Identify State-Space Model with Input Delay” on page 1-1304.
Type of canonical form of sys, specified as the comma-separated pair consisting of 'Form' and one
of the following values:
                                                                                              1-1311
1   Functions
          For more information, see “Estimate State-Space Models with Canonical Parameterization”. For an
          example, see “Modify Form, Feedthrough, and Disturbance-Model Matrices” on page 1-1304.
          Direct feedthrough from input to output, specified as the comma-separated pair consisting of
          'Feedthrough' and a logical vector of length Nu, where Nu is the number of inputs. If you specify
          Feedthrough as a logical scalar, that value is applied to all the inputs. For static systems, the
          software always assumes 'Feedthrough' is 1.
For an example, see “Modify Form, Feedthrough, and Disturbance-Model Matrices” on page 1-1304.
          Option to estimate time-domain noise component parameters in the K matrix, specified as the comma-
          separated pair consisting of 'DisturbanceModel' and one of the following values:
          • 'estimate' — Estimate the noise component. The K matrix is treated as a free parameter.
          • 'none' — Do not estimate the noise component. The elements of the K matrix are fixed at zero.
For an example, see “Modify Form, Feedthrough, and Disturbance-Model Matrices” on page 1-1304.
          Output Arguments
          sys — Identified state-space model
          idss model
          Identified state-space model, returned as an idss model. This model is created using the specified
          model orders, delays, and estimation options.
          Information about the estimation results and options used is stored in the Report property of the
          model. Report has the following fields.
           Report      Description
           Field
           Status      Summary of the model status, which indicates whether the model was created by
                       construction or obtained by estimation.
           Method      Estimation command used.
1-1312
                                                                                                ssest
Report      Description
Field
InitialSt How initial states were handled during estimation, returned as one of the following
ate       values:
            This field is especially useful when the InitialState option in the estimation option
            set is 'auto'.
N4Weight    Weighting scheme used for singular-value decomposition by the N4SID algorithm,
            returned as one of the following values:
            This option is especially useful when the N4Weight option in the estimation option set
            is 'auto'.
N4Horizon Forward and backward prediction horizons used by the N4SID algorithm, returned as a
          row vector with three elements — [r sy su], where r is the maximum forward
          prediction horizon. sy is the number of past outputs, and su is the number of past
          inputs that are used for the predictions.
Fit         Quantitative assessment of the estimation, returned as a structure. See “Loss Function
            and Model Quality Metrics” for more information on these quality metrics. The
            structure has the following fields:
             Field        Description
             FitPerce Normalized root mean squared error (NRMSE) measure of how well the
             nt       response of the model fits the estimation data, expressed as the
                      percentage fit = 100(1-NRMSE).
             LossFcn      Value of the loss function when the estimation completes.
             MSE          Mean squared error (MSE) measure of how well the response of the
                          model fits the estimation data.
             FPE          Final prediction error for the model.
             AIC          Raw Akaike Information Criteria (AIC) measure of model quality.
             AICc         Small sample-size corrected AIC.
             nAIC         Normalized AIC.
             BIC          Bayesian Information Criteria (BIC).
                                                                                              1-1313
1   Functions
           Report       Description
           Field
           Parameter Estimated values of model parameters.
           s
           OptionsUs Option set used for estimation. If no custom options were configured, this is a set of
           ed        default options. See ssestOptions for more information.
           RandState State of the random number stream at the start of estimation. Empty, [], if
                     randomization was not used during estimation. For more information, see rng in the
                     MATLAB documentation.
           DataUsed     Attributes of the data used for estimation. Structure with the following fields:
                        Field         Description
                        Name          Name of the data set.
                        Type          Data type.
                        Length        Number of data samples.
                        Ts            Sample time. This is equivalent to Data.Ts.
                        InterSam Input intersample behavior. One of the following values:
                        ple
                                 • 'zoh' — Zero-order hold maintains a piecewise-constant input signal
                                    between samples.
                                      • 'foh' — First-order hold maintains a piecewise-linear input signal
                                        between samples.
                                      • 'bl' — Band-limited behavior specifies that the continuous-time input
                                        signal has zero power above the Nyquist frequency.
1-1314
                                                                                                    ssest
Report       Description
Field
Terminati Termination conditions for the iterative search used for prediction error minimization.
on        Structure with the following fields:
              Field        Description
              WhyStop      Reason for terminating the numerical search.
              Iteratio Number of search iterations performed by the estimation algorithm.
              ns
              FirstOrd ∞-norm of the gradient search vector when the search algorithm
              erOptima terminates.
              lity
              FcnCount Number of times the objective function was called.
              UpdateNo Norm of the gradient search vector in the last iteration. Omitted when the
              rm       search method is 'lsqnonlin' or 'fmincon'.
              LastImpr Criterion improvement in the last iteration, expressed as a percentage.
              ovement Omitted when the search method is 'lsqnonlin' or 'fmincon'.
              Algorith Algorithm used by 'lsqnonlin' or 'fmincon' search method. Omitted
              m        when other search methods are used.
             For estimation methods that do not require numerical search optimization, the
             Termination field is omitted.
Initial states computed during the estimation, returned as an array containing a column vector
corresponding to each experiment.
This array is also stored in the Parameters field of the model Report property.
For an example, see “Estimate Initial States as Independent Parameters” on page 1-1305.
Algorithms
ssest initializes the parameter estimates using either a noniterative subspace approach or an
iterative rational function estimation approach. It then refines the parameter values using the
prediction error minimization approach. For more information, see pem and ssestOptions.
References
[1] Ljung, L. System Identification: Theory for the User, Second Edition. Upper Saddle River, NJ:
        Prentice Hall PTR, 1999.
                                                                                               1-1315
1   Functions
          Extended Capabilities
          Automatic Parallel Support
          Accelerate code by automatically running computation in parallel using Parallel Computing Toolbox™.
          Parallel computing support is available for estimation using the lsqnonlin search method (requires
          Optimization Toolbox). To enable parallel computing, use ssestOptions, set SearchMethod to
          'lsqnonlin', and set SearchOptions.Advanced.UseParallel to true.
For example:
          opt = ssestOptions;
          opt.SearchMethod = 'lsqnonlin';
          opt.SearchOptions.Advanced.UseParallel = true;
          See Also
          Functions
          canon | iddata | idfrd | idgrey | idss | n4sid | pem | polyest | procest | ssestOptions |
          ssregest | tfest
          Topics
          “Estimate State-Space Models at the Command Line”
          “Estimate State-Space Models with Free-Parameterization”
          “Estimate State-Space Models with Canonical Parameterization”
          “Estimate State-Space Models with Structured Parameterization”
          “Use State-Space Estimation to Reduce Model Order”
          “What Are State-Space Models?”
          “Supported State-Space Parameterizations”
          “State-Space Model Estimation Methods”
          “Regularized Estimates of Model Parameters”
          “Estimating Models Using Frequency-Domain Data”
Introduced in R2012a
1-1316
                                                                                           ssestOptions
ssestOptions
Option set for ssest
Syntax
opt = ssestOptions
opt = ssestOptions(Name,Value)
Description
opt = ssestOptions creates the default option set for ssest.
opt = ssestOptions(Name,Value) creates an option set with the options specified by one or
more Name,Value pair arguments.
Input Arguments
Name-Value Pair Arguments
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Algorithm used to initialize the state-space parameter values for ssest, specified as one of the
following values:
   • lsrf, if the system is non-MIMO, the data is frequency-domain, and the state-space
     parameters are real-valued.
   • n4sid otherwise (time-domain, MIMO, or with complex-valued state-space parameters).
• 'n4sid' — Subspace state-space estimation approach — can be used with all systems (see
  n4sid).
• 'lsrf' — Least-squares rational function estimation-based approach [7] (see “Continuous-Time
  Transfer Function Estimation Using Continuous-Time Frequency-Domain Data” on page 1-1411) —
  can provide higher-accuracy results for non-MIMO frequency-domain systems with real-valued
  state-space parameters, but cannot be used for any other systems (time-domain, MIMO, or with
  complex-valued state-space parameters).
Handling of initial states during estimation, specified as one of the following values:
                                                                                               1-1317
1   Functions
          Weighting scheme used for singular-value decomposition by the N4SID algorithm, specified as one of
          the following values:
                Specifying this option allows unbiased estimates when using data that is collected in closed-loop
                operation. For more information about the algorithm, see [6].
          • 'auto' — The estimating function chooses between the MOESP and CVA algorithms.
          Forward and backward prediction horizons used by the N4SID algorithm, specified as one of the
          following values:
          • A row vector with three elements — [r sy su], where r is the maximum forward prediction
            horizon. The algorithm uses up to r step-ahead predictors. sy is the number of past outputs, and
            su is the number of past inputs that are used for the predictions. See pages 209 and 210 in [4] for
            more information. These numbers can have a substantial influence on the quality of the resulting
            model, and there are no simple rules for choosing them. Making 'N4Horizon' a k-by-3 matrix
            means that each row of 'N4Horizon' is tried, and the value that gives the best (prediction) fit to
            data is selected. k is the number of guesses of [r sy su] combinations. If you specify
            N4Horizon as a single column, r = sy = su is used.
          • 'auto' — The software uses an Akaike Information Criterion (AIC) for the selection of sy and su.
          Error to be minimized in the loss function during estimation, specified as the comma-separated pair
          consisting of 'Focus' and one of the following values:
1-1318
                                                                                            ssestOptions
• 'prediction' — The one-step ahead prediction error between measured and predicted outputs
  is minimized during estimation. As a result, the estimation focuses on producing a good predictor
  model.
• 'simulation' — The simulation error between measured and simulated outputs is minimized
  during estimation. As a result, the estimation focuses on making a good fit for simulation of model
  response with the current inputs.
The Focus option can be interpreted as a weighting filter in the loss function. For more information,
see “Loss Function and Model Quality Metrics”.
Weighting prefilter applied to the loss function to be minimized during estimation. To understand the
effect of WeightingFilter on the loss function, see “Loss Function and Model Quality Metrics”.
   Passbands are expressed in rad/TimeUnit for time-domain data and in FrequencyUnit for
   frequency-domain data, where TimeUnit and FrequencyUnit are the time and frequency units
   of the estimation data.
• SISO filter — Specify a single-input-single-output (SISO) linear filter in one of the following ways:
      This option calculates the weighting function as a product of the filter and the input spectrum
      to estimate the transfer function.
• Weighting vector — Applicable for frequency-domain data only. Specify a column vector of
  weights. This vector must have the same length as the frequency vector of the data set,
  Data.Frequency. Each input and output response in the data is multiplied by the corresponding
  weight at that frequency.
• 'invsqrt' — Applicable for frequency-domain data only, with InitializeMethod set to
  'lsrf' only. Uses 1/ G(ω) as the weighting filter, where G(ω) is the complex frequency-
  response data. Use this option for capturing relatively low amplitude dynamics in data.
• 'inv' — Applicable for frequency-domain data only, with InitializeMethod set to 'lsrf'
  only. Uses 1/ G(ω) as the weighting filter. Similarly to 'invsqrt', this option captures relatively
  low-amplitude dynamics in data. Use it when 'invsqrt' weighting produces an estimate that is
  missing dynamics in the low-amplitude regions. 'inv' is more sensitive to noise than 'invsqrt'.
                                                                                                1-1319
1   Functions
          Control whether to enforce stability of estimated model, specified as the comma-separated pair
          consisting of 'EnforceStability' and either true or false.
          Data Types: logical
          If EstimateCovariance is true, then use getcov to fetch the covariance matrix from the
          estimated model.
Specify whether to display the estimation progress, specified as one of the following values:
          • 'on' — Information on model structure and estimation results are displayed in a progress-viewer
            window.
          • 'off' — No progress or results information is displayed.
          Removal of offset from time-domain input data during estimation, specified as the comma-separated
          pair consisting of 'InputOffset' and one of the following:
          • A column vector of positive integers of length Nu, where Nu is the number of inputs.
          • [] — Indicates no offset.
          • Nu-by-Ne matrix — For multi-experiment data, specify InputOffset as an Nu-by-Ne matrix. Nu
            is the number of inputs, and Ne is the number of experiments.
Each entry specified by InputOffset is subtracted from the corresponding input data.
          Removal of offset from time-domain output data during estimation, specified as the comma-separated
          pair consisting of 'OutputOffset' and one of the following:
Each entry specified by OutputOffset is subtracted from the corresponding output data.
Weighting of prediction errors in multi-output estimations, specified as one of the following values:
1-1320
                                                                                           ssestOptions
• 'noise' — Minimize det(E′ * E/N), where E represents the prediction error and N is the number
  of data samples. This choice is optimal in a statistical sense and leads to maximum likelihood
  estimates if nothing is known about the variance of the noise. It uses the inverse of the estimated
  noise variance as the weighting function.
   • E is the matrix of prediction errors, with one column for each output, and W is the positive
     semidefinite symmetric matrix of size equal to the number of outputs. Use W to specify the
     relative importance of outputs in multiple-output models, or the reliability of corresponding
     data.
   • N is the number of data samples.
• [] — The software chooses between the 'noise' or using the identity matrix for W.
Options for regularized estimation of model parameters. For more information on regularization, see
“Regularized Estimates of Model Parameters”.
Specify a positive scalar to add the regularization term to the estimation cost.
   Default: 0
• R — Weighting matrix.
   Specify a vector of nonnegative numbers or a square positive semi-definite matrix. The length
   must be equal to the number of free parameters of the model.
   For black-box models, using the default value is recommended. For structured and grey-box
   models, you can also specify a vector of np positive numbers such that each entry denotes the
   confidence in the value of the associated parameter.
   The default value of 1 implies a value of eye(npfree), where npfree is the number of free
   parameters.
   Default: 1
• Nominal — The nominal value towards which the free parameters are pulled during estimation.
   The default value of zero implies that the parameter values are pulled towards zero. If you are
   refining a model, you can set the value to 'model' to pull the parameters towards the parameter
   values of the initial model. The initial parameter values must be finite for this setting to work.
Default: 0
                                                                                              1-1321
1   Functions
          Numerical search method used for iterative parameter estimation, specified as the comma-separated
          pair consisting of 'SearchMethod' and one of the following:
          • 'auto' — A combination of the line search algorithms, 'gn', 'lm', 'gna', and 'grad' methods
            is tried in sequence at each iteration. The first descent direction leading to a reduction in
            estimation cost is used.
          • 'gn' — Subspace Gauss-Newton least squares search. Singular values of the Jacobian matrix less
            than GnPinvConstant*eps*max(size(J))*norm(J) are discarded when computing the
            search direction. J is the Jacobian matrix. The Hessian matrix is approximated as JTJ. If there is no
            improvement in this direction, the function tries the gradient direction.
          • 'gna' — Adaptive subspace Gauss-Newton search. Eigenvalues less than gamma*max(sv) of the
            Hessian are ignored, where sv contains the singular values of the Hessian. The Gauss-Newton
            direction is computed in the remaining subspace. gamma has the initial value
            InitialGnaTolerance (see Advanced in 'SearchOptions' for more information). This value
            is increased by the factor LMStep each time the search fails to find a lower value of the criterion
            in fewer than five bisections. This value is decreased by the factor 2*LMStep each time a search is
            successful without any bisections.
          • 'lm' — Levenberg-Marquardt least squares search, where the next parameter value is -pinv(H
            +d*I)*grad from the previous one. H is the Hessian, I is the identity matrix, and grad is the
            gradient. d is a number that is increased until a lower value of the criterion is found.
          • 'grad' — Steepest descent least squares search.
          • 'lsqnonlin' — Trust-region-reflective algorithm of lsqnonlin. Requires Optimization Toolbox
            software.
          • 'fmincon' — Constrained nonlinear solvers. You can use the sequential quadratic programming
            (SQP) and trust-region-reflective algorithms of the fmincon solver. If you have Optimization
            Toolbox software, you can also use the interior-point and active-set algorithms of the fmincon
            solver. Specify the algorithm in the SearchOptions.Algorithm option. The fmincon algorithms
            may result in improved estimation results in the following scenarios:
                • Constrained minimization problems when there are bounds imposed on the model parameters.
                • Model structures where the loss function is a nonlinear or non smooth function of the
                  parameters.
                • Multi-output model estimation. A determinant loss function is minimized by default for multi-
                  output model estimation. fmincon algorithms are able to minimize such loss functions directly.
                  The other search methods such as 'lm' and 'gn' minimize the determinant loss function by
                  alternately estimating the noise variance and reducing the loss value for a given noise variance
                  value. Hence, the fmincon algorithms can offer better efficiency and accuracy for multi-output
                  model estimations.
          Option set for the search algorithm, specified as the comma-separated pair consisting of
          'SearchOptions' and a search option set with fields that depend on the value of SearchMethod.
1-1322
                                                                                      ssestOptions
                                                                                            1-1323
1   Functions
1-1324
                                                                                        ssestOptions
                                                                                           1-1325
1   Functions
                                      • 'sqp' — Sequential
                                        quadratic programming
                                        algorithm. The algorithm
                                        satisfies bounds at all
                                        iterations, and it can recover
                                        from NaN or Inf results. It is
                                        not a large-scale algorithm.
                                        For more information, see
                                        “Large-Scale vs. Medium-
                                        Scale Algorithms”
                                        (Optimization Toolbox).
                                      • 'trust-region-
                                        reflective' — Subspace
                                        trust-region method based
                                        on the interior-reflective
                                        Newton method. It is a large-
                                        scale algorithm.
                                      • 'interior-point' —
                                        Large-scale algorithm that
                                        requires Optimization
                                        Toolbox software. The
                                        algorithm satisfies bounds at
                                        all iterations, and it can
                                        recover from NaN or Inf
                                        results.
                                      • 'active-set' — Requires
                                        Optimization Toolbox
                                        software. The algorithm can
                                        take large steps, which adds
                                        speed. It is not a large-scale
                                        algorithm.
1-1326
                                                                                           ssestOptions
• ErrorThreshold — Specifies when to adjust the weight of large errors from quadratic to linear.
   Errors larger than ErrorThreshold times the estimated standard deviation have a linear weight
   in the loss function. The standard deviation is estimated robustly as the median of the absolute
   deviations from the median of the prediction errors, divided by 0.7. For more information on
   robust norm choices, see section 15.2 of [4].
   Default: 0
• MaxSize — Specifies the maximum number of elements in a segment when input-output data is
  split into segments.
   Default: 250000
• StabilityThreshold — Specifies thresholds for stability tests.
   • s — Specifies the location of the right-most pole to test the stability of continuous-time models.
     A model is considered stable when its right-most pole is to the left of s.
      Default: 0
   • z — Specifies the maximum distance of all poles from the origin to test stability of discrete-
     time models. A model is considered stable if all poles are within the distance z from the origin.
                                                                                               1-1327
1   Functions
                   Default: 1+sqrt(eps)
          • AutoInitThreshold — Specifies when to automatically estimate the initial conditions.
                  yp, z − ymeas
                                > AutoInitThreshold
                  yp, e − ymeas
                Default: 1.05
          • DDC — Specifies if the Data Driven Coordinates algorithm [5] is used to estimate freely
            parameterized state-space models.
                • 'on' — The free parameters are projected to a reduced space of identifiable parameters using
                  the Data Driven Coordinates algorithm.
                • 'off' — All the entries of A, B, and C updated directly using the chosen SearchMethod.
Default: 'on'
          Output Arguments
          opt — Option set for ssest
          ssestOptions option set
Examples
opt = ssestOptions;
          Create an option set for ssest using the 'backcast' algorithm to initialize the state and set the
          Display to 'on'.
opt = ssestOptions('InitialState','backcast','Display','on');
1-1328
                                                                                              ssestOptions
opt = ssestOptions;
opt.InitialState = 'backcast';
opt.Display = 'on';
Compatibility Considerations
Renaming of Estimation and Analysis Options
The names of some estimation and analysis options were changed in R2018a. Prior names still work.
For details, see the R2018a release note “Renaming of Estimation and Analysis Options”.
References
[1] Larimore, W.E. "Canonical variate analysis in identification, filtering and adaptive control."
        Proceedings of the 29th IEEE Conference on Decision and Control, pp. 596–604, 1990.
[2] Verhaegen, M. “Identification of the deterministic part of MIMO state space models.” Automatica,
        Vol. 30, No. 1, 1994, pp. 61–74.
[3] Wills, Adrian, B. Ninness, and S. Gibson. “On Gradient-Based Search for Multivariable System
         Estimates.” Proceedings of the 16th IFAC World Congress, Prague, Czech Republic, July 3–8,
         2005. Oxford, UK: Elsevier Ltd., 2005.
[4] Ljung, L. System Identification: Theory for the User. Upper Saddle River, NJ: Prentice-Hall PTR,
        1999.
[5] McKelvey, T., A. Helmersson,, and T. Ribarits. “Data driven local coordinates for multivariable
       linear systems and their application to system identification.” Automatica, Volume 40, No. 9,
       2004, pp. 1629–1635.
[6] Jansson, M. “Subspace identification and ARX modeling.” 13th IFAC Symposium on System
        Identification , Rotterdam, The Netherlands, 2003.
[7] Ozdemir, A. A., and S. Gumossoy. "Transfer Function Estimation in System identification Toolbox
       via Vector Fitting." Proceedings of the 20th World Congress of the International Federation of
       Automatic Control. Toulouse, France, July 2017.
See Also
ssest
Topics
“Loss Function and Model Quality Metrics”
Introduced in R2012a
                                                                                                     1-1329
1   Functions
          ssform
          Quick configuration of state-space model structure
          Syntax
          sys1 = ssform(sys,Name,Value)
          Description
          sys1 = ssform(sys,Name,Value) specifies the type of parameterization and whether
          feedthrough and disturbance dynamics are present for the state-space model sys using one or more
          Name,Value pair arguments.
          Input Arguments
          sys
State-space model
Default:
          Specify comma-separated pairs of Name,Value arguments, where Name is the argument name and
          Value is the corresponding value. Name must appear inside single quotes (' '). You can specify
          several name and value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Form
• 'free'
                Companion form of the model where the characteristic polynomial appears in the far-right column
                of the state matrix A
          • 'modal'
                Modal decomposition form, where the state matrix A is block diagonal. Each block corresponds to
                a real or complex-conjugate pair of poles.
                You cannot use this value for models with repeated poles.
          • 'canonical'
Default:
1-1330
                                                                                                  ssform
Feedthrough
Specify whether the model has direct feedthrough from the input u(t) to the output y(t), (whether the
elements of the matrix D are nonzero).
Must be a logical vector (true or false) of length equal to the number of inputs (Nu).
Note Specifying this option for a previously estimated model causes the model parameter covariance
information to be lost. Use translatecov to recompute the covariance.
Default:
DisturbanceModel
Specify whether to estimate the noise component of the model, specified as one of the following
values:
• 'none'
Note Specifying this option for a previously estimated model causes the model parameter covariance
information to be lost. Use translatecov to recompute the covariance.
Default:
Output Arguments
sys1
Examples
                                                                                              1-1331
1   Functions
          D = 0;
          K = randn(2,1);
          model = idss(A,B,C,D,K,'Ts',0);
model1 = ssform(model,'Form','canonical');
          rng('default');
          A = randn(2) - 2*eye(2);
          B = randn(2,1);
          C = randn(1,2);
          D = 0;
          K = randn(2,1);
          model = idss(A,B,C,D,K,'Ts',0);
Convert the model to observability canonical form and specify to estimate its feedthrough behavior.
model2 = ssest(z1,model1);
          Alternatives
          Use the Structure property of an idss model to specify the parameterization, feedthrough, and
          disturbance dynamics by modifying the Value and Free attributes of the A, B, C, D and K parameters.
References
          [1] Ljung, L. System Identification: Theory For the User, Second Edition, Appendix 4A, pp 132-134,
                  Upper Saddle River, N.J: Prentice Hall, 1999.
          See Also
          idss | n4sid | ssest
          Topics
          “Estimate State-Space Models at the Command Line”
1-1332
                                             ssform
Introduced in R2012b
                                            1-1333
1   Functions
          ssregest
          Estimate state-space model by reduction of regularized ARX model
          Syntax
          sys = ssregest(data,nx)
          sys = ssregest(data,nx,Name,Value)
          sys = ssregest( ___ ,opt)
          Description
          sys = ssregest(data,nx) estimates a state-space model by reduction of a regularized ARX
          model.
          sys = ssregest( ___ ,opt) specifies estimation options that configure the estimation objective,
          ARX orders, and order reduction options. This syntax can include any of the input argument
          combinations in the previous syntaxes.
          [sys,x0] = ssregest( ___ ) returns the value of initial states computed during estimation. This
          syntax can include any of the input argument combinations in the previous syntaxes.
Examples
sys = ssregest(z2,3);
load iddata2 z2
1-1334
                                                                                              ssregest
sys = ssregest(z2,3,'InputDelay',2);
Specify the order of the regularized ARX model used by the software during estimation. Also, set the
estimation focus to simulation.
sys = ssregest(z2,3,opt);
Obtain the initial state values when identifying a third-order state-space model.
[sys,x0] = ssregest(z2,3);
Load data.
Create a transfer function model used for generating the estimation data (true system).
opt = impulseestOptions('RegularizationKernel','DC');
m0 = impulseest(eData,70,opt);
Convert the model into a state-space model and reduce the model order.
m1 = balred(idss(m0),15);
m2 = ssregest(eData,15);
                                                                                             1-1335
1   Functions
          Compare the impulse responses of the true system and the estimated models.
          impulse(trueSys,m1,m2,50);
          legend('trueSys','m1','m2');
          Input Arguments
          data — Estimation data
          iddata | idfrd | frd
          For time-domain estimation, data must be an iddata object containing the input and output signal
          values.
1-1336
                                                                                                ssregest
If nx is a vector, then ssregest creates a plot which you can use to choose a suitable model order.
The plot shows the Hankel singular values for models of chosen values in the vector. States with
relatively small Hankel singular values can be safely discarded. A default choice is suggested in the
plot.
You can also specify nx = 'best', as in ssregest(data,'best'), in which case the optimal order
is chosen automatically in the 1:10 range.
Estimation options for ssregest, specified as an options set you create using ssregestOptions.
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Example: sys = ssregest(z2,3,'InputDelay',2) specifies a delay of 2 sampling periods.
Ts — Sample time
sample time of data (data.Ts) (default) | positive scalar | 0
Sample time of the model, specified as 0 or equal to the sample time of data.
For continuous-time models, use Ts = 0. For discrete-time models, specify Ts as a positive scalar
whose value is equal to the data sample time.
Input delay for each input channel, specified as a numeric vector. For continuous-time systems,
specify input delays in the time unit stored in the TimeUnit property. For discrete-time systems,
specify input delays in integer multiples of the sample time Ts. For example, InputDelay = 3
means a delay of three sampling periods.
For a system with Nu inputs, set InputDelay to an Nu-by-1 vector. Each entry of this vector is a
numerical value that represents the input delay for the corresponding input channel.
You can also set InputDelay to a scalar value to apply the same delay to all channels.
                                                                                               1-1337
1   Functions
          Use the Form, Feedthrough and DisturbanceModel name-value pair arguments to modify the
          default behavior of the A, B, C, D, and K matrices.
          Direct feedthrough from input to output, specified as a logical vector of length Nu, where Nu is the
          number of inputs. If Feedthrough is specified as a logical scalar, it is applied to all the inputs.
          Use the Form, Feedthrough and DisturbanceModel name-value pair arguments to modify the
          default behavior of the A, B, C, D, and K matrices.
          Specify whether to estimate the K matrix which specifies the noise component, specified as one of the
          following values:
          • 'none' — Noise component is not estimated. The value of the K matrix is fixed to zero value.
          • 'estimate' — The K matrix is treated as a free parameter.
          Use the Form, Feedthrough and DisturbanceModel name-value pair arguments to modify the
          default behavior of the A, B, C, D, and K matrices.
          Output Arguments
          sys — Estimated state-space model
          idss
Estimated state-space model of order nx, returned as an idss model object. The model represents:
          A, B, C, D, and K are state-space matrices. u(t) is the input, y(t) is the output, e(t) is the disturbance
          and x(t) is the vector of nx states.
          All the entries of A, B, C, and K are free estimable parameters by default. D is fixed to zero by default,
          meaning that there is no feedthrough, except for static systems (nx=0).
          Information about the estimation results and options used is stored in the Report property of the
          model. Report has the following fields:
           Report        Description
           Field
           Status        Summary of the model status, which indicates whether the model was created by
                         construction or obtained by estimation.
1-1338
                                                                                              ssregest
Report       Description
Field
Method       Estimation command used.
InitialSt Handling of initial states during estimation, returned as one of the following values:
ate
          • 'zero' — The initial state was set to zero.
             • 'estimate' — The initial state was treated as an independent estimation
               parameter.
             This field is especially useful when the InitialState option in the estimation option
             set is 'auto'.
ARXOrder     ARX model orders, returned as a matrix of nonnegative integers [na nb nk].
Fit          Quantitative assessment of the estimation, returned as a structure. See “Loss Function
             and Model Quality Metrics” for more information on these quality metrics. The
             structure has the following fields:
             Field         Description
             FitPerce Normalized root mean squared error (NRMSE) measure of how well the
             nt       response of the model fits the estimation data, expressed as the
                      percentage fit = 100(1-NRMSE).
             LossFcn       Value of the loss function when the estimation completes.
             MSE           Mean squared error (MSE) measure of how well the response of the
                           model fits the estimation data.
             FPE           Final prediction error for the model.
             AIC           Raw Akaike Information Criteria (AIC) measure of model quality.
             AICc          Small sample-size corrected AIC.
             nAIC          Normalized AIC.
             BIC           Bayesian Information Criteria (BIC).
Parameter Estimated values of model parameters.
s
OptionsUs Option set used for estimation. If no custom options were configured, this is a set of
ed        default options. See ssregestOptions for more information.
RandState State of the random number stream at the start of estimation. Empty, [], if
          randomization was not used during estimation. For more information, see rng in the
          MATLAB documentation.
                                                                                             1-1339
1   Functions
           Report       Description
           Field
           DataUsed     Attributes of the data used for estimation, returned as a structure with the following
                        fields:
                        Field         Description
                        Name          Name of the data set.
                        Type          Data type.
                        Length        Number of data samples.
                        Ts            Sample time.
                        InterSam Input intersample behavior, returned as one of the following values:
                        ple
                                 • 'zoh' — Zero-order hold maintains a piecewise-constant input signal
                                    between samples.
                                      • 'foh' — First-order hold maintains a piecewise-linear input signal
                                        between samples.
                                      • 'bl' — Band-limited behavior specifies that the continuous-time input
                                        signal has zero power above the Nyquist frequency.
                        InputOff Offset removed from time-domain input data during estimation. For
                        set      nonlinear models, it is [].
                        OutputOf Offset removed from time-domain output data during estimation. For
                        fset     nonlinear models, it is [].
          Initial states computed during estimation, returned as a scalar. If data contains multiple
          experiments, then x0 is a matrix with each column corresponding to an experiment.
This value is also stored in the Parameters field of the model’s Report property.
          More About
          Modal Form
          In modal form, A is a block-diagonal matrix. The block size is typically 1-by-1 for real eigenvalues and
          2-by-2 for complex eigenvalues. However, if there are repeated eigenvalues or clusters of nearby
          eigenvalues, the block size can be larger.
For example, for a system with eigenvalues (λ1, σ ± jω, λ2), the modal A matrix is of the form
                λ1 0 0 0
                0 σ ω 0
                0 −ω σ 0
                0   0 0 λ2
1-1340
                                                                                                ssregest
Companion Form
In the companion realization, the characteristic polynomial of the system appears explicitly in the
rightmost column of the A matrix.
P(s) = sn + α1sn − 1 + … + αn − 1s + αn
          0 0 0 … 0 −αn
          1 0 0 … 0 −αn − 1
          0 1 0 … 0 −αn − 2
    A=
          0 0 1 … 0 −αn − 3
          ⋮ ⋮ ⋮ ⋱ ⋮   ⋮
          0 0 0 … 1 −α1
The companion transformation requires that the system be controllable from the first input. The
companion form is poorly conditioned for most state-space computations; avoid using it when
possible.
Tips
• ssregest function provides improved accuracy than n4sid for short, noisy data sets.
• For some problems, the quality of fit using n4sid is sensitive to options, such as N4Horizon,
  whose values can be difficult to determine. In comparison, the quality of fit with ssregest is less
  sensitive to its options, which makes ssregest simpler to use.
Algorithms
ssregest estimates a regularized ARX model and converts the ARX model to a state-space model.
The software then uses balanced model reduction techniques to reduce the state-space model to the
specified order.
References
[1] Ljung, L. System Identification: Theory For the User, Second Edition, Appendix 4A, pp 132-134,
        Upper Saddle River, N.J: Prentice Hall, 1999.
See Also
arx | arxRegul | balred | n4sid | ssest | ssregestOptions
Topics
“Regularized Estimates of Model Parameters”
Introduced in R2014a
                                                                                               1-1341
1   Functions
          ssregestOptions
          Option set for ssregest
          Syntax
          options = ssregestOptions
          options = ssregestOptions(Name,Value)
          Description
          options = ssregestOptions creates a default option set for ssregest.
Examples
          Create Default Option Set for State-Space Estimation Using Reduction of Regularized ARX
          Model
options = ssregestOptions;
Specify Options for State-Space Estimation Using Reduction of Regularized ARX Model
          Create an option set for ssregest that fixes the value of the initial states to 'zero'. Also, set the
          Display to 'on'.
opt = ssregestOptions('InitialState','zero','Display','on');
          opt = ssregestOptions;
          opt.InitialState = 'zero';
          opt.Display = 'on';
          Input Arguments
          Name-Value Pair Arguments
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
          Example: opt = ssregestOptions('InitialState','zero') fixes the value of the initial states
          to zero.
1-1342
                                                                                          ssregestOptions
Handling of initial states during estimation, specified as one of the following values:
ARX model orders, specified as a matrix of nonnegative integers [na nb nk]. The max(ARXOrder)
+1 must be greater than the desired state-space model order (number of states). If you specify a
value, it is recommended that you use a large value for nb order. To learn more about ARX model
orders, see arx.
Regularizing kernel used for regularized estimates of the underlying ARX model, specified as one of
the following values:
Options for model order reduction, specified as a structure with the following fields:
• StateElimMethod
   State elimination method. Specifies how to eliminate the weakly coupled states (states with
   smallest Hankel singular values). Specified as one of the following values:
       'MatchDC'              Discards the specified states and alters the remaining states to preserve
                              the DC gain.
       'Truncate'             Discards the specified states without altering the remaining states. This
                              method tends to product a better approximation in the frequency
                              domain, but the DC gains are not guaranteed to match.
   Default: 'Truncate'
• AbsTol, RelTol
   Absolute and relative error tolerance for stable/unstable decomposition. Positive scalar values. For
   an input model G with unstable poles, the reduction algorithm of ssregest first extracts the
                                                                                                1-1343
1   Functions
                stable dynamics by computing the stable/unstable decomposition G → GS + GU. The AbsTol and
                RelTol tolerances control the accuracy of this decomposition by ensuring that the frequency
                responses of G and GS + GU differ by no more than AbsTol + RelTol*abs(G). Increasing these
                tolerances helps separate nearby stable and unstable modes at the expense of accuracy. See
                stabsep for more information.
                Offset for the stable/unstable boundary. Positive scalar value. In the stable/unstable
                decomposition, the stable term includes only poles satisfying
Increase the value of Offset to treat poles close to the stability boundary as unstable.
Default: 1e-8
          Error to be minimized in the loss function during estimation, specified as the comma-separated pair
          consisting of 'Focus' and one of the following values:
          • 'prediction' — The one-step ahead prediction error between measured and predicted outputs
            is minimized during estimation. As a result, the estimation focuses on producing a good predictor
            model.
          • 'simulation' — The simulation error between measured and simulated outputs is minimized
            during estimation. As a result, the estimation focuses on making a good fit for simulation of model
            response with the current inputs.
          The Focus option can be interpreted as a weighting filter in the loss function. For more information,
          see “Loss Function and Model Quality Metrics”.
          Weighting prefilter applied to the loss function to be minimized during estimation. To understand the
          effect of WeightingFilter on the loss function, see “Loss Function and Model Quality Metrics”.
                Passbands are expressed in rad/TimeUnit for time-domain data and in FrequencyUnit for
                frequency-domain data, where TimeUnit and FrequencyUnit are the time and frequency units
                of the estimation data.
1-1344
                                                                                         ssregestOptions
• SISO filter — Specify a single-input-single-output (SISO) linear filter in one of the following ways:
      This option calculates the weighting function as a product of the filter and the input spectrum
      to estimate the transfer function.
• Weighting vector — Applicable for frequency-domain data only. Specify a column vector of
  weights. This vector must have the same length as the frequency vector of the data set,
  Data.Frequency. Each input and output response in the data is multiplied by the corresponding
  weight at that frequency.
If EstimateCovariance is true, then use getcov to fetch the covariance matrix from the
estimated model.
Specify whether to display the estimation progress, specified as one of the following values:
• 'on' — Information on model structure and estimation results are displayed in a progress-viewer
  window.
• 'off' — No progress or results information is displayed.
Removal of offset from time-domain input data during estimation, specified as the comma-separated
pair consisting of 'InputOffset' and one of the following:
• A column vector of positive integers of length Nu, where Nu is the number of inputs.
• [] — Indicates no offset.
• Nu-by-Ne matrix — For multi-experiment data, specify InputOffset as an Nu-by-Ne matrix. Nu
  is the number of inputs, and Ne is the number of experiments.
Each entry specified by InputOffset is subtracted from the corresponding input data.
Removal of offset from time-domain output data during estimation, specified as the comma-separated
pair consisting of 'OutputOffset' and one of the following:
                                                                                                1-1345
1   Functions
          • [] — Indicates no offset.
          • Ny-by-Ne matrix — For multi-experiment data, specify OutputOffset as a Ny-by-Ne matrix. Ny is
            the number of outputs, and Ne is the number of experiments.
Each entry specified by OutputOffset is subtracted from the corresponding output data.
Weight of prediction errors in multi-output estimation, specified as one of the following values:
          • Positive semidefinite, symmetric matrix (W). The software minimizes the trace of the weighted
            prediction error matrix trace(E'*E*W/N) where:
                • E is the matrix of prediction errors, with one column for each output, and W is the positive
                  semidefinite, symmetric matrix of size equal to the number of outputs. Use W to specify the
                  relative importance of outputs in multiple-output models, or the reliability of corresponding
                  data.
                • N is the number of data samples.
          • [] — No weighting is used. Specifying as [] is the same as eye(Ny), where Ny is the number of
            outputs.
Advanced options for regularized estimation, specified as a structure with the following fields:
          • MaxSize — Maximum allowable size of Jacobian matrices formed during estimation, specified as a
            large positive number.
                Default: 250e3
          • SearchMethod — Search method for estimating regularization parameters, specified as one of
            the following values:
Default: 'fmincon'
          Output Arguments
          options — Option set for ssregest
          ssregestOptions options set
1-1346
                                                                                       ssregestOptions
Compatibility Considerations
Renaming of Estimation and Analysis Options
The names of some estimation and analysis options were changed in R2018a. Prior names still work.
For details, see the R2018a release note “Renaming of Estimation and Analysis Options”.
References
[1] T. Chen, H. Ohlsson, and L. Ljung. “On the Estimation of Transfer Functions, Regularizations and
         Gaussian Processes - Revisited”, Automatica, Volume 48, August 2012.
See Also
ssregest
Topics
“Loss Function and Model Quality Metrics”
Introduced in R2014a
                                                                                              1-1347
1   Functions
          stack
          Build model array by stacking models or model arrays along array dimensions
          Syntax
          sys = stack(arraydim,sys1,sys2,...)
          Description
          sys = stack(arraydim,sys1,sys2,...) produces an array of dynamic system models sys by
          stacking (concatenating) the models (or arrays) sys1,sys2,... along the array dimension
          arraydim. All models must have the same number of inputs and outputs (the same I/O dimensions),
          but the number of states can vary. The I/O dimensions are not counted in the array dimensions. For
          more information about model arrays and array dimensions, see “Model Arrays” (Control System
          Toolbox).
          For arrays of state-space models with variable order, you cannot use the dot operator (e.g., sys.A) to
          access arrays. Use the syntax
[A,B,C,D] = ssdata(sys,'cell')
to extract the state-space matrices of each model as separate cells in the cell arrays A, B, C, and D.
          Examples
          Example 1
Example 2
          Stack identified state-space models derived from the same estimation data and compare their bode
          responses.
          load iddata1 z1
          sysc = cell(1,5);
          opt = ssestOptions('Focus','simulation');
          for i = 1:5
          sysc{i} = ssest(z1,i-1,opt);
          end
          sysArray = stack(1, sysc{:});
          bode(sysArray);
Introduced in R2012a
1-1348
                                                                                                    step
step
Step response plot of dynamic system; step response data
Syntax
step(sys)
step(sys,Tfinal)
step(sys,t)
step(sys1,sys2,...,sysN)
step(sys1,sys2,...,sysN,Tfinal)
step(sys1,sys2,...,sysN,t)
y = step(sys,t)
[y,t] = step(sys)
[y,t] = step(sys,Tfinal)
[y,t,x] = step(sys)
[y,t,x,ysd] = step(sys)
[y,...] = step(sys,...,options)
Description
step calculates the step response of a dynamic system. For the state-space case, zero initial state is
assumed. When it is invoked with no output arguments, this function plots the step response on the
screen.
step(sys) plots the step response of an arbitrary dynamic system model, sys. This model can be
continuous- or discrete-time, and SISO or MIMO. The step response of multi-input systems is the
collection of step responses for each input channel. The duration of simulation is determined
automatically, based on the system poles and zeros.
step(sys,Tfinal) simulates the step response from t = 0 to the final time t = Tfinal. Express
Tfinal in the system time units, specified in the TimeUnit property of sys. For discrete-time
systems with unspecified sample time (Ts = -1), step interprets Tfinal as the number of sampling
periods to simulate.
step(sys,t) uses the user-supplied time vector t for simulation. Express t in the system time
units, specified in the TimeUnit property of sys. For discrete-time models, t should be of the form
Ti:Ts:Tf, where Ts is the sample time. For continuous-time models, t should be of the form
Ti:dt:Tf, where dt becomes the sample time of a discrete approximation to the continuous system
(see “Algorithms” on page 1-1356). The step command always applies the step input at t=0,
regardless of Ti.
To plot the step response of several models sys1,..., sysN on a single figure, use
step(sys1,sys2,...,sysN)
step(sys1,sys2,...,sysN,Tfinal)
step(sys1,sys2,...,sysN,t)
                                                                                                1-1349
1   Functions
          All of the systems plotted on a single plot must have the same number of inputs and outputs. You can,
          however, plot a mix of continuous- and discrete-time systems on a single plot. This syntax is useful to
          compare the step responses of multiple systems.
          You can also specify a distinctive color, linestyle, marker, or all three for each system. For example,
          step(sys1,'y:',sys2,'g--')
          plots the step response of sys1 with a dotted yellow line and the step response of sys2 with a green
          dashed line.
y = step(sys,t)
[y,t] = step(sys)
[y,t] = step(sys,Tfinal)
[y,t,x] = step(sys)
          step returns the output response y, the time vector t used for simulation (if not supplied as an input
          argument), and the state trajectories x (for state-space models only). No plot generates on the
          screen. For single-input systems, y has as many rows as time samples (length of t), and as many
          columns as outputs. In the multi-input case, the step responses of each input channel are stacked up
          along the third dimension of y. The dimensions of y are then
          and y(:,:,j) gives the response to a unit step command injected in the jth input channel. Similarly,
          the dimensions of x are
          For identified models (see idlti and idnlmodlel) [y,t,x,ysd] = step(sys) also computes
          the standard deviation ysd of the response y (ysd is empty if sys does not contain parameter
          covariance information).
          [y,...] = step(sys,...,options) specifies additional options for computing the step response,
          such as the step amplitude or input offset. Use stepDataOptions to create the option set options.
Examples
          a = [-0.5572,-0.7814;0.7814,0];
          b = [1,-1;0,2];
1-1350
                                                                                                      step
c = [1.9691,6.4493];
sys = ss(a,b,c,0);
step(sys)
The left plot shows the step response of the first input channel, and the right plot shows the step
response of the second input channel.
Create a feedback loop with delay and plot its step response.
s = tf('s');
G = exp(-s) * (0.8*s^2+s+2)/(s^2+s);
T = feedback(ss(G),1);
step(T)
                                                                                                1-1351
1   Functions
          The system step response displayed is chaotic. The step response of systems with internal delays may
          exhibit odd behavior, such as recurring jumps. Such behavior is a feature of the system and not
          software anomalies.
          Compare the step response of a parametric identified model to a non-parametric (empirical) model.
          Also view their 3 σ confidence regions.
1-1352
                                                                                                step
Validate the linearization of a nonlinear ARX model by comparing the small amplitude step responses
of the linear and nonlinear models.
Determine an equilibrium operating point for nlsys corresponding to a steady-state input value of 1.
u0 = 1;
[X,~,r] = findop(nlsys, 'steady', 1);
y0 = r.SignalLevels.Output;
                                                                                             1-1353
1   Functions
sys = linearize(nlsys,u0,X);
Validate the usefulness of sys by comparing its small-amplitude step response to that of nlsys.
          The nonlinear system nlsys is operating at an equilibrium level dictated by (u0, y0). Introduce a
          step perturbation of size 0.1 about this steady-state and compute the corresponding response.
          opt = stepDataOptions;
          opt.InputOffset = u0;
          opt.StepAmplitude = 0.1;
          t = (0:0.1:10)';
          ynl = step(nlsys, t, opt);
          The linear system sys expresses the relationship between the perturbations in input to the
          corresponding perturbation in output. It is unaware of the nonlinear system's equilibrium values.
          opt = stepDataOptions;
          opt.StepAmplitude = 0.1;
          yl = step(sys, t, opt);
Add the steady-state offset, y0 , to the response of the linear system and plot the responses.
1-1354
                                                                                                   step
A time-series model, also called a signal model, is one without measured input signals. The step plot
of this model uses its (unmeasured) noise channel as the input channel to which the step signal is
applied.
load iddata9;
ys is a model of the form A y(t) = e(t) , where e(t) represents the noise channel. For
computation of step response, e(t) is treated as an input channel, and is named e@y1.
step(sys)
                                                                                               1-1355
1   Functions
          Tips
          You can change the properties of your plot, for example the units. For information on the ways to
          change properties of your plots, see “Ways to Customize Plots” (Control System Toolbox).
          Algorithms
          Continuous-time models without internal delays are converted to state space and discretized using
          zero-order hold on the inputs. The sample time is chosen automatically based on the system
          dynamics, except when a time vector t = 0:dt:Tf is supplied (dt is then used as sampling period).
          The resulting simulation time steps t are equisampled with spacing dt.
          For systems with internal delays, Control System Toolbox software uses variable step solvers. As a
          result, the time steps t are not equisampled.
References
          [1] L.F. Shampine and P. Gahinet, "Delay-differential-algebraic equations in control theory," Applied
                   Numerical Mathematics, Vol. 56, Issues 3–4, pp. 574–588.
          See Also
          Linear System Analyzer | impulse | initial | lsim | stepDataOptions
1-1356
                                                                                                  step
step
Update model parameters and output online using recursive estimation algorithm
Syntax
[EstimatedParameters,EstimatedOutput] = step(obj,y,InputData)
Description
[EstimatedParameters,EstimatedOutput] = step(obj,y,InputData) updates parameters
and output of the model specified in System object, obj, using measured output, y, and input data.
step puts the object into a locked state. In a locked state you cannot change any nontunable
properties of the object, such as model order, data type, or estimation algorithm.
The EstimatedParameters and InputData depend on the online estimation System object:
• recursiveAR — step returns the estimated polynomial A(q) coefficients of a single output AR
  model using time-series output data.
  [A,EstimatedOutput] = step(obj,y)
• recursiveARMA — step returns the estimated polynomial A(q) and C(q) coefficients of a single
  output ARMA model using time-series output data, y.
  [A,C,EstimatedOutput] = step(obj,y)
• recursiveARX — step returns the estimated polynomial A(q) and B(q) coefficients of a SISO or
  MISO ARX model using measured input and output data, u and y, respectively.
  [A,B,EstimatedOutput] = step(obj,y,u).
• recursiveARMAX — step returns the estimated polynomial A(q), B(q), and C(q) coefficients of a
  SISO ARMAX model using measured input and output data, u and y, respectively.
  [A,B,C,EstimatedOutput] = step(obj,y,u).
• recursiveOE — step returns the estimated polynomial B(q), and F(q) coefficients of a SISO
  Output-Error polynomial model using measured input and output data, u and y, respectively.
  [B,F,EstimatedOutput] = step(obj,y,u).
• recursiveBJ — step returns the estimated polynomial B(q), C(q), D(q), and F(q) coefficients of a
  SISO Box-Jenkins polynomial model using measured input and output data, u and y, respectively.
  [B,C,D,F,EstimatedOutput] = step(obj,y,u).
• recursiveLS — step returns the estimated system parameters, θ, of a single output system that
  is linear in estimated parameters, using regressors H and output data y.
  [theta,EstimatedOutput] = step(obj,y,H).
Examples
obj = recursiveARMAX;
                                                                                               1-1357
1   Functions
          The ARMAX model has a default structure with polynomials of order 1 and initial polynomial
          coefficient values, eps.
Load the estimation data. In this example, use a static data set for illustration.
          for i = 1:numel(input)
          [A,B,C,EstimatedOutput] = step(obj,output(i),input(i));
          end
obj.A
ans = 1×2
1.0000 -0.8298
obj.ParameterCovariance
ans = 3×3
EstimatedOutput
EstimatedOutput = -4.5595
obj = recursiveARMAX;
          The ARMAX model has a default structure with polynomials of order 1 and initial polynomial
          coefficient values, eps.
Load the estimation data. In this example, use a static data set for illustration.
1-1358
                                                                                                   step
Estimate ARMAX model parameters online using the default recursive estimation algorithm,
Forgetting Factor. Change the ForgettingFactor property during online parameter estimation.
for i = 1:dataSize
    if i == dataSize/2
        obj.ForgettingFactor = 0.98;
    end
[A,B,C,EstimatedOutput] = step(obj,output(i),input(i));
end
y t = a1u t + a2u t − 1
Here,
Create a System object for online estimation using the recursive least squares algorithm.
obj = recursiveLS(2);
Load the estimation data, which for this example is a static data set.
load iddata3
input = z3.u;
output = z3.y;
Create a variable to store u(t-1). This variable is updated at each time step.
oldInput = 0;
Estimate the parameters and output using step and input-output data, maintaining the current
regressor pair in H. Invoke the step function implicitly by calling the obj system object with input
arguments.
for i = 1:numel(input)
    H = [input(i) oldInput];
    [theta, EstimatedOutput] = obj(output(i),H);
    estimatedOut(i)= EstimatedOutput;
    theta_est(i,:) = theta;
    oldInput = input(i);
end
numSample = 1:numel(input);
plot(numSample,output,'b',numSample,estimatedOut,'r--');
legend('Measured Output','Estimated Output');
                                                                                               1-1359
1   Functions
          plot(numSample,theta_est(:,1),numSample,theta_est(:,2))
          title('Parameter Estimates for Recursive Least Squares Estimation')
          legend("theta1","theta2")
1-1360
                                                                                                 step
theta_final = theta
theta_final = 2×1
   -1.5322
   -0.0235
Input Arguments
obj — System object for online parameter estimation
recursiveAR object | recursiveARMA object | recursiveARX object | recursiveARMAX object |
recursiveOE object | recursiveBJ object | recursiveLS object
System object for online parameter estimation, created using one of the following commands:
• recursiveAR
• recursiveARMA
• recursiveARX
• recursiveARMAX
• recursiveOE
                                                                                              1-1361
1   Functions
          • recursiveBJ
          • recursiveLS
          The step command updates parameters of the model using the recursive estimation algorithm
          specified in obj and the incoming input-output data.
          y — Output data
          real scalar
          Input data acquired in real time, specified as a scalar or vector of real values depending on the type
          of System object.
          Output Arguments
          EstimatedParameters — Estimated model parameters
          vector of real values for each parameter
          Estimated model parameters, returned as vectors of real values. The number of estimated
          parameters, and so the step syntax, depend on the type of System object:
1-1362
                                                                                                     step
Estimated output, returned as a real scalar. The output is estimated using input-output estimation
data, current parameter values, and recursive estimation algorithm specified in obj.
Tips
• Starting in R2016b, instead of using the step command to update model parameter estimates,
  you can call the System object with input arguments, as if it were a function. For example,
  [A,EstimatedOutput] = step(obj,y) and [A,EstimatedOutput] = obj(y) perform
  equivalent operations.
See Also
clone | isLocked | recursiveAR | recursiveARMA | recursiveARMAX | recursiveARX |
recursiveBJ | recursiveLS | recursiveOE | release | reset
Topics
“Perform Online Parameter Estimation at the Command Line”
“Validate Online Parameter Estimation at the Command Line”
“Online ARX Parameter Estimation for Tracking Time-Varying System Dynamics”
“Line Fitting with Online Recursive Least Squares Estimation”
“What Is Online Estimation?”
Introduced in R2015b
                                                                                              1-1363
1   Functions
          stepDataOptions
          Options set for step
          Syntax
          opt = stepDataOptions
          opt = stepDataOptions(Name,Value)
          Description
          opt = stepDataOptions creates the default options for step.
          opt = stepDataOptions(Name,Value) creates an options set with the options specified by one or
          more Name,Value pair arguments.
          Input Arguments
          Name-Value Pair Arguments
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
InputOffset
Input signal level for all time t < 0, as shown in the next figure.
Default: 0
StepAmplitude
Change of input signal level which occurs at time t = 0, as shown in the previous figure.
Default: 1
1-1364
                                                                                  stepDataOptions
Output Arguments
opt
Examples
Specify Input Offset and Step Amplitude Level for Step Response
sys = tf(1,[1,1]);
Create an option set for step to specify input offset and step amplitude level.
opt = stepDataOptions('InputOffset',-1,'StepAmplitude',2);
[y,t] = step(sys,opt);
See Also
step
Introduced in R2012a
                                                                                         1-1365
1   Functions
          stepinfo
          Rise time, settling time, and other step-response characteristics
          Syntax
          S = stepinfo(sys)
          S = stepinfo(y,t)
          S = stepinfo(y,t,yfinal)
          Description
          S = stepinfo(sys)computes the step-response characteristics for a dynamic system model sys.
          The function returns the characteristics in a structure containing the fields:
          • RiseTime — Time it takes for the response to rise from 10% to 90% of the steady-state response.
          • SettlingTime — Time it takes for the error |y(t) - yfinal| between the response y(t) and the steady-
            state response yfinal to fall to within 2% of yfinal.
          • SettlingMin — Minimum value of y(t) once the response has risen.
          • SettlingMax — Maximum value of y(t) once the response has risen.
          • Overshoot — Percentage overshoot, relative to yfinal).
          • Undershoot — Percentage undershoot.
          • Peak — Peak absolute value of y(t)
          • PeakTime — Time at which the peak value occurs.
The following figure illustrates some of these quantities on a typical second-order response.
1-1366
                                                                                                stepinfo
For SISO responses, t and y are vectors with the same length NS. For systems with NU inputs and
NY outputs, you can specify y as an NS-by-NY-by-NU array (see step) and yfinal as an NY-by-NU
array. stepinfo then returns a NY-by-NU structure array S of performance metrics for each I/O pair.
                                                                                               1-1367
1   Functions
          S = stepinfo( ___ ,'RiseTimeLimits',RT) lets you specify the lower and upper thresholds
          used in the definition of rise time. By default, the rise time is defined as the time the response takes
          to rise from 10 to 90% of the steady-state value (RT = [0.1 0.9]). The upper threshold RT(2) is
          also used to calculate SettlingMin and SettlingMax. These values are the minimum and
          maximum values of the response occurring after the response has reached the upper threshold. You
          can use this syntax with any of the previous input-argument combinations.
Examples
          Compute step-response characteristics such as rise time, settling time, and overshoot for a dynamic
          system model. For this example, use the continuous-time transfer function:
                                  s2 + 5s + 5
                sys =                                    .
                        s4 + 1 . 65s3 + 5s2 + 6 . 5s + 2
          The plot shows that the response rises in a few seconds, and then rings down to a steady-state value
          of about 2.5. Compute the characteristics of this response using stepinfo.
1-1368
                                                                                                   stepinfo
S = stepinfo(sys)
By default, the settling time is the time it takes for y(t) − yf inal to fall below 2% of its peak value,
where y(t)is the system response at time t and yf inal is the steady-state response. The result
S.SettlingTime shows that for sys, this condition occurs after about 28 seconds. The default
definition of rise time is the time it takes for the response to go from 10% of its steady-state value to
90% of that value. S.RiseTime shows that for sys, this rise occurs in less than 4 seconds. The
maximum overshoot is returned in S.Overshoot. For this system, the peak value S.Peak, which
occurs at the time S.PeakTime, overshoots the steady-state value by about 7.5% of the steady-state
value.
For a MIMO system, stepinfo returns a structure array in which each entry contains the response
characteristics of the corresponding I/O channel of the system. For this example, use a two-output,
two-input discrete-time system. Compute the step-response characteristics.
A =   [0.68 -0.34; 0.34 0.68];
B =   [0.18 -0.05; 0.04 0.11];
C =   [0 -1.53; -1.12 -1.10];
D =   [0 0; 0.06 -0.37];
sys   = ss(A,B,C,D,0.2);
S = stepinfo(sys)
Access the response characteristics for a particular I/0 channel by indexing into S. For instance,
examine the response characteristics for the response from the first input to the second output of
sys, corresponding to S(2,1).
S(2,1)
                                                                                                  1-1369
1   Functions
                SettlingTime:      2.8000
                 SettlingMin:      -0.6724
                 SettlingMax:      -0.5188
                   Overshoot:      24.6476
                  Undershoot:      11.1224
                        Peak:      0.6724
                    PeakTime:      1
          To access a particular value, use dot notation. For instance, extract the rise time of the (2,1) channel.
          rt21 = S(2,1).RiseTime
rt21 = 0.4000
          By default, stepinfo defines settling time as the time it takes for the error y t − yfinal between
          the response y t and the steady-state response yfinal to come within 2% of yfinal. Also, stepinfo
          defines the rise time as the time it takes for the response to rise from 10% of yfinal to 90% of yfinal.
          You can change these definitions using SettlingTimeThreshold and RiseTimeThreshold. For
          this example, use the system given by:
                              s2 + 5s + 5
                sys =                                .
                        s4 + 1 . 65s3 + 6 . 5s + 2
          Compute the time it takes for the error in the response of sys to to reach 0.5% of the steady-state
          response. To do so, set SettlingTimeThreshold to 0.5%, or 0.005.
          S1 = stepinfo(sys,'SettlingTimeThreshold',0.005);
          st1 = S1.SettlingTime
st1 = 46.1325
          Compute the time it takes the response of sys to rise from 5% to 95% of the steady-state value. To
          do so, set RiseTimeThreshold to a vector containing those bounds.
          S2 = stepinfo(sys,'RiseTimeThreshold',[0.05 0.95]);
          rt2 = S2.RiseTime
rt2 = 4.1690
          You can define both settling time and rise time in the same computation.
          S3 = stepinfo(sys,'SettlingTimeThreshold',0.005,'RiseTimeThreshold',[0.05 0.95])
1-1370
                                                                                              stepinfo
        Overshoot:   7.4915
       Undershoot:   0
             Peak:   2.6873
         PeakTime:   8.0530
You can extract step-response characteristics from step-response data even if you do not have a
model of your system. For instance, suppose you have measured the response of your system to a step
input, and saved the resulting response data in a vector y of response values at the times stored in
another vector, t. Load the response data and examine it.
load StepInfoData t y
plot(t,y)
Compute step-response characteristics from this response data using stepinfo. If you do not specify
the steady-state response value yfinal, then stepinfo assumes that the last value in the response
vector y is the steady-state response.Because there is some noise in the data, the last value in y is
likely not the true steady-state response value. When you know what the steady-state value should be,
you can provide it to stepinfo. For this example, suppose that the steady-state response is 2.4.
S1 = stepinfo(y,t,2.4)
                                                                                             1-1371
1   Functions
          Because of the noise in the data, the default definition of the settling time is too stringent, resulting in
          an arbitrary value of almost 20 seconds. To allow for the noise, increase the settling-time threshold
          from the default 2% to 5%.
S2 = stepinfo(y,t,2.4,'SettlingTimeThreshold',0.05)
          Input Arguments
          sys — Dynamic system
          dynamic system model
          Dynamic system, specified as a SISO or MIMO dynamic system model. Dynamic systems that you can
          use include:
          y — Step-response data
          vector | array
          • For SISO response data, a vector of length Ns, where Ns is the number of samples in the response
            data.
          • For MIMO response data, an Ns-by-Ny-by-Nu array, where Ny is the number of system outputs, and
            Nu is the number of system inputs.
1-1372
                                                                                                       stepinfo
t — Time vector
vector
Time vector corresponding to the response data in y, specified as a vector of length Ns.
If you do not provide yfinal, then stepinfo uses the last value in the corresponding channel of y
as the steady-state response value.
Threshold for defining settling time, specified as a scalar value between 0 and 1. By default,
stepinfo defines settling time as the time it takes for the error |y(t) - yfinal| between the response
y(t) and the steady-state response yfinal to fall to within 2% of yfinal. To change this definition, set ST to
a different value. For instance, to set a threshold of 5%, set ST to 0.05.
Threshold for defining rise time, specified as a 2-element row vector of nondescending values
between 0 and 1. By default, stepinfo defines rise time as the time it takes for the response to rise
from 10% to 90% of the steady-state value yfinal. To change this definition, set RT to a different value.
For instance, to define the rise time as the time it takes for the response to rise from 5% to 95% of
the steady-state value, set RT to [0.05 0.95].
Output Arguments
S — Step-response characteristics
structure
• RiseTime — Time it takes for the response to rise from 10% to 90% of the steady-state response.
• SettlingTime — Time it takes for the error |y(t) - yfinal| between the response y(t) and the steady-
  state response yfinal to fall to within 2% of yfinal.
• SettlingMin — Minimum value of y(t) once the response has risen.
• SettlingMax — Maximum value of y(t) once the response has risen.
• Overshoot — Percentage overshoot, relative to yfinal).
• Undershoot — Percentage undershoot.
• Peak — Peak absolute value of y(t)
• PeakTime — Time at which the peak value occurs.
                                                                                                      1-1373
1   Functions
          For MIMO models or responses data, S is a structure array in which each entry contains the step-
          response characteristics of the corresponding I/O channel. For instance, if you provide a 3-input, 3-
          output model or array of response data, then S(2,3) contains the characteristics of the response
          from the third input to the second output. For an example, see “Step-Response Characteristics of
          MIMO System” (Control System Toolbox).
          If sys is unstable, then all step-response characteristics are NaN, except for Peak and PeakTime,
          which are Inf.
          See Also
          lsiminfo | step
Introduced in R2006a
1-1374
                                                                                            stepplot
stepplot
Plot step response and return plot handle
Syntax
h = stepplot(sys)
stepplot(sys,Tfinal)
stepplot(sys,t)
stepplot(sys1,sys2,...,sysN)
stepplot(sys1,sys2,...,sysN,Tfinal)
stepplot(sys1,sys2,...,sysN,t)
stepplot(AX,...)
stepplot(..., plotoptions)
stepplot(..., dataoptions)
Description
h = stepplot(sys) plots the step response of the dynamic system model sys. It also returns the
plot handle h. You can use this handle to customize the plot with the getoptions and setoptions
commands. Type
help timeoptions
For multiinput models, independent step commands are applied to each input channel. The time
range and number of points are chosen automatically.
stepplot(sys,Tfinal) simulates the step response from t = 0 to the final time t = Tfinal.
Express Tfinal in the system time units, specified in the TimeUnit property of sys. For discrete-
time systems with unspecified sample time (Ts = -1), stepplot interprets Tfinal as the number
of sampling intervals to simulate.
stepplot(sys,t) uses the user-supplied time vector t for simulation. Express t in the system time
units, specified in the TimeUnit property of sys. For discrete-time models, t should be of the form
Ti:Ts:Tf, where Ts is the sample time. For continuous-time models, t should be of the form
Ti:dt:Tf, where dt becomes the sample time of a discrete approximation to the continuous system
(see step). The stepplot command always applies the step input at t=0, regardless of Ti.
To plot the step responses of multiple models sys1,sys2,... on a single plot, use:
stepplot(sys1,sys2,...,sysN)
stepplot(sys1,sys2,...,sysN,Tfinal)
stepplot(sys1,sys2,...,sysN,t)
You can also specify a color, line style, and marker for each system, as in
stepplot(sys1,'r',sys2,'y--',sys3,'gx')
                                                                                            1-1375
1   Functions
          stepplot(..., plotoptions) customizes the plot appearance using the options set,
          plotoptions. Use timeoptions to create the options set.
          stepplot(..., dataoptions) specifies options such as the step amplitude and input offset using
          the options set, dataoptions. Use stepDataOptions to create the options set.
Examples
          sys1 = rss(3);
          sys2 = rss(3);
          h = stepplot(sys1,sys2);
          Each step response settles at a different steady-state value. Use the plot handle to normalize the
          plotted response.
setoptions(h,'Normalize','on')
1-1376
                                                                                                stepplot
Now, the responses settle at the same value expressed in arbitrary units.
Compare the step response of a parametric identified model to a nonparametric (empirical) model,
and view their 3-σ confidence regions. (Identified models require System Identification Toolbox™
software.)
load iddata1 z1
sys1 = ssest(z1,4);
sys2 = impulseest(z1);
Plot the step responses of both identified models. Use the plot handle to display the 3-σ confidence
regions.
t = -1:0.1:5;
h = stepplot(sys1,sys2,t);
showConfidence(h,3)
legend('parametric','nonparametric')
                                                                                               1-1377
1   Functions
          load(fullfile(matlabroot,'toolbox','ident','iddemos','data','twotankdata'));
          z = iddata(y,u,0.2,'Name','Two tank system');
          Estimate a Hammerstein-Wiener Model of order [1 5 3] using the estimation data. Specify the input
          nonlinearity as piecewise linear and output nonlinearity as one-dimensional polynomial.
Create an option set to specify input offset and step amplitude level.
opt = stepDataOptions('InputOffset',2,'StepAmplitude',0.5);
Plot the step response until 60 seconds using the specified options.
stepplot(sys,60,opt);
1-1378
                                                                                              stepplot
Tips
You can change the properties of your plot, for example the units. For information on the ways to
change properties of your plots, see “Ways to Customize Plots” (Control System Toolbox).
See Also
getoptions | setoptions | showConfidence | step
Introduced in R2012a
                                                                                              1-1379
1   Functions
          strseq
          Create sequence of indexed character vectors
          Syntax
          txtarray = strseq(TXT,INDICES)
          Description
          txtarray = strseq(TXT,INDICES) creates a sequence of indexed character vectors in the cell
          array txtarray by appending the integer values INDICES to the character vector TXT.
          Note You can use strvec to aid in system interconnection. For an example, see the sumblk
          reference page.
Examples
          See Also
          connect | strcat
Introduced in R2012a
1-1380
                                                                                                   struc
struc
Generate model-order combinations for single-output ARX model estimation
Syntax
nn = struc(na,nb,nk)
nn = struc(na,nb_1,...,nb_nu,nk_1,...,nk_nu)
Description
nn = struc(na,nb,nk) generates model-order combinations for single-input, single-output ARX
model estimation. na and nb are row vectors that specify ranges of model orders. nk is a row vector
that specifies a range of model delays. nn is a matrix that contains all combinations of the orders and
delays.
Examples
load iddata1;
ze = z1(1:150);
zv = z1(151:300);
Generate model-order combinations for estimation, specifying ranges for model orders and delays.
NN = struc(1:3,1:2,2:4);
Estimate ARX models using the instrumental variable method, and compute the loss function for each
model order combination.
V = ivstruc(ze,zv,NN);
Select the model order with the best fit to the validation data.
order = selstruc(V,0);
M = iv4(ze,order);
                                                                                                1-1381
1   Functions
          load   co2data;
          Ts =   0.5; % Sample time is 0.5 min
          ze =   iddata(Output_exp1,Input_exp1,Ts);
          zv =   iddata(Output_exp2,Input_exp2,Ts);
          • na = 2:4
          • nb = 2:5 for the first input, and 1 or 4 for the second input.
          • nk = 1:4 for the first input, and 0 for the second input.
NN = struc(2:4,2:5,[1 4],1:4,0);
V = arxstruc(ze,zv,NN);
Select the model order with the best fit to the validation data.
order = selstruc(V,0);
M = arx(ze,order);
          Tips
          • Use with arxstruc or ivstruc to compute loss functions for ARX models, one for each model
            order combination returned by struc.
          See Also
          arxstruc | ivstruc | selstruc
          Topics
          “Estimating Model Orders Using an ARX Model Structure”
          “Preliminary Step – Estimating Model Orders and Input Delays”
1-1382
                                                                                 System Identification
System Identification
Identify models of dynamic systems from measured data
Description
The System Identification app enables you to identify models of dynamic systems from measured
input-output data. You can estimate both linear and nonlinear models and compare responses of
different models.
For more information, in the System Identification app, select Help > System Identification App
Help.
Examples
•    “Working with System Identification App”
•    “Identify Linear Models Using System Identification App”
•    “Identify Nonlinear Black-Box Models Using System Identification App”
Programmatic Use
systemIdentification opens the System Identification app. If the app is already open, the
command brings the app into focus.
systemIdentification(sessionFile) opens the app and loads a previously saved session file,
sessionFile, on the MATLAB path. A session includes data sets and models in the app at the time
of saving. If the app is already open, the command merges the contents of the session file with those
already present in the app.
                                                                                              1-1383
1   Functions
          For example, systemIdentification('mySession') opens the app and loads the previously
          saved app session mySession.sid.
          To save a session, in the System Identification app, select File > Save session. The session is
          saved to a file with a .sid extension.
          See Also
          Functions
          arx | iddata | midprefs | nlarx | nlhw | polyest | procest | ssest | tfest
          Topics
          “Working with System Identification App”
          “Identify Linear Models Using System Identification App”
          “Identify Nonlinear Black-Box Models Using System Identification App”
1-1384
                                                                                                    tfdata
tfdata
Access transfer function data
Syntax
[num,den] = tfdata(sys)
[num,den,Ts] = tfdata(sys)
[num,den,Ts,sdnum,sdden]=tfdata(sys)
[num,den,Ts,...]=tfdata(sys,J1,...,Jn)
Description
[num,den] = tfdata(sys) returns the numerator(s) and denominator(s) of the transfer function
for the TF, SS or ZPK model (or LTI array of TF, SS or ZPK models) sys. For single LTI models, the
outputs num and den of tfdata are cell arrays with the following characteristics:
• num and den have as many rows as outputs and as many columns as inputs.
• The (i,j) entries num{i,j} and den{i,j} are row vectors specifying the numerator and
  denominator coefficients of the transfer function from input j to output i. These coefficients are
  ordered in descending powers of s or z.
For arrays sys of LTI models, num and den are multidimensional cell arrays with the same sizes as
sys.
If sys is a state-space or zero-pole-gain model, it is first converted to transfer function form using tf.
For more information on the format of transfer function model data, see the tf reference page.
[num,den] = tfdata(sys,'v')
forces tfdata to return the numerator and denominator directly as row vectors rather than as cell
arrays (see example below).
You can access the remaining LTI properties of sys with get or by direct referencing, for example,
sys.Ts
sys.variable
                                                                                                  1-1385
1   Functions
          Examples
          Example 1
          den =
                1      2      5
          the command
          [num,den] = tfdata(H)
          now returns two cell arrays with the numerator/denominator data for each SISO entry. Use
          celldisp to visualize this data. Type
          celldisp(num)
          num{2} =
               0       1
          den{2} =
               1       1
Example 2
          Extract the numerator, denominator and their standard deviations for a 2-input, 1 output identified
          transfer function.
          load iddata7
1-1386
                                                             tfdata
See Also
get | ssdata | tf | zpkdata
                                                            1-1387
1   Functions
          tfest
          Transfer function estimation
          Syntax
          sys    =   tfest(data,np)
          sys    =   tfest(data,np,nz)
          sys    =   tfest(data,np,nz,iodelay)
          sys    =   tfest( ___ ,Name,Value)
          sys    =   tfest(data,init_sys)
          sys    =   tfest( ___ ,opt)
          Description
          sys = tfest(data,np) estimates a continuous-time transfer function, sys, using time- or
          frequency-domain data, data, and contains np poles. The number of zeros in the sys is
          max(np-1,0).
          sys = tfest(data,np,nz,iodelay) estimates a transfer function with transport delay for input/
          output pairs iodelay.
          sys = tfest( ___ ,Name,Value) uses additional options specified by one or more Name,Value
          pair arguments. All input arguments described for previous syntaxes also apply here.
          sys = tfest(data,init_sys) uses the linear system init_sys to configure the initial
          parameterization of sys.
          sys = tfest( ___ ,opt) specifies the estimation behavior using the option set opt. All input
          arguments described for previous syntaxes also apply here.
          Input Arguments
          data
Estimation data.
For time domain estimation, data is an iddata object containing the input and output signal values.
          Time-series models, which are models that contain no measured inputs, cannot be estimated using
          tfest. Use ar, arx or armax for time-series models instead.
1-1388
                                                                                                  tfest
For multi-experiment data, the sample times and intersample behavior of all the experiments must
match.
np
np is a nonnegative number.
• To use the same number of poles for all the input/output pairs, specify np as a scalar.
• To use different number of poles for the input/output pairs, specify np as an ny-by-nu matrix. ny is
  the number of outputs, and nu is the number of inputs.
nz
nz is a nonnegative number.
• To use the same number of zeros for all the input/output pairs, specify nz as a scalar.
• To use a different number of zeros for the input/output pairs, specify nz as an Ny-by-Nu matrix.
  Ny is the number of outputs, and Nu is the number of inputs.
For a continuous-time model, estimated using discrete-time data, set nz <= np.
For discrete-time model estimation, specify nz as the number of zeros of the numerator polynomial of
the transfer function. For example, tfest(data,2,1,'Ts',data.Ts) estimates a transfer function
of the form b1z−1 /(1 + a1z−1 + b2z−2), while tfest(data,2,2,'Ts',data.Ts) estimates
(b1z−1 + b2z−2)/(1 + a1z−1 + b2z−2). Here z-1 is the Z-transform lag variable. For more information
about discrete-time transfer functions, see “Discrete-Time Representation”. For an example, see
“Estimate Discrete-Time Transfer Function” on page 1-1396.
iodelay
Transport delay.
For continuous-time systems, specify transport delays in the time unit stored in the TimeUnit
property of data. For discrete-time systems, specify transport delays as integers denoting delay of a
multiple of the sample time Ts.
For a MIMO system with Ny outputs and Nu inputs, set iodelay to an Ny-by-Nu array. Each entry of
this array is a numerical value that represents the transport delay for the corresponding input/output
pair. You can also set iodelay to a scalar value to apply the same delay to all input/output pairs.
                                                                                               1-1389
1   Functions
          iodelay must contain either nonnegative numbers or NaNs. Use NaN in the iodelay matrix to
          denote unknown transport delays.
opt
Estimation options.
opt is an options set, created using tfestOptions, that specifies estimation options including:
          • Estimation objective
          • Handling of initial conditions
          • Numerical search method to be used in estimation
init_sys
          You obtain init_sys by either performing an estimation using measured data or by direct
          construction.
          If init_sys is an idtf model, tfest uses the parameters and constraints defined in init_sys as
          the initial guess for estimating sys. Use the Structure property of init_sys to configure initial
          guesses and constraints for the numerator, denominator, and transport lag. For example:
          If init_sys is not an idtf model, the software first converts init_sys to a transfer function.
          tfest uses the parameters of the resulting model as the initial guess for estimation.
          If opt is not specified, and init_sys was obtained by estimation, then the estimation options from
          init_sys.Report.OptionsUsed are used.
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Ts
Sample time.
1-1390
                                                                                                     tfest
• 0 — Continuous-time model.
• data.Ts — Discrete-time model. In this case, np and nz refer to the number of roots of z^-1 for
  the numerator and denominator polynomials.
Default: 0
InputDelay
Input delay for each input channel, specified as a scalar value or numeric vector. For continuous-time
systems, specify input delays in the time unit stored in the TimeUnit property. For discrete-time
systems, specify input delays in integer multiples of the sample time Ts. For example, InputDelay =
3 means a delay of three sample times.
For a system with Nu inputs, set InputDelay to an Nu-by-1 vector. Each entry of this vector is a
numerical value that represents the input delay for the corresponding input channel.
You can also set InputDelay to a scalar value to apply the same delay to all channels.
Default: 0
Feedthrough
Feedthrough for discrete-time transfer function, specified as an Ny-by-Nu logical matrix. Ny is the
number of outputs, and Nu is the number of inputs. To use the same feedthrough for all input-output
channels, specify Feedthrough as a scalar.
When the model has direct feedthrough, b0 is 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, b0 is fixed
to zero. For an example, see “Estimate Discrete-Time Transfer Function With Feedthrough” on page
1-1397.
Output Arguments
sys
Identified transfer function, returned as an idtf model. This model is created using the specified
model orders, delays and estimation options.
Information about the estimation results and options used is stored in the Report property of the
model. Report has the following fields:
                                                                                              1-1391
1   Functions
           Report      Description
           Field
           Status      Summary of the model status, which indicates whether the model was created by
                       construction or obtained by estimation.
           Method      Estimation command used.
           Initializ Algorithm used to initialize the numerator and denominator for estimation of
           eMethod   continuous-time transfer functions using time-domain data, returned as one of the
                     following values:
                       This field is especially useful to view the algorithm used when the InitializeMethod
                       option in the estimation option set is 'all'.
           N4Weight    Weighting matrices used in the singular-value decomposition step when
                       InitializeMethod is 'n4sid', returned as one of the following values:
                       This field is especially useful to view the weighting matrices used when the N4Weight
                       option in the estimation option set is 'auto'.
           N4Horizon Forward and backward prediction horizons used when InitializeMethod is
                     'n4sid', returned as a row vector with three elements — [r sy su], where r is the
                     maximum forward prediction horizon. sy is the number of past outputs, and su is the
                     number of past inputs that are used for the predictions.
           InitialCo Handling of initial conditions during model estimation, returned as one of the following
           ndition   values:
                       This field is especially useful to view how the initial conditions were handled when the
                       InitialCondition option in the estimation option set is 'auto'.
1-1392
                                                                                                   tfest
Report       Description
Field
Fit          Quantitative assessment of the estimation, returned as a structure. See “Loss Function
             and Model Quality Metrics” for more information on these quality metrics. The
             structure has the following fields:
             Field         Description
             FitPerce Normalized root mean squared error (NRMSE) measure of how well the
             nt       response of the model fits the estimation data, expressed as the
                      percentage fit = 100(1-NRMSE).
             LossFcn       Value of the loss function when the estimation completes.
             MSE           Mean squared error (MSE) measure of how well the response of the
                           model fits the estimation data.
             FPE           Final prediction error for the model.
             AIC           Raw Akaike Information Criteria (AIC) measure of model quality.
             AICc          Small sample-size corrected AIC.
             nAIC          Normalized AIC.
             BIC           Bayesian Information Criteria (BIC).
Parameter Estimated values of model parameters.
s
OptionsUs Option set used for estimation. If no custom options were configured, this is a set of
ed        default options. See polyestOptions for more information.
RandState State of the random number stream at the start of estimation. Empty, [], if
          randomization was not used during estimation. For more information, see rng in the
          MATLAB documentation.
                                                                                             1-1393
1   Functions
           Report      Description
           Field
           DataUsed    Attributes of the data used for estimation, returned as a structure with the following
                       fields:
                        Field        Description
                        Name         Name of the data set.
                        Type         Data type.
                        Length       Number of data samples.
                        Ts           Sample time.
                        InterSam Input intersample behavior, returned as one of the following values:
                        ple
                                 • 'zoh' — Zero-order hold maintains a piecewise-constant input signal
                                    between samples.
                                     • 'foh' — First-order hold maintains a piecewise-linear input signal
                                       between samples.
                                     • 'bl' — Band-limited behavior specifies that the continuous-time input
                                       signal has zero power above the Nyquist frequency.
                        InputOff Offset removed from time-domain input data during estimation. For
                        set      nonlinear models, it is [].
                        OutputOf Offset removed from time-domain output data during estimation. For
                        fset     nonlinear models, it is [].
           Terminati Termination conditions for the iterative search used for prediction error minimization.
           on        Structure with the following fields:
                        Field        Description
                        WhyStop      Reason for terminating the numerical search.
                        Iteratio Number of search iterations performed by the estimation algorithm.
                        ns
                        FirstOrd ∞-norm of the gradient search vector when the search algorithm
                        erOptima terminates.
                        lity
                        FcnCount Number of times the objective function was called.
                        UpdateNo Norm of the gradient search vector in the last iteration. Omitted when the
                        rm       search method is 'lsqnonlin' or 'fmincon'.
                        LastImpr Criterion improvement in the last iteration, expressed as a percentage.
                        ovement Omitted when the search method is 'lsqnonlin' or 'fmincon'.
                        Algorith Algorithm used by 'lsqnonlin' or 'fmincon' search method. Omitted
                        m        when other search methods are used.
                       For estimation methods that do not require numerical search optimization, the
                       Termination field is omitted.
1-1394
                                                                                                    tfest
Examples
Load time-domain system response data and use it to estimate a transfer function for the system.
To see the numerator and denominator coefficients of the resulting estimated model sys, enter:
sys.Numerator
ans = 1×2
2.4554 176.9856
sys.Denominator
ans = 1×3
To view the uncertainty in the estimates of the numerator and denominator and other information,
use tfdata.
Load time-domain system response data and use it to estimate a transfer function for the system.
np and nz specify the number of poles and zeros in the estimated transfer function, respectively.
                                                                                              1-1395
1   Functions
          Load time-domain system response data and use it to estimate a transfer function for the system.
          Specify a known transport delay for the transfer function.
np and nz specify the number of poles and zeros in the estimated transfer function, respectively.
iodelay specifies the transport delay for the estimated transfer function as 0.2 seconds.
          sys is an idtf model containing the estimated transfer function, with IODelay property set to 0.2
          seconds.
          Load time-domain system response data and use it to estimate a transfer function for the system.
          Specify an unknown transport delay for the transfer function.
np and nz specify the number of poles and zeros in the estimated transfer function, respectively.
          iodelay specifies the transport delay for the estimated transfer function. iodelay = NaN denotes
          the transport delay as an unknown parameter to be estimated.
          sys is an idtf model containing the estimated transfer function, whose IODelay property is
          estimated using data.
          Estimate a discrete-time transfer function with two poles and one zero. Specify the sample time as
          0.1 sec and the transport delay as 2 sec.
1-1396
                                                                                                  tfest
np = 2;
nz = 1;
iodelay = 2;
Ts = 0.1;
sysd = tfest(z2,np,nz,iodelay,'Ts',Ts)
sysd =
Parameterization:
   Number of poles: 2   Number of zeros: 1
   Number of free coefficients: 3
   Use "tfdata", "getpvec", "getcov" for parameters and their uncertainties.
Status:
Estimated using TFEST on time domain data "z2".
Fit to estimation data: 80.26%
FPE: 2.095, MSE: 2.063
By default, the model has no feedthrough, and the numerator polynomial of the estimated transfer
function has a zero leading coefficient b0. To estimate b0, specify the Feedthrough property during
estimation.
load iddata5 z5
First estimate a discrete-time transfer function model with two poles, one zero, and no feedthrough.
np = 2;
nz = 1;
model = tfest(z5,np,nz,'Ts',z5.Ts);
                 b1z−1 + b2z−2
    H(z−1) =
               1 + a1z−1 + a2z−2
By default, the model has no feedthrough, and the numerator polynomial of the estimated transfer
function has a zero leading coefficient b0. To estimate b0, specify the Feedthrough property during
estimation.
model = tfest(z5,np,nz,'Ts',z5.Ts,'Feedthrough',true);
The numerator polynomial of the estimated transfer function now has a nonzero leading coefficient:
                                                                                              1-1397
1   Functions
                           b0 + b1z−1 + b2z−2
                H(z−1) =
                            1 + a1z−1 + a2z−2
Compare two discrete-time models with and without feedthrough and transport delay.
          If there is a delay from the measured input to output, it can be attributed to a lack of feedthrough or
          to a true transport delay. For discrete-time models, absence of feedthrough corresponds to a lag of 1
          sample between the input and output. Estimating a model with Feedthrough = false and
          IODelay = 0 thus produces a discrete-time system that is equivalent to a system with
          Feedthrough = true and IODelay = 1. Both systems show the same time- and frequency-domain
          responses, for example, on step and Bode plots. However, you get different results if you reduce these
          models using balred or convert them to their continuous-time representation. Therefore, you should
          check if the observed delay should be attributed to transport delay or to a lack of feedthrough.
          load iddata1 z1
          np = 2;
          nz = 2;
          model1 = tfest(z1,np,nz,'Ts',z1.Ts);
          model1 has a transport delay of 1 sample and its IODelay property is 0. Its numerator polynomial
          begins with z−1.
Estimate another discrete-time model with feedthrough and 1 sample input-output delay.
model2 = tfest(z1,np,nz-1,1,'Ts',z1.Ts,'Feedthrough',true);
bode(model1,model2);
1-1398
                                                                                             tfest
The equations for model1 and model2 are equivalent, but the transport delay of model2 has been
absorbed into the numerator of model1.
Convert the models to continuous time, and compare their Bode responses.
bode(d2c(model1),d2c(model2));
                                                                                         1-1399
1   Functions
          As the plot shows, the Bode responses of the two models do not match when you convert them to
          continuous time.
          Estimate MISO Discrete-Time Transfer Function with Feedthrough and Delay Specifications
          for Individual Channels
          Estimate a 2-input, 1-output discrete-time transfer function with a delay of 2 samples on first input
          and zero seconds on the second input. Both inputs have no feedthrough.
          Estimate a 2-input, 1-output transfer function with 2 poles and 1 zero for each input-to-output
          transfer function.
          Lag = [2;0];
          Ft = [false,false];
          model = tfest(ze,2,1,'Ts',z7.Ts,'Feedthrough',Ft,'InputDelay',Lag);
          Choice of Feedthrough dictates whether the leading numerator coefficient is zero (no feedthrough)
          or not (nonzero feedthrough). Delays are expressed separately using InputDelay or IODelay
          property. This example uses InputDelay to express the delays.
1-1400
                                                                                                 tfest
Validate the estimated model. Exclude the data outliers for validation.
I = 1:201;
I(114:118) = [];
opt = compareOptions('Samples',I);
compare(zv,model,opt)
Identify a 15th order transfer function model by using regularized impulse response estimation
Load data.
opt = impulseestOptions('RegularizationKernel','DC');
m0 = impulseest(m0simdata,70,opt);
Convert model into a transfer function model after reducing order to 15.
m = idtf(balred(idss(m0),15));
                                                                                             1-1401
1   Functions
compare(m0simdata,m);
          opt specifies that the initialization method as 'n4sid', and the search method as 'lsqnonlin'. It
          also specifies that the loss-function values for each iteration be shown.
          Load time-domain system response data and use it to estimate a transfer function for the system.
          Specify the estimation options using opt.
          load iddata2 z2;
          np = 2;
          nz = 1;
          iodelay = 0.2;
          sysc = tfest(z2,np,nz,iodelay,opt);
np and nz specify the number of poles and zeros in the estimated transfer function, respectively.
iodelay specifies the transport delay for the estimated transfer function as 0.2 seconds.
1-1402
                                                                                                    tfest
Load time-domain system response data, and use it to estimate a transfer function for the system.
Specify the input delay for the estimated transfer function.
np and nz specify the number of poles and zeros in the estimated transfer function, respectively.
input_delay specifies the input delay for the estimated transfer function as 0.2 seconds.
sys is an idtf model containing the estimated transfer function with an input delay of 0.2 seconds.
For example, use bode to obtain the magnitude and phase response data for the following system:
                 s + 0.2
    H(s) =
             s3 + 2s2 + s + 1
Use 100 frequency points, ranging from 0.1 rad/s to 10 rad/s, to obtain the frequency-response data.
Use frd to create a frequency-response data object.
freq = logspace(-1,1,100);
[mag,phase] = bode(tf([1 0.2],[1 2 1 1]),freq);
data = frd(mag.*exp(1j*phase*pi/180),freq);
np = 3;
nz = 1;
sys = tfest(data,np,nz);
np and nz specify the number of poles and zeros in the estimated transfer function, respectively.
                                                                                              1-1403
1   Functions
Estimate Transfer Function with Known Transport Delays for Multiple Inputs
          load co2data;
          Ts = 0.5;
          data = iddata(Output_exp1,Input_exp1,Ts);
          Specify the search method as gna. Also specify the maximum search iterations and input/output
          offsets.
          opt = tfestOptions('SearchMethod','gna');
          opt.InputOffset = [170;50];
          opt.OutputOffset = mean(data.y(1:75));
          opt.SearchOptions.MaxIterations = 50;
          opt is an estimation option set that specifies the search method as gna, with a maximum of 50
          iterations. opt also specifies the input offset and the output offset.
          Estimate a transfer function using the measured data and the estimation option set. Specify the
          transport delays from the inputs to the output.
          np = 3;
          nz = 1;
          iodelay = [2 5];
          sys = tfest(data,np,nz,iodelay,opt);
          iodelay specifies the input to output delay from the first and second inputs to the output as 2
          seconds and 5 seconds, respectively.
          Load time-domain system response data and use it to estimate a transfer function for the system.
          Specify the known and unknown transport delays.
          load co2data;
          Ts = 0.5;
          data = iddata(Output_exp1,Input_exp1,Ts);
          Specify the search method as gna. Also specify the maximum search iterations and input/output
          offsets.
          opt = tfestOptions('Display','on','SearchMethod','gna');
          opt.InputOffset = [170; 50];
          opt.OutputOffset = mean(data.y(1:75));
          opt.SearchOptions.MaxIterations = 50;
1-1404
                                                                                                   tfest
opt is an estimation option set that specifies the search method as gna, with a maximum of 50
iterations. opt also specifies the input/output offsets.
Estimate the transfer function. Specify the unknown and known transport delays.
np = 3;
nz = 1;
iodelay = [2 nan];
sys = tfest(data,np,nz,iodelay,opt);
iodelay specifies the transport delay from the first input to the output as 2 seconds. Using NaN
specifies the transport delay from the second input to the output as unknown.
Create a transfer function model with the expected numerator and denominator structure and delay
constraints.
In this example, the experiment data consists of two inputs and one output. Both transport delays are
unknown and have an identical upper bound. Additionally, the transfer functions from both inputs to
the output are identical in structure.
init_sys = idtf(NaN(1,2),[1,NaN(1,3)],'IODelay',NaN);
init_sys.Structure(1).IODelay.Free = true;
init_sys.Structure(1).IODelay.Maximum = 7;
init_sys is an idtf model describing the structure of the transfer function from one input to the
output. The transfer function consists of one zero, three poles and a transport delay. The use of NaN
indicates unknown coefficients.
init_sys = [init_sys,init_sys];
Load time-domain system response data and use it to estimate a transfer function.
load co2data;
Ts = 0.5;
data = iddata(Output_exp1,Input_exp1,Ts);
opt = tfestOptions('Display','on','SearchMethod','gna');
opt.InputOffset = [170;50];
opt.OutputOffset = mean(data.y(1:75));
opt.SearchOptions.MaxIterations = 50;
sys = tfest(data,init_sys,opt);
                                                                                               1-1405
1   Functions
          opt is an estimation option set that specifies the search method as gna, with a maximum of 50
          iterations. opt also specifies the input offset and the output offset.
          opt2 = compareOptions;
          opt2.InputOffset = opt.InputOffset;
          opt2.OutputOffset = opt.OutputOffset;
          compare(data,sys,opt2)
Estimate Transfer Function Containing Different Number of Poles for Input/Output Pairs
          Estimate a multiple-input, single-output transfer function containing different number of poles for
          input/output pairs for given data.
For example, use frd to create a frequency-response data model for the following system:
1-1406
                                                                                                   tfest
                         s+2
          e−4s
                 s3 + 2s2 + 4s + 5
    G=
                            5
          e−0 . 6s
                     s4 + 2s3 + s2 + s
Use 100 frequency points, ranging from 0.01 rad/s to 100 rad/s, to obtain the frequency-response
data.
G = tf({[1 2],[5]},{[1 2 4 5],[1 2 1 1 0]},0,'IODelay',[4 0.6]);
data = frd(G,logspace(-2,2,100));
np specifies the number of poles in the estimated transfer function. The first element of np indicates
that the transfer function from the first input to the output contains 3 poles. Similarly, the second
element of np indicates that the transfer function from the second input to the output contains 4
poles.
nz specifies the number of zeros in the estimated transfer function. The first element of nz indicates
that the transfer function from the first input to the output contains 1 zero. Similarly, the second
element of np indicates that the transfer function from the second input to the output does not
contain any zeros.
iodelay specifies the transport delay from the first input to the output as 4 seconds. The transport
delay from the second input to the output is specified as 0.6 seconds.
For example, use frd to create frequency-response data model for the following system:
               s+2
         s3 + 2s2 + 4s + 5
    G=
                 5
       s + 2s + s2 + s + 1
        4     3
Use 100 frequency points, ranging from 0.01 rad/s to 100 rad/s, to obtain the frequency-response
data.
G = idtf({[1 2], 5},{[1 2 4 5],[1 2 1 1 1]});
data = idfrd(G,logspace(-2,2,100));
                                                                                               1-1407
1   Functions
          np = [3 4];
          nz = [1 0];
          sys = tfest(data,np,nz);
          np specifies the number of poles in the estimated transfer function. The first element of np indicates
          that the transfer function from the first input to the output contains 3 poles. Similarly, the second
          element of np indicates that the transfer function from the second input to the output contains 4
          poles.
          nz specifies the number of zeros in the estimated transfer function. The first element of nz indicates
          that the transfer function from the first input to the output contains 1 zero. Similarly, the second
          element of nz indicates that the transfer function from the second input to the output does not
          contain any zeros.
pole(sys)
                -1.5260   +   0.0000i
                -0.2370   +   1.7946i
                -0.2370   -   1.7946i
                -1.4656   +   0.0000i
                -1.0000   +   0.0000i
                 0.2328   +   0.7926i
                 0.2328   -   0.7926i
Estimate Transfer Function using High Modal Density Frequency Response Data
          Load the high density frequency response measurement data. The data corresponds to an unstable
          process maintained at equilibrium using feedback control.
Package the data as an idfrd object for identification and, find the Bode magnitude response.
          G = idfrd(permute(FRF,[2 3 1]),f,0,'FrequencyUnit','Hz');
          bodemag(G)
1-1408
                                                                                              tfest
Estimate a transfer function with 32 poles and 32 zeros, and compare the Bode magnitude response.
sys = tfest(G,32,32);
bodemag(G, sys)
xlim([0.01,2e3])
legend
                                                                                           1-1409
1   Functions
          More About
          Compatibility
          Starting in R2016b, a new algorithm is used for performing transfer function estimation from
          frequency-domain data. You are likely to see faster and more accurate results with the new algorithm,
          particularly for data with dynamics over a large range of frequencies and amplitudes. However, the
          estimation results may not match results from previous releases. To perform estimation using the
          previous estimation algorithm, append '-R2016a' to the syntax.
          For example, suppose that you are estimating a transfer function model with np poles using
          frequency-domain data, data.
sys = tfest(data,np)
sys = tfest(data,np,'-R2016a')
          Algorithms
          The details of the estimation algorithms used by tfest vary depending on a variety of factors,
          including the sampling of the estimated model and the estimation data.
1-1410
                                                                                                  tfest
The estimation algorithm initializes the estimable parameters using the method specified by the
InitializeMethod estimation option. The default method is the Instrument Variable (IV) method.
The State-Variable Filters (SVF) approach and the Generalized Poisson Moment Functions (GPMF)
                                                                                                1
approach to continuous-time parameter estimation use prefiltered data [1] [2]. The constant in [1]
                                                                                                λ
and [2] corresponds to the initialization option (InitializeOptions) field FilterTimeConstant.
IV is the simplified refined IV method and is called SRIVC in [3]. This method has a prefilter that is
the denominator of the current model, initialized with SVF. This prefilter is iterated up to
MaxIterations times, until the model change is less than Tolerance. MaxIterations and
Tolerance are options that you can specify using the InitializeOptions structure. The 'n4sid'
initialization option estimates a discrete-time model, using the N4SID estimation algorithm, that it
transforms to continuous-time using d2c.
You use tfestOptions to create the option set used to estimate a transfer function.
Parameter Update
The initialized parameters are updated using a nonlinear least-squares search method, specified by
the SearchMethod estimation option. The objective of the search method is to minimize the
weighted prediction error norm.
For discrete-time data, tfest uses the same algorithm as oe to determine the numerator and
denominator polynomial coefficients. In this algorithm, the initialization is performed using arx,
followed by nonlinear least-squares search based updates to minimize a weighted prediction error
norm.
               nf                   nu                2
                                      Ni(ωk)
    minimize   ∑     W(ωk) y(ωk) − ∑         u (ω )
                                      D(ωk) i k
       D, Ni   k=1                i=1
    Here W is a frequency-dependent weight that you specify. D is the denominator of the transfer
    function model that is to be estimated, and Ni is the numerator corresponding to the ith input. y
    and u are the measured output and input data, respectively. nf and nu are the number of
    frequencies and inputs, and w is the frequency. Rearranging the terms gives:
               nf                        n                2
                     W(ωk)              u
    minimize   ∑     D(ωk)
                           D(ωk)y(ωk) − ∑ Ni(ωk)ui(ωk)
       D, Ni   k=1                     i=1
                                                                                               1-1411
1   Functions
                              nf                                      n                       2
                                      W(ωk)                   u
                minimize      ∑      Dm − 1(ωk)
                                                Dm(ωk)y(ωk) − ∑ Ni, m(ωk)ui(ωk)
                 Dm, Ni, m k = 1                             i=1
                where m is the current iteration, and Dm-1(ω) is the denominator response identified at the
                previous iteration. Now each step of the iteration is a linear least-squares problem, where the
                identified parameters capture the responses Dm(ω) and Ni,m(ω) for i = 1,2,...nu. The iteration is
                initialized by choosing D0(ω) = 1.
                • The first iteration of the algorithm identifies D1(ω). The D1(ω) and Ni,1(ω) polynomials are
                  expressed in monomial basis.
                • The second and following iterations express the polynomials Dm(ω) and Ni,m(ω) in terms of
                  orthogonal rational basis functions on the unit disk. These basis functions have the form:
                                                    2 j−1
                                   1 − λ j, m − 1        1 − (λ j, m − 1)*q(ω)
                B j, m(ω) =
                                   q − λ j, m − 1     ∏    q(ω) − λr, m − 1
                                                     r=0
                   Here λj,m-1 is the jth pole that is identified at the previous step, m-1, of the iteration. λj,m-1* is
                   the complex conjugate of λj,m-1, and q is the frequency-domain variable on the unit disk.
                • The algorithm runs for a maximum of 20 iterations. The iterations are terminated early if the
                  relative change in the value of the loss function is less than 0.001 in the last three iterations.
                If you specify bounds on transfer function coefficients, these bounds correspond to affine
                constraints on the identified parameters. If you only have equality constraints (fixed transfer
                function coefficients), the corresponding equality constrained least-squares problem is solved
                algebraically. To do so, the software computes an orthogonal basis for the null space of the
                equality constraint matrix, and then solves least-squares problem within this null space. If you
                have upper or lower bounds on transfer function coefficients, the corresponding inequality
                constrained least-squares problem is solved using interior-point methods.
          3     Perform linear refinements — The S-K iterations, even when they converge, do not always yield a
                locally optimal solution. To find a critical point of the optimization problem that may yield a
                locally optimal solution, a second set of iterations are performed. The critical points are solutions
                to a set of nonlinear equations. The algorithm searches for a critical point by successively
                constructing a linear approximation to the nonlinear equations and solving the resulting linear
                equations in the least-squares sense. The equations are:
                The first iteration is started with the best solution found for the numerators Ni and denominator
                D parameters during S-K iterations. Unlike S-K iterations, the basis functions Bj(ω) are not
1-1412
                                                                                                     tfest
    changed at each iteration, the iterations are performed with the basis functions that yielded the
    best solution in the S-K iterations. As before, the algorithm runs for a maximum of 20 iterations.
    The iterations are terminated early if the relative change in the value of the loss function is less
    than 0.001 in the last three iterations.
    If you specify bounds on transfer function coefficients, these bounds are incorporated into the
    necessary optimality conditions via generalized Lagrange multipliers. The resulting constrained
    linear least-squares problems are solved using the same methods explained in the S-K iterations
    step.
4   Return the transfer function parameters corresponding to the optimal solution — Both the S-K
    and linear refinement iteration steps do not guarantee an improvement in the loss function value.
    The algorithm tracks the best parameter value observed during these steps, and returns these
    values.
5   Invert the bilinear mapping performed in step 1.
6   Perform an iterative refinement of the transfer function parameters using the nonlinear least-
    squares search method specified in the SearchMethod estimation option. This step is
    implemented in the following situations:
    • When you specify the EnforceStability estimation option as true (stability is requested),
      and the result of step 5 of this algorithm is an unstable model. The unstable poles are
      reflected inside the stability boundary and the resulting parameters are iteratively refined.
      For information about estimation options, see tfestOptions.
    • When you add a regularization penalty to the loss function using the Regularization
      estimation option. For an example about regularization, see “Regularized Identification of
      Dynamic Systems”.
    • You estimate a continuous-time model using discrete-time data (see “Discrete-Time Transfer
      Function Estimation Using Discrete-Time Frequency-Domain Data” on page 1-1413).
    • You use frequency domain input-output data to identify a multi-input model.
If you are using the estimation algorithm from R2016a or earlier (see “Compatibility” on page 1-1410)
for estimating a continuous-time model using continuous-time frequency-domain data, then for
continuous-time data and fixed delays, the Output-Error algorithm is used for model estimation. For
continuous-time data and free delays, the state-space estimation algorithm is used. In this algorithm,
the model coefficients are initialized using the N4SID estimation method. This initialization is
followed by nonlinear least-squares search based updates to minimize a weighted prediction error
norm.
The estimation algorithm is the same as for continuous-time transfer function estimation using
continuous-time frequency-domain data on page 1-1411, except discrete-time data is used.
If you are using the estimation algorithm from R2016a or earlier (see “Compatibility” on page 1-
1410), the algorithm is the same as the algorithm for discrete-time transfer function estimation using
time-domain data on page 1-1411.
Note The software does not support estimation of a discrete-time transfer function using continuous-
time frequency-domain data.
                                                                                                 1-1413
1   Functions
          tfest command first estimates a discrete-time model from the discrete-time data. The estimated
          model is then converted to a continuous-time model using the d2c command. The frequency response
          of the resulting continuous-time model is then computed over the frequency grid of the estimation
          data. A continuous-time model of the desired (user-specified) structure is then fit to this frequency
          response. The estimation algorithm for using the frequency-response data to obtain the continuous-
          time model is the same as that for continuous-time transfer function estimation using continuous-time
          data on page 1-1411.
          If you are using the estimation algorithm from R2016a or earlier (see “Compatibility” on page 1-
          1410), the state-space estimation algorithm is used for estimating continuous-time models from
          discrete-time data. In this algorithm, the model coefficients are initialized using the N4SID estimation
          method. This initialization is followed by nonlinear least-squares search based updates to minimize a
          weighted prediction error norm.
Delay Estimation
          • When delay values are specified as NaN, they are estimated separate from the model numerator
            and denominator coefficients, using delayest. The delay values thus determined are treated as
            fixed values during the iterative update of the model using a nonlinear least-squares search
            method. Thus, the delay values are not iteratively updated.
          • For an initial model, init_sys, with:
          Estimation of delays is often a difficult problem. You should assess the presence and the value of a
          delay. To do so, use physical insight of the process being modeled and functions such as arxstruc,
          delayest, and impulseest. For an example of determining input delay, see “Model Structure
          Selection: Determining Model Order and Input Delay”.
          References
          [1] Garnier, H., M. Mensler, and A. Richard. “Continuous-time Model Identification From Sampled
                  Data: Implementation Issues and Performance Evaluation.” International Journal of Control,
                  2003, Vol. 76, Issue 13, pp 1337–1357.
          [2] Ljung, L. “Experiments With Identification of Continuous-Time Models.” Proceedings of the 15th
                  IFAC Symposium on System Identification. 2009.
          [3] Young, P. C. and A.J. Jakeman. “Refined instrumental variable methods of time-series analysis: Part
                  III, extensions.” International Journal of Control 31, 1980, pp 741–764.
          [4] Drmac, Z., S. Gugercin, and C. Beattie. “Quadrature-based vector fitting for discretized H2
                 approximation.” SIAM Journal on Scientific Computing. Vol. 37, Numer 2, 2014, pp A625–
                 A652.
          [5] Ozdemir, A. A., and S. Gumussoy. “Transfer Function Estimation in System Identification Toolbox
                 via Vector Fitting.” Proceedings of the 20th World Congress of the International Federation of
                 Automatic Control. Toulouse, France, July 2017.
1-1414
                                                                                               tfest
Extended Capabilities
Automatic Parallel Support
Accelerate code by automatically running computation in parallel using Parallel Computing Toolbox™.
Parallel computing support is available for estimation using the lsqnonlin search method (requires
Optimization Toolbox). To enable parallel computing, use tfestOptions, set SearchMethod to
'lsqnonlin', and set SearchOptions.Advanced.UseParallel to true.
For example:
opt = tfestOptions;
opt.SearchMethod = 'lsqnonlin';
opt.SearchOptions.Advanced.UseParallel = true;
See Also
ar | arx | bj | greyest | idtf | oe | polyest | procest | ssest | tfestOptions
Topics
“Estimate Transfer Function Models at the Command Line”
“Estimate Transfer Function Models with Transport Delay to Fit Given Frequency-Response Data”
“Estimate Transfer Function Models With Prior Knowledge of Model Structure and Constraints”
“Troubleshoot Frequency-Domain Identification of Transfer Function Models”
“What are Transfer Function Models?”
“Regularized Estimates of Model Parameters”
“Estimating Models Using Frequency-Domain Data”
Introduced in R2012a
                                                                                           1-1415
1   Functions
          tfestOptions
          Option set for tfest
          Syntax
          opt = tfestOptions
          opt = tfestOptions(Name,Value)
          Description
          opt = tfestOptions creates the default option set for tfest.
          opt = tfestOptions(Name,Value) creates an option set with the options specified by one or
          more Name,Value pair arguments.
          Input Arguments
          Name-Value Pair Arguments
          Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
          Value is the corresponding value. Name must appear inside quotes. You can specify several name and
          value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
          Algorithm used to initialize the values of the numerator and denominator of the output of tfest,
          applicable only for estimation of continuous-time transfer functions using time-domain data, specified
          as one of the following values:
          Option set for the initialization algorithm used to initialize the values of the numerator and
          denominator of the output of tfest, specified as a structure with the following fields:
          • N4Weight — Calculates the weighting matrices used in the singular-value decomposition step of
            the 'n4sid' algorithm. Applicable when InitializeMethod is 'n4sid'.
1-1416
                                                                                              tfestOptions
      Specifying this option allows unbiased estimates when using data that is collected in closed-
      loop operation. For more information about the algorithm, see [6].
   • 'auto' — The software automatically determines if the MOESP algorithm or the CVA
     algorithm should be used in the singular-value decomposition step.
   Default: 'auto'
• N4Horizon — Determines the forward and backward prediction horizons used by the 'n4sid'
  algorithm. Applicable when InitializeMethod is 'n4sid'.
   N4Horizon is a row vector with three elements: [r sy su], where r is the maximum forward
   prediction horizon. The algorithm uses up to r step-ahead predictors. sy is the number of past
   outputs, and su is the number of past inputs that are used for the predictions. See pages 209 and
   210 in [1] for more information. These numbers can have a substantial influence on the quality of
   the resulting model, and there are no simple rules for choosing them. Making 'N4Horizon' a k-
   by-3 matrix means that each row of 'N4Horizon' is tried, and the value that gives the best
   (prediction) fit to data is selected. k is the number of guesses of [r sy su] combinations.
   If N4Horizon = 'auto', the software uses an Akaike Information Criterion (AIC) for the
   selection of sy and su.
   Default: 'auto'
• FilterTimeConstant — Time constant of the differentiating filter used by the iv, svf, and
  gpmf initialization methods (see [4] and [5]).
FilterTimeConstant specifies the cutoff frequency of the differentiating filter, Fcutoff, as:
                 FilterTimeConstant
    Fcutof f =
                          Ts
   Default: 0.1
• MaxIterations — Maximum number of iterations. Applicable when InitializeMethod is
  'iv'.
   Default: 30
• Tolerance — Convergence tolerance. Applicable when InitializeMethod is 'iv'.
Default: 0.01
Handling of initial conditions during estimation, specified as one of the following values:
                                                                                                   1-1417
1   Functions
          Weighting prefilter applied to the loss function to be minimized during estimation. To understand the
          effect of WeightingFilter on the loss function, see “Loss Function and Model Quality Metrics”.
                Passbands are expressed in rad/TimeUnit for time-domain data and in FrequencyUnit for
                frequency-domain data, where TimeUnit and FrequencyUnit are the time and frequency units
                of the estimation data.
          • SISO filter — Specify a single-input-single-output (SISO) linear filter in one of the following ways:
                   This option calculates the weighting function as a product of the filter and the input spectrum
                   to estimate the transfer function.
          • Weighting vector — Applicable for frequency-domain data only. Specify a column vector of
            weights. This vector must have the same length as the frequency vector of the data set,
            Data.Frequency. Each input and output response in the data is multiplied by the corresponding
            weight at that frequency.
          • 'inv' — Applicable for estimation using frequency-response data only. Use 1/ G(ω) as the
            weighting filter, where G(ω) is the complex frequency-response data. Use this option for capturing
            relatively low amplitude dynamics in data, or for fitting data with high modal density. This option
            also makes it easier to specify channel-dependent weighting filters for MIMO frequency-response
            data.
          • 'invsqrt' — Applicable for estimation using frequency-response data only. Use 1/ G(ω) as the
            weighting filter. Use this option for capturing relatively low amplitude dynamics in data, or for
            fitting data with high modal density. This option also makes it easier to specify channel-dependent
            weighting filters for MIMO frequency-response data.
1-1418
                                                                                             tfestOptions
Control whether to enforce stability of estimated model, specified as the comma-separated pair
consisting of 'EnforceStability' and either true or false.
Use this option when estimating models using frequency-domain data. Models estimated using time-
domain data are always stable.
Data Types: logical
If EstimateCovariance is true, then use getcov to fetch the covariance matrix from the
estimated model.
Specify whether to display the estimation progress, specified as one of the following values:
• 'on' — Information on model structure and estimation results are displayed in a progress-viewer
  window.
• 'off' — No progress or results information is displayed.
Removal of offset from time-domain input data during estimation, specified as the comma-separated
pair consisting of 'InputOffset' and one of the following:
• A column vector of positive integers of length Nu, where Nu is the number of inputs.
• [] — Indicates no offset.
• Nu-by-Ne matrix — For multi-experiment data, specify InputOffset as an Nu-by-Ne matrix. Nu
  is the number of inputs, and Ne is the number of experiments.
Each entry specified by InputOffset is subtracted from the corresponding input data.
Removal of offset from time-domain output data during estimation, specified as the comma-separated
pair consisting of 'OutputOffset' and one of the following:
Each entry specified by OutputOffset is subtracted from the corresponding output data.
Weighting of prediction errors in multi-output estimations, specified as one of the following values:
                                                                                                1-1419
1   Functions
          • 'noise' — Minimize det(E′ * E/N), where E represents the prediction error and N is the number
            of data samples. This choice is optimal in a statistical sense and leads to maximum likelihood
            estimates if nothing is known about the variance of the noise. It uses the inverse of the estimated
            noise variance as the weighting function.
                • E is the matrix of prediction errors, with one column for each output, and W is the positive
                  semidefinite symmetric matrix of size equal to the number of outputs. Use W to specify the
                  relative importance of outputs in multiple-output models, or the reliability of corresponding
                  data.
                • N is the number of data samples.
          • [] — The software chooses between the 'noise' or using the identity matrix for W.
          Options for regularized estimation of model parameters. For more information on regularization, see
          “Regularized Estimates of Model Parameters”.
Specify a positive scalar to add the regularization term to the estimation cost.
                Default: 0
          • R — Weighting matrix.
                Specify a vector of nonnegative numbers or a square positive semi-definite matrix. The length
                must be equal to the number of free parameters of the model.
                For black-box models, using the default value is recommended. For structured and grey-box
                models, you can also specify a vector of np positive numbers such that each entry denotes the
                confidence in the value of the associated parameter.
                The default value of 1 implies a value of eye(npfree), where npfree is the number of free
                parameters.
                Default: 1
          • Nominal — The nominal value towards which the free parameters are pulled during estimation.
                The default value of zero implies that the parameter values are pulled towards zero. If you are
                refining a model, you can set the value to 'model' to pull the parameters towards the parameter
                values of the initial model. The initial parameter values must be finite for this setting to work.
Default: 0
1-1420
                                                                                            tfestOptions
Numerical search method used for iterative parameter estimation, specified as the comma-separated
pair consisting of 'SearchMethod' and one of the following:
• 'auto' — A combination of the line search algorithms, 'gn', 'lm', 'gna', and 'grad' methods
  is tried in sequence at each iteration. The first descent direction leading to a reduction in
  estimation cost is used.
• 'gn' — Subspace Gauss-Newton least squares search. Singular values of the Jacobian matrix less
  than GnPinvConstant*eps*max(size(J))*norm(J) are discarded when computing the
  search direction. J is the Jacobian matrix. The Hessian matrix is approximated as JTJ. If there is no
  improvement in this direction, the function tries the gradient direction.
• 'gna' — Adaptive subspace Gauss-Newton search. Eigenvalues less than gamma*max(sv) of the
  Hessian are ignored, where sv contains the singular values of the Hessian. The Gauss-Newton
  direction is computed in the remaining subspace. gamma has the initial value
  InitialGnaTolerance (see Advanced in 'SearchOptions' for more information). This value
  is increased by the factor LMStep each time the search fails to find a lower value of the criterion
  in fewer than five bisections. This value is decreased by the factor 2*LMStep each time a search is
  successful without any bisections.
• 'lm' — Levenberg-Marquardt least squares search, where the next parameter value is -pinv(H
  +d*I)*grad from the previous one. H is the Hessian, I is the identity matrix, and grad is the
  gradient. d is a number that is increased until a lower value of the criterion is found.
• 'grad' — Steepest descent least squares search.
• 'lsqnonlin' — Trust-region-reflective algorithm of lsqnonlin. Requires Optimization Toolbox
  software.
• 'fmincon' — Constrained nonlinear solvers. You can use the sequential quadratic programming
  (SQP) and trust-region-reflective algorithms of the fmincon solver. If you have Optimization
  Toolbox software, you can also use the interior-point and active-set algorithms of the fmincon
  solver. Specify the algorithm in the SearchOptions.Algorithm option. The fmincon algorithms
  may result in improved estimation results in the following scenarios:
   • Constrained minimization problems when there are bounds imposed on the model parameters.
   • Model structures where the loss function is a nonlinear or non smooth function of the
     parameters.
   • Multi-output model estimation. A determinant loss function is minimized by default for multi-
     output model estimation. fmincon algorithms are able to minimize such loss functions directly.
     The other search methods such as 'lm' and 'gn' minimize the determinant loss function by
     alternately estimating the noise variance and reducing the loss value for a given noise variance
     value. Hence, the fmincon algorithms can offer better efficiency and accuracy for multi-output
     model estimations.
Option set for the search algorithm, specified as the comma-separated pair consisting of
'SearchOptions' and a search option set with fields that depend on the value of SearchMethod.
                                                                                                1-1421
1   Functions
1-1422
                                                                                           tfestOptions
                                                                                              1-1423
1   Functions
1-1424
                                                                         tfestOptions
                            • 'sqp' — Sequential
                              quadratic programming
                              algorithm. The algorithm
                              satisfies bounds at all
                              iterations, and it can recover
                              from NaN or Inf results. It is
                              not a large-scale algorithm.
                              For more information, see
                              “Large-Scale vs. Medium-
                              Scale Algorithms”
                              (Optimization Toolbox).
                            • 'trust-region-
                              reflective' — Subspace
                              trust-region method based
                              on the interior-reflective
                              Newton method. It is a large-
                              scale algorithm.
                            • 'interior-point' —
                              Large-scale algorithm that
                              requires Optimization
                              Toolbox software. The
                              algorithm satisfies bounds at
                              all iterations, and it can
                              recover from NaN or Inf
                              results.
                            • 'active-set' — Requires
                              Optimization Toolbox
                              software. The algorithm can
                              take large steps, which adds
                              speed. It is not a large-scale
                              algorithm.
                                                                            1-1425
1   Functions
• ErrorThreshold — Specifies when to adjust the weight of large errors from quadratic to linear.
                Errors larger than ErrorThreshold times the estimated standard deviation have a linear weight
                in the loss function. The standard deviation is estimated robustly as the median of the absolute
                deviations from the median of the prediction errors, divided by 0.7. For more information on
                robust norm choices, see section 15.2 of [1].
                Default: 0
          • MaxSize — Specifies the maximum number of elements in a segment when input-output data is
            split into segments.
                Default: 250000
          • StabilityThreshold — Specifies thresholds for stability tests.
                • s — Specifies the location of the right-most pole to test the stability of continuous-time models.
                  A model is considered stable when its right-most pole is to the left of s.
                   Default: 0
                • z — Specifies the maximum distance of all poles from the origin to test stability of discrete-
                  time models. A model is considered stable if all poles are within the distance z from the origin.
1-1426
                                                                                         tfestOptions
      Default: 1+sqrt(eps)
• AutoInitThreshold — Specifies when to automatically estimate the initial conditions.
      yp, z − ymeas
                    > AutoInitThreshold
      yp, e − ymeas
Default: 1.05
Output Arguments
opt — Option set for tfest
tfestOptions option set
Examples
Create an options set for tfest using the 'n4sid' initialization algorithm and set the Display to
'on'.
opt = tfestOptions('InitializeMethod','n4sid','Display','on');
Compatibility Considerations
Renaming of Estimation and Analysis Options
The names of some estimation and analysis options were changed in R2018a. Prior names still work.
For details, see the R2018a release note “Renaming of Estimation and Analysis Options”.
                                                                                            1-1427
1   Functions
          References
          [1] Ljung, L. System Identification: Theory for the User. Upper Saddle River, NJ: Prentice-Hall PTR,
                  1999.
          [2] Knudsen, T. "New method for estimating ARMAX models," In Proceedings of 10th IFAC
                 Symposium on System Identification, SYSID'94, Copenhagen, Denmark, July 1994, Vol. 2, pp.
                 611–617.
          [3] Wills, Adrian, B. Ninness, and S. Gibson. “On Gradient-Based Search for Multivariable System
                   Estimates.” Proceedings of the 16th IFAC World Congress, Prague, Czech Republic, July 3–8,
                   2005. Oxford, UK: Elsevier Ltd., 2005.
          [4] Garnier, H., M. Mensler, and A. Richard. “Continuous-time Model Identification From Sampled
                  Data: Implementation Issues and Performance Evaluation” International Journal of Control,
                  2003, Vol. 76, Issue 13, pp 1337–1357.
          [5] Ljung, L. “Experiments With Identification of Continuous-Time Models.” Proceedings of the 15th
                  IFAC Symposium on System Identification. 2009.
          [6] Jansson, M. “Subspace identification and ARX modeling.” 13th IFAC Symposium on System
                  Identification , Rotterdam, The Netherlands, 2003.
          See Also
          tfest
          Topics
          “Loss Function and Model Quality Metrics”
Introduced in R2012b
1-1428
                                                                                            timeoptions
timeoptions
Create list of time plot options
Syntax
P = timeoptions
P = timeoptions('cstprefs')
Description
P = timeoptions returns a list of available options for time plots with default values set. You can
use these options to customize the time value plot appearance from the command line.
P = timeoptions('cstprefs') initializes the plot options you selected in the Control System and
System Identification Toolbox Preferences Editor. For more information about the editor, see “Toolbox
Preferences Editor”.
Option                                            Description
Title, XLabel, YLabel                             Label text and style
TickLabel                                         Tick label style
Grid                                              Show or hide the grid, specified as one of the
                                                  following values: 'off' | 'on'
                                                  Default: 'off'
GridColor                                         Color of the grid lines, specified as one of the
                                                  following: Vector of RGB values in the range
                                                  [0,1]| character vector of color name |'none'.
                                                  For example, for yellow color, specify as one of the
                                                  following: [1 1 0], 'yellow', or 'y'.
                                                  Default: [0.15,0.15,0.15]
XlimMode, YlimMode                                Limit modes
Xlim, Ylim                                        Axes limits
IOGrouping                                        Grouping of input-output pairs, specified as one of
                                                  the following values: 'none'
                                                  |'inputs'|'outputs'|'all'
                                                  Default: 'none'
InputLabels, OutputLabels                         Input and output label styles
InputVisible, OutputVisible                       Visibility of input and output channels
Normalize                                         Normalize responses, specified as one of the
                                                  following values: 'on' |'off'
                                                  Default: 'off'
SettleTimeThreshold                               Settling time threshold
RiseTimeLimits                                    Rise time limits
                                                                                               1-1429
1   Functions
           Option                                            Description
           TimeUnits                                         Time units, specified as one of the following
                                                             values:
                                                             • 'nanoseconds'
                                                             • 'microseconds'
                                                             • 'milliseconds'
                                                             • 'seconds'
                                                             • 'minutes'
                                                             • 'hours'
                                                             • 'days'
                                                             • 'weeks'
                                                             • 'months'
                                                             • 'years'
Default: 'seconds'
Examples
opt = timeoptions;
opt.Normalize = 'on';
Plot the step response of two transfer function models using the specified options.
          sys1 = tf(10,[1,1]);
          sys2 = tf(5,[1,5]);
          stepplot(sys1,sys2,opt);
1-1430
                                                                                    timeoptions
The plot shows the normalized step response for the two transfer function models.
See Also
getoptions | impulseplot | initialplot | lsimplot | setoptions | stepplot
Introduced in R2012a
                                                                                      1-1431
1   Functions
          totaldelay
          Total combined I/O delays for LTI model
          Syntax
          td = totaldelay(sys)
          Description
          td = totaldelay(sys) returns the total combined I/O delays for an LTI model sys. The matrix td
          combines contributions from the InputDelay, OutputDelay, and ioDelayMatrix properties.
          Delays are expressed in seconds for continuous-time models, and as integer multiples of the sample
          period for discrete-time models. To obtain the delay times in seconds, multiply td by the sample time
          sys.Ts.
Examples
          sys.InputDelay = 2;
          sys.Outputdelay = 1.5;
td = totaldelay(sys)
td = 3.5000
                     1                    1
                e−2sx e−1 . 5s = e−3 . 5s
                     s                    s
          This result is equivalent to specifying an input-output delay of 3.5 seconds for the original transfer
          function, 1/s.
          See Also
          absorbDelay | hasdelay
Introduced in R2012a
1-1432
                                                                                         translatecov
translatecov
Translate parameter covariance across model transformation operations
Syntax
sys_new = translatecov(fcn,sys)
sys_new = translatecov(fcn,Input1,...,InputN)
Description
sys_new = translatecov(fcn,sys) transforms sys into sys_new = fcn(sys), and translates
the parameter covariance of sys to the parameter covariance of the transformed model. fcn is a
transformation function that you specify. The command computes the parameter covariance of
sys_new by applying the Gauss Approximation formula. To view the translated parameter covariance,
use getcov.
Applying model transformations directly does not always translate the parameter covariance of the
original model to that of the transformed model. For example, d2c(sys) does not translate the
parameter covariance of sys. In contrast, translatecov(@(x)d2c(x),sys) produces a
transformed model that has the same coefficients as d2c(sys) and has the translated parameter
covariance of sys.
Input Arguments
fcn
For single-input functions, sys_new = fcn(sys). The input to fcn must be an identified model with
parameter covariance information. Typical single-input transformation operations include:
• Model-type conversion, such as idpoly and idss. For example, fcn = @(x)idpoly(x)
  converts the model x to a polynomial model.
• Sample time conversion, such as c2d and d2c. For example, fcn = @(x)c2d(x,Ts) converts
  the continuous-time model x to discrete-time using the specified sample time Ts.
For multi-input functions, sys_new = fcn(Input1,..InputN). At least one of the input arguments
Input1,...,InputN must be an identified model with parameter covariance information. Typical
multi-input operations include merging and concatenation of multiple models. For example, fcn =
@(x,y)[x,y] performs horizontal concatenation of the models x and y.
sys
Linear model with parameter covariance information, specified as one of the following model types:
                                                                                            1-1433
1   Functions
          • idtf
          • idproc
          • idss
          • idpoly
          • idgrey
The model must contain parameter covariance information, that is getcov(sys) must be nonempty.
Input1,...,InputN
          Multiple input arguments to the translation function fcn. At least one of the N inputs must be a linear
          identified model with parameter covariance information. The other inputs can be any MATLAB data
          type. For an example, see “Translate Parameter Covariance to Closed-Loop Model” on page 1-1437.
          Output Arguments
          sys_new
          Model resulting from transformation operation. The model includes parameter covariance
          information.
Examples
          Convert an estimated transfer function model into state-space model while also translating the
          estimated parameter covariance.
          load iddata1
          sys1 = tfest(z1,2);
          Convert the estimated model to state-space form while also translating the estimated parameter
          covariance.
sys2 = translatecov(@(x)idss(x),sys1);
          If you convert the transfer function model to state-space form directly, the estimated parameter
          covariance is lost (the output of getcov is empty).
          sys3 = idss(sys1);
          getcov(sys3)
ans =
[]
          covsys1 = getcov(sys1);
          covsys2 = getcov(sys2);
1-1434
                                                                                       translatecov
h = bodeplot(sys1,sys2);
showConfidence(h,2);
Concatenate 3 single-output models such that the covariance data from the 3 models combine to
produce the covariance data for the resulting model.
t = (0:0.01:0.99)';
u = randn(100,2);
y = lsim(sys,u,t,'zoh');
                                                                                           1-1435
1   Functions
          y = y + rand(size(y))/10;
          data = iddata(y,u,0.01);
Combine the estimated models while also translating the covariance information.
          f = @(x,y,z)[x;y;z];
          M2 = translatecov(f, m1, m2, m3);
getcov(M2, 'factors')
          If you combine the estimated models into one 3-output model directly, the covariance information is
          lost (the output of getcov is empty).
          M1 = [m1;m2;m3];
          getcov(M1)
ans =
[]
1-1436
                                                                                            translatecov
The confidence bounds for M2 overlap with those of m1, m2 and m3 models on their respective plot
axes.
Consider a closed-loop feedback model consisting of a plant and controller. Translate the parameter
covariance of the plant to the closed-loop feedback model.
Create a controller as a continuous-time zero-pole-gain model with zeros, poles, and gain equal to -2,
-10, 5, respectively.
Controller = zpk(-2,-10,5);
Translate the parameter covariance of the plant to the closed-loop feedback model.
                                                                                               1-1437
1   Functions
sys_new = translatecov(fcn,Plant,Controller);
          Plot the frequency-response of the transformed model sys_new, and view the confidence region of
          the response.
          h = bodeplot(sys_new);
          showConfidence(h);
The plot shows the effect of the uncertainty in Plant on the closed-loop response.
          Tips
          • If you obtained sys through estimation and have access to the estimation data, you can use zero-
            iteration update to recompute the parameter covariance. For example:
                load iddata1
                m = ssest(z1,4);
                opt = ssestOptions
                opt.SearchOptions.MaxIterations = 0;
                m_new = ssest(z1,m2,opt)
1-1438
                                                                                         translatecov
Algorithms
translatecov uses numerical perturbations of individual parameters of sys to compute the
Jacobian of fcn(sys) parameters with respect to parameters of sys. translatecov then applies
Gauss Approximation formula cov_new = J × cov×  J T to translate the covariance, where J is the
Jacobian matrix. This operation can be slow for models containing a large number of free parameters.
See Also
getcov | getpvec | rsample | setcov
Topics
“What Is Model Covariance?”
“Types of Model Uncertainty Information”
Introduced in R2012b
                                                                                            1-1439
1   Functions
          treepartition
          Class representing binary-tree nonlinearity estimator for nonlinear ARX models
          Syntax
          t=treepartition(Property1,Value1,...PropertyN,ValueN)
          t=treepartition('NumberOfUnits',N)
          Description
          treepartition is an object that stores the binary-tree nonlinear estimator for estimating nonlinear
          ARX models. The object defines a nonlinear function y = F(x), where F is a piecewise-linear (affine)
          function of x, y is scalar, and x is a 1-by-m vector. Compute the value of F using evaluate(t,x),
          where t is the treepartition object at x.
          Construction
          t=treepartition(Property1,Value1,...PropertyN,ValueN) creates a binary tree
          nonlinearity estimator object specified by properties in “treepartition Properties” on page 1-1440.
          The tree has the number of leaves equal to 2^(J+1)-1, where J is the number of nodes in the tree
          and set by the property NumberOfUnits. The default value of NumberOfUnits is computed
          automatically and sets an upper limit on the actual number of tree nodes used by the estimator.
          treepartition Properties
          You can include property-value pairs in the constructor to specify the object.
          After creating the object, you can use get or dot notation to access the object property values. For
          example:
You can also use the set function to set the value of particular properties. For example:
set(t, 'NumberOfUnits', 5)
1-1440
                                                                                treepartition
For example:
                treepartition('NumberOfUnits',5)
Parameters      Structure containing the following fields:
                                                                                     1-1441
1   Functions
          Examples
          Use treepartition to specify the nonlinear estimator in nonlinear ARX models. For example:
m=nlarx(Data,Orders,treepartition('num',5));
          Algorithms
          The mapping F is defined by a dyadic partition P of the x-space, such that on each partition element
          Pk, F is a linear mapping. When x belongs to Pk, F(x) is given by:
F(x) = d + xL + 1, x Ck,
          where L is 1-by-m vector and d is a scalar common for all elements of partition. Ck is a 1-by-(m+1)
          vector.
The mapping F and associated partition P of the x-space are computed as follows:
          1     Given the value of J, a dyadic tree with J levels and N = 2J–1 nodes is initialized.
          2     Each node at level 1 < j < J has two descendants at level j + 1 and one parent at level j – 1.
1-1442
                                                                                           treepartition
You cannot use treepartition when Focus is 'simulation' because this nonlinearity estimators
is not differentiable. Minimization of simulation error requires differentiable nonlinear functions.
See Also
nlarx
Introduced in R2007a
                                                                                               1-1443
1   Functions
          TrendInfo
          Offset and linear trend slope values for detrending data
          Description
          TrendInfo class represents offset and linear trend information of input and output data.
          Constructing the corresponding object lets you:
          • Compute and store mean values or best-fit linear trends of input and output data signals.
          • Define specific offsets and trends to be removed from input-output data.
By storing offset and trend information, you can apply it to multiple data sets.
          After estimating a linear model from detrended data, you can simulate the model at original operation
          conditions by adding the saved trend to the simulated output using retrend.
          Construction
          For transient data, if you want to define a specific offset or trend to be removed from this data, create
          the TrendInfo object using getTrend. For example:
T = getTrend(data)
          where data is the iddata object from which you will be removing the offset or linear trend, and T is
          the TrendInfo object. You must then assign specific offset and slope values as properties of this
          object before passing the object as an argument to detrend.
          For steady-state data, if you want to detrend the data and store the trend information, use the
          detrend command with the output argument for storing trend information.
          Properties
          After creating the object, you can use get or dot notation to access the object property values.
1-1444
                                                                                                       TrendInfo
Examples
load dryer2
Create a data object with sample time of 0.08 seconds and plot it.
       data = iddata(y2,u2,0.08);
       plot(data)
                                                                                                       1-1445
1   Functions
T = getTrend(data);
          T.InputOffset = 5;
          T.OutputOffset = 5;
data_d = detrend(data,T);
          hold on
          plot(data_d)
1-1446
                                                                                           TrendInfo
get(T)
Construct the TrendInfo object that stores trend information as part of data detrending.
load dryer2
data = iddata(y2,u2,0.08);
Detrend the mean from the data and store the mean as a TrendInfo object T.
                                                                                           1-1447
1   Functions
[data_d,T] = detrend(data,0);
get(T)
          See Also
          detrend | getTrend | retrend
          Topics
          “Handling Offsets and Trends in Data”
Introduced in R2009a
1-1448
                                                                                                  unitgain
unitgain
Specify absence of nonlinearities for specific input or output channels in Hammerstein-Wiener models
Syntax
unit=unitgain
Description
unit=unitgain instantiates an object that specifies an identity mapping F(x)=x to exclude specific
input and output channels from being affected by a nonlinearity in Hammerstein-Wiener models.
Use the unitgain object as an argument in the nlhw estimator to set the corresponding channel
nonlinearity to unit gain.
For example, for a two-input and one-output model, to exclude the second input from being affected
by a nonlinearity, use the following syntax:
m = nlhw(data,orders,['saturation''unitgain'],'deadzone')
In this case, the first input saturates and the output has an associated deadzone nonlinearity.
unitgain Properties
unitgain does not have properties.
Examples
For example, for a one-input and one-output model, to exclude the output from being affected by a
nonlinearity, use the following syntax:
m = nlhw(Data,Orders,'saturation','unitgain')
If nonlinearities are absent in input or output channels, you can replace unitgain with an empty
matrix. For example, to specify a Wiener model with a sigmoid nonlinearity at the output and a unit
gain at the input, use the following command:
m = nlhw(Data,Orders,[],'sigmoid');
Tips
Use the unitgain object to exclude specific input and output channels from being affected by a
nonlinearity in Hammerstein-Wiener models. unitgain is a linear function y = F(x), where F(x)=x.
See Also
deadzone | nlhw | saturation | sigmoidnet
                                                                                                  1-1449
1   Functions
Introduced in R2007a
1-1450
                                                                                 unscentedKalmanFilter
unscentedKalmanFilter
Create unscented Kalman filter object for online state estimation
Syntax
obj = unscentedKalmanFilter(StateTransitionFcn,MeasurementFcn,InitialState)
obj = unscentedKalmanFilter(StateTransitionFcn,MeasurementFcn,InitialState,
Name,Value)
obj = unscentedKalmanFilter(StateTransitionFcn,MeasurementFcn)
obj = unscentedKalmanFilter(StateTransitionFcn,MeasurementFcn,Name,Value)
obj = unscentedKalmanFilter(Name,Value)
Description
obj = unscentedKalmanFilter(StateTransitionFcn,MeasurementFcn,InitialState)
creates an unscented Kalman filter object for online state estimation of a discrete-time nonlinear
system. StateTransitionFcn is a function that calculates the state of the system at time k, given
the state vector at time k-1. MeasurementFcn is a function that calculates the output measurement
of the system at time k, given the state at time k. InitialState specifies the initial value of the
state estimates.
After creating the object, use the correct and predict commands to update state estimates and
state estimation error covariance values using a discrete-time unscented Kalman filter algorithm and
real-time data.
obj = unscentedKalmanFilter(StateTransitionFcn,MeasurementFcn,InitialState,
Name,Value) specifies additional attributes of the unscented Kalman filter object using one or more
Name,Value pair arguments.
obj = unscentedKalmanFilter(StateTransitionFcn,MeasurementFcn,Name,Value)
specifies additional attributes of the unscented Kalman filter object using one or more Name,Value
pair arguments. Before using the predict and correct commands, specify the initial state values
using Name,Value pair arguments or dot notation.
Object Description
unscentedKalmanFilter creates an object for online state estimation of a discrete-time nonlinear
system using the discrete-time unscented Kalman filter algorithm.
                                                                                              1-1451
1   Functions
          Consider a plant with states x, input u, output y, process noise w, and measurement noise v. Assume
          that you can represent the plant as a nonlinear system.
          The algorithm computes the state estimates x of the nonlinear system using state transition and
          measurement functions specified by you. The software lets you specify the noise in these functions as
          additive or nonadditive:
          • Additive Noise Terms — The state transition and measurements equations have the following
            form:
                Here f is a nonlinear state transition function that describes the evolution of states x from one
                time step to the next. The nonlinear measurement function h relates x to the measurements y at
                time step k. w and v are the zero-mean, uncorrelated process and measurement noises,
                respectively. These functions can also have additional input arguments that are denoted by us and
                um in the equations. For example, the additional arguments could be time step k or the inputs u to
                the nonlinear system. There can be multiple such arguments.
                Note that the noise terms in both equations are additive. That is, x(k) is linearly related to the
                process noise w(k-1), and y(k) is linearly related to the measurement noise v(k).
          • Nonadditive Noise Terms — The software also supports more complex state transition and
            measurement functions where the state x[k] and measurement y[k] are nonlinear functions of the
            process noise and measurement noise, respectively. When the noise terms are nonadditive, the
            state transition and measurements equation have the following form:
          When you perform online state estimation, you first create the nonlinear state transition function f
          and measurement function h. You then construct the unscentedKalmanFilter object using these
          nonlinear functions, and specify whether the noise terms are additive or nonadditive. After you create
          the object, you use the predict command to predict state estimates at the next time step, and
          correct to correct state estimates using the unscented Kalman filter algorithm and real-time data.
          For information about the algorithm, see “Extended and Unscented Kalman Filter Algorithms for
          Online State Estimation”.
1-1452
                                                                                    unscentedKalmanFilter
Command                                              Description
correct                                              Correct the state and state estimation error
                                                     covariance at time step k using measured data at
                                                     time step k.
predict                                              Predict the state and state estimation error
                                                     covariance at time the next time step.
residual                                             Return the difference between the actual and
                                                     predicted measurements.
clone                                                Create another object with the same object
                                                     property values.
Examples
To define an unscented Kalman filter object for estimating the states of your system, you write and
save the state transition function and measurement function for the system.
In this example, use the previously written and saved state transition and measurement functions,
vdpStateFcn.m and vdpMeasurementFcn.m. These functions describe a discrete-approximation to
van der Pol oscillator with nonlinearity parameter, mu, equal to 1. The oscillator has two states.
Specify an initial guess for the two states. You specify the initial state guess as an M-element row or
column vector, where M is the number of states.
initialStateGuess = [1;0];
Create the unscented Kalman filter object. Use function handles to provide the state transition and
measurement functions to the object.
obj = unscentedKalmanFilter(@vdpStateFcn,@vdpMeasurementFcn,initialStateGuess);
The object has a default structure where the process and measurement noise are additive.
To estimate the states and state estimation error covariance from the constructed object, use the
correct and predict commands and real-time data.
Specify Process and Measurement Noise Covariances in Unscented Kalman Filter Object
Create an unscented Kalman filter object for a van der Pol oscillator with two states and one output.
Use the previously written and saved state transition and measurement functions, vdpStateFcn.m
                                                                                                 1-1453
1   Functions
          and vdpMeasurementFcn.m. These functions are written for additive process and measurement
          noise terms. Specify the initial state values for the two states as [2;0].
          Since the system has two states and the process noise is additive, the process noise is a 2-element
          vector and the process noise covariance is a 2-by-2 matrix. Assume there is no cross-correlation
          between process noise terms, and both the terms have the same variance 0.01. You can specify the
          process noise covariance as a scalar. The software uses the scalar value to create a 2-by-2 diagonal
          matrix with 0.01 on the diagonals.
          Alternatively, you can specify noise covariances after object construction using dot notation. For
          example, specify the measurement noise covariance as 0.2.
          obj.MeasurementNoise = 0.2;
          Since the system has only one output, the measurement noise is a 1-element vector and the
          MeasurementNoise property denotes the variance of the measurement noise.
          Create an unscented Kalman filter object for a van der Pol oscillator with two states and one output.
          Assume that the process noise terms in the state transition function are additive. That is, there is a
          linear relation between the state and process noise. Also assume that the measurement noise terms
          are nonadditive. That is, there is a nonlinear relation between the measurement and measurement
          noise.
          obj = unscentedKalmanFilter('HasAdditiveMeasurementNoise',false);
          Specify the state transition function and measurement functions. Use the previously written and
          saved functions, vdpStateFcn.m and vdpMeasurementNonAdditiveNoiseFcn.m.
          The state transition function is written assuming the process noise is additive. The measurement
          function is written assuming the measurement noise is nonadditive.
          obj.StateTransitionFcn = @vdpStateFcn;
          obj.MeasurementFcn = @vdpMeasurementNonAdditiveNoiseFcn;
          Specify the initial state values for the two states as [2;0].
          obj.State = [2;0];
          You can now use the correct and predict commands to estimate the state and state estimation
          error covariance values from the constructed object.
          Consider a nonlinear system with input u whose state x and measurement y evolve according to the
          following state transition and measurement equations:
1-1454
                                                                                    unscentedKalmanFilter
                                2
    y[k] = x[k] + 2 * u[k] + v[k]
The process noise w of the system is additive while the measurement noise v is nonadditive.
Create the state transition function and measurement function for the system. Specify the functions
with an additional input u.
f = @(x,u)(sqrt(x+u));
h = @(x,v,u)(x+2*u+v^2);
f and h are function handles to the anonymous functions that store the state transition and
measurement functions, respectively. In the measurement function, because the measurement noise
is nonadditive, v is also specified as an input. Note that v is specified as an input before the
additional input u.
Create an unscented Kalman filter object for estimating the state of the nonlinear system using the
specified functions. Specify the initial value of the state as 1, and the measurement noise as
nonadditive.
obj = unscentedKalmanFilter(f,h,1,'HasAdditiveMeasurementNoise',false);
You can now estimate the state of the system using the predict and correct commands. You pass
the values of u to predict and correct, which in turn pass them to the state transition and
measurement functions, respectively.
Correct the state estimate with measurement y[k]=0.8 and input u[k]=0.2 at time step k.
correct(obj,0.8,0.2)
Input Arguments
StateTransitionFcn — State transition function
function handle
State transition function f, specified as a function handle. The function calculates the Ns-element
state vector of the system at time step k, given the state vector at time step k-1. Ns is the number of
states of the nonlinear system.
You write and save the state transition function for your nonlinear system, and use it to construct the
object. For example, if vdpStateFcn.m is the state transition function, specify
StateTransitionFcn as @vdpStateFcn. You can also specify StateTransitionFcn as a function
handle to an anonymous function.
The inputs to the function you write depend on whether you specify the process noise as additive or
nonadditive in the HasAdditiveProcessNoise property of the object:
                                                                                                 1-1455
1   Functions
          • HasAdditiveProcessNoise is true — The process noise w is additive, and the state transition
            function specifies how the states evolve as a function of state values at the previous time step:
x(k) = f(x(k-1),Us1,...,Usn)
                Where x(k) is the estimated state at time k, and Us1,...,Usn are any additional input
                arguments required by your state transition function, such as system inputs or the sample time.
                During estimation, you pass these additional arguments to the predict command, which in turn
                passes them to the state transition function.
          • HasAdditiveProcessNoise is false — The process noise is nonadditive, and the state transition
            function also specifies how the states evolve as a function of the process noise:
x(k) = f(x(k-1),w(k-1),Us1,...,Usn)
          To see an example of a state transition function with additive process noise, type edit
          vdpStateFcn at the command line.
          Measurement function h, specified as a function handle. The function calculates the N-element output
          measurement vector of the nonlinear system at time step k, given the state vector at time step k. N is
          the number of measurements of the system. You write and save the measurement function, and use it
          to construct the object. For example, if vdpMeasurementFcn.m is the measurement function, specify
          MeasurementFcn as @vdpMeasurementFcn. You can also specify MeasurementFcn as a function
          handle to an anonymous function.
          The inputs to the function depend on whether you specify the measurement noise as additive or
          nonadditive in the HasAdditiveMeasurementNoise property of the object:
y(k) = h(x(k),Um1,...,Umn)
                Where y(k) and x(k) are the estimated output and estimated state at time k, and Um1,...,Umn
                are any optional input arguments required by your measurement function. For example, if you are
                using multiple sensors for tracking an object, an additional input could be the sensor position.
                During estimation, you pass these additional arguments to the correct command, which in turn
                passes them to the measurement function.
          • HasAdditiveMeasurementNoise is false — The measurement noise is nonadditive, and the
            measurement function also specifies how the output measurement evolves as a function of the
            measurement noise:
y(k) = h(x(k),v(k),Um1,...,Umn)
          To see an example of a measurement function with additive process noise, type edit
          vdpMeasurementFcn at the command line. To see an example of a measurement function with
          nonadditive process noise, type edit vdpMeasurementNonAdditiveNoiseFcn.
1-1456
                                                                                      unscentedKalmanFilter
Initial state estimates, specified as an Ns-element vector, where Ns is the number of states in the
system. Specify the initial state values based on your knowledge of the system.
The specified value is stored in the State property of the object. If you specify InitialState as a
column vector then State is also a column vector, and predict and correct commands return
state estimates as a column vector. Otherwise, a row vector is returned.
If you want a filter with single-precision floating-point variables, specify InitialState as a single-
precision vector variable. For example, for a two-state system with state transition and measurement
functions vdpStateFcn.m and vdpMeasurementFcn.m, create the unscented Kalman filter object
with initial states [1;2] as follows:
obj = unscentedKalmanFilter(@vdpStateFcn,@vdpMeasurementFcn,single([1;2]))
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
Properties
unscentedKalmanFilter object properties are of three types:
• Tunable properties that you can specify multiple times, either during object construction using
  Name,Value arguments, or any time afterwards during state estimation. After object creation,
  use dot notation to modify the tunable properties.
   obj = unscentedKalmanFilter(StateTransitionFcn,MeasurementFcn,InitialState);
   obj.ProcessNoise = 0.01;
Spread of sigma points around mean state value, specified as a scalar value between 0 and 1 ( 0 <
Alpha <= 1).
The unscented Kalman filter algorithm treats the state of the system as a random variable with mean
value State and variance StateCovariance. To compute the state and its statistical properties at
                                                                                                   1-1457
1   Functions
          the next time step, the algorithm first generates a set of state values distributed around the mean
          State value by using the unscented transformation. These generated state values are called sigma
          points. The algorithm uses each of the sigma points as an input to the state transition and
          measurement functions to get a new set of transformed state points and measurements. The
          transformed points are used to compute the state and state estimation error covariance value at the
          next time step.
          The spread of the sigma points around the mean state value is controlled by two parameters Alpha
          and Kappa. A third parameter, Beta, impacts the weights of the transformed points during state and
          measurement covariance calculations:
          • Alpha — Determines the spread of the sigma points around the mean state value. It is usually a
            small positive value. The spread of sigma points is proportional to Alpha. Smaller values
            correspond to sigma points closer to the mean state.
          • Kappa — A second scaling parameter that is usually set to 0. Smaller values correspond to sigma
            points closer to the mean state. The spread is proportional to the square-root of Kappa.
          • Beta — Incorporates prior knowledge of the distribution of the state. For Gaussian distributions,
            Beta = 2 is optimal.
          If you know the distribution of state and state covariance, you can adjust these parameters to capture
          the transformation of higher-order moments of the distribution. The algorithm can track only a single
          peak in the probability distribution of the state. If there are multiple peaks in the state distribution of
          your system, you can adjust these parameters so that the sigma points stay around a single peak. For
          example, choose a small Alpha to generate sigma points close to the mean state value.
          Characterization of the state distribution that is used to adjust weights of transformed sigma points,
          specified as a scalar value greater than or equal to 0. For Gaussian distributions, Beta = 2 is an
          optimal choice.
y(k) = h(x(k),Um1,...,Umn)
                Where y(k) and x(k) are the estimated output and estimated state at time k, and Um1,...,Umn
                are any optional input arguments required by your measurement function.
          • false — Measurement noise is nonadditive. The measurement function specifies how the output
            measurement evolves as a function of the state and measurement noise:
1-1458
                                                                                     unscentedKalmanFilter
y(k) = h(x(k),v(k),Um1,...,Umn)
HasAdditiveMeasurementNoise is a nontunable property, and you can specify it only during object
construction. You cannot change it using dot notation.
x(k) = f(x(k-1),Us1,...,Usn)
   Where x(k) is the estimated state at time k, and Us1,...,Usn are any additional input
   arguments required by your state transition function.
• false — Process noise is nonadditive. The state transition function specifies how the states
  evolve as a function of the state and process noise at the previous time step:
x(k) = f(x(k-1),w(k-1),Us1,...,Usn)
HasAdditiveProcessNoise is a nontunable property, and you can specify it only during object
construction. You cannot change it using dot notation.
Spread of sigma points around mean state value, specified as a scalar value between 0 and 3 ( 0 <=
Kappa <= 3). Kappa is typically specified as 0. Smaller values correspond to sigma points closer to
the mean state. The spread is proportional to the square-root of Kappa. For more information, see the
Alpha property description.
Measurement function h, specified as a function handle. The function calculates the N-element output
measurement vector of the nonlinear system at time step k, given the state vector at time step k. N is
the number of measurements of the system. You write and save the measurement function and use it
to construct the object. For example, if vdpMeasurementFcn.m is the measurement function, specify
MeasurementFcn as @vdpMeasurementFcn. You can also specify MeasurementFcn as a function
handle to an anonymous function.
The inputs to the function depend on whether you specify the measurement noise as additive or
nonadditive in the HasAdditiveMeasurementNoise property of the object:
y(k) = h(x(k),Um1,...,Umn)
   Where y(k) and x(k) are the estimated output and estimated state at time k, and Um1,...,Umn
   are any optional input arguments required by your measurement function. For example, if you are
                                                                                                  1-1459
1   Functions
                using multiple sensors for tracking an object, an additional input could be the sensor position.
                During estimation, you pass these additional arguments to the correct command which in turn
                passes them to the measurement function.
          • HasAdditiveMeasurementNoise is false — The measurement noise is nonadditive, and the
            measurement function also specifies how the output measurement evolves as a function of the
            measurement noise:
y(k) = h(x(k),v(k),Um1,...,Umn)
          To see an example of a measurement function with additive process noise, type edit
          vdpMeasurementFcn at the command line. To see an example of a measurement function with
          nonadditive process noise, type edit vdpMeasurementNonAdditiveNoiseFcn.
          MeasurementFcn is a nontunable property. You can specify it once before using the correct
          command either during object construction or using dot notation after object construction. You
          cannot change it after using the correct command.
          Measurement noise covariance, specified as a scalar or matrix depending on the value of the
          HasAdditiveMeasurementNoise property:
          Process noise covariance, specified as a scalar or matrix depending on the value of the
          HasAdditiveProcessNoise property:
1-1460
                                                                                    unscentedKalmanFilter
State of the nonlinear system, specified as a vector of size Ns, where Ns is the number of states of the
system.
When you use the predict command, State is updated with the predicted value at time step k using
the state value at time step k–1. When you use the correct command, State is updated with the
estimated value at time step k using measured data at time step k.
The initial value of State is the value you specify in the InitialState input argument during
object creation. If you specify InitialState as a column vector, then State is also a column vector,
and the predict and correct commands return state estimates as a column vector. Otherwise, a
row vector is returned. If you want a filter with single-precision floating-point variables, you must
specify State as a single-precision variable during object construction using the InitialState
input argument.
State estimation error covariance, specified as a scalar or an Ns-by-Ns matrix, where Ns is the
number of states of the system. If you specify a scalar, the software uses the scalar value to create an
Ns-by-Ns diagonal matrix.
Specify a high value for the covariance when you do not have confidence in the initial state values
that you specify in the InitialState input argument.
When you use the predict command, StateCovariance is updated with the predicted value at
time step k using the state value at time step k–1. When you use the correct command,
StateCovariance is updated with the estimated value at time step k using measured data at time
step k.
StateCovariance is a tunable property. You can change it using dot notation after using the
correct or predict commands.
State transition function f, specified as a function handle. The function calculates the Ns-element
state vector of the system at time step k, given the state vector at time step k-1. Ns is the number of
states of the nonlinear system.
You write and save the state transition function for your nonlinear system and use it to construct the
object. For example, if vdpStateFcn.m is the state transition function, specify
StateTransitionFcn as @vdpStateFcn. You can also specify StateTransitionFcn as a function
handle to an anonymous function.
The inputs to the function you write depend on whether you specify the process noise as additive or
nonadditive in the HasAdditiveProcessNoise property of the object:
• HasAdditiveProcessNoise is true — The process noise w is additive, and the state transition
  function specifies how the states evolve as a function of state values at previous time step:
                                                                                                 1-1461
1   Functions
x(k) = f(x(k-1),Us1,...,Usn)
                Where x(k) is the estimated state at time k, and Us1,...,Usn are any additional input
                arguments required by your state transition function, such as system inputs or the sample time.
                During estimation, you pass these additional arguments to the predict command, which in turn
                passes them to the state transition function.
          • HasAdditiveProcessNoise is false — The process noise is nonadditive, and the state transition
            function also specifies how the states evolve as a function of the process noise:
x(k) = f(x(k-1),w(k-1),Us1,...,Usn)
          To see an example of a state transition function with additive process noise, type edit
          vdpStateFcn at the command line.
          StateTransitionFcn is a nontunable property. You can specify it once before using the predict
          command either during object construction or using dot notation after object construction. You
          cannot change it after using the predict command.
          Output Arguments
          obj — unscented Kalman filter object for online state estimation
          unscentedKalmanFilter object
          Unscented Kalman filter object for online state estimation, returned as an unscentedKalmanFilter
          object. This object is created using the specified properties on page 1-1457. Use the correct and
          predict commands to estimate the state and state estimation error covariance using the unscented
          Kalman filter algorithm.
          When you use predict, obj.State and obj.StateCovariance are updated with the predicted
          value at time step k using the state value at time step k–1. When you use correct, obj.State and
          obj.StateCovariance are updated with the estimated values at time step k using measured data
          at time step k.
          Extended Capabilities
          C/C++ Code Generation
          Generate C and C++ code using MATLAB® Coder™.
For more information, see “Generate Code for Online State Estimation in MATLAB”.
          See Also
          Functions
          clone | correct | extendedKalmanFilter | predict | residual
          Blocks
          Extended Kalman Filter | Kalman Filter | Unscented Kalman Filter
1-1462
                                                                                 unscentedKalmanFilter
Topics
“Nonlinear State Estimation Using Unscented Kalman Filter and Particle Filter”
“Generate Code for Online State Estimation in MATLAB”
“What Is Online Estimation?”
“Extended and Unscented Kalman Filter Algorithms for Online State Estimation”
“Validate Online State Estimation at the Command Line”
“Troubleshoot Online State Estimation”
Introduced in R2016b
                                                                                              1-1463
1   Functions
          wavenet
          Create a wavelet network nonlinearity estimator object
          Syntax
          NL = wavenet
          NL = wavenet(Name,Value)
          Description
          NL = wavenet creates a default wavelet network nonlinearity estimator object for estimating
          nonlinear ARX and Hammerstein-Wiener models. Use dot notation to customize the object properties,
          if needed.
          Object Description
          wavenet is an object that stores the wavelet network nonlinearity estimator for estimating nonlinear
          ARX and Hammerstein-Wiener models.
          Use wavenet to define a nonlinear function y = F(x, θ), where y is scalar, x is an m-dimensional row
          vector of regressors, and θ represent the parameters in wavelet expansion. The wavelet network
          function is based on the following function expansion:
                                   T
                 f (z) = e−0.5zz
                                              T
                 g(z)  =  (m − zzT )e−0.5zz
Here,
          • f(z) is a radial function called the scaling function, and z is the input to the scaling function. z is a
            1-by-q row vector. q is the number of components of x used in the scaling and wavelet functions.
          • g(z) is a radial function called the wavelet function, and z is the input to the wavelet function.
          • θ represents the following parameters of the nonlinearity estimator:
1-1464
                                                                                             wavenet
      When used in a nonlinear ARX model, q is equal to the size of the NonlinearRegressors
      property of the idnlarx object. When used in a Hammerstein-Wiener model, m=q=1 and Q is a
      scalar.
   • r – Mean value of the regressor vector computed from estimation data, specified as a 1-by-m
     vector.
   • as, bs, aw, and bw — Scaling and wavelet parameters, specified as scalars. Parameters with the s
     subscript are scaling parameters, and parameters with the w subscript are wavelet
     parameters.
   • L — Specified as a p-by-1 vector.
   • cs and cw – Specified as a 1-by-q vectors.
   • d — Output offset, specified as a scalar.
Examples
NL = wavenet;
NL.LinearTerm = 'off';
load twotankdata;
z = iddata(y,u,0.2);
NL = wavenet('NumberOfUnits',5);
                                                                                             1-1465
1   Functions
load motorizedcamera;
z = iddata(y,u,0.02,'Name','Motorized Camera','TimeUnit','s');
Orders = [ones(2,2),2*ones(2,6),ones(2,6)];
NL = [wavenet('NumberOfUnits',2),linear];
sys = nlarx(z,Orders,NL);
load motorizedcamera;
z = iddata(y,u,0.02,'Name','Motorized Camera','TimeUnit','s');
Orders = [ones(2,6),ones(2,6),ones(2,6)];
InputNL = saturation;
OutputNL = [deadzone,wavenet];
sys = nlhw(z,Orders,InputNL,OutputNL);
To see the shape of the estimated input and output nonlinearities, plot the nonlinearities.
plot(sys)
1-1466
                                                                                                 wavenet
Click on the input and output nonlinearity blocks on the top of the plot to see the nonlinearities.
Input Arguments
Name-Value Pair Arguments
Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and
Value is the corresponding value. Name must appear inside quotes. You can specify several name and
value pair arguments in any order as Name1,Value1,...,NameN,ValueN.
                                                                                                 1-1467
1   Functions
          Use Name,Value arguments to specify additional properties on page 1-550 of wavenet nonlinearity.
          For example, NL= wavenet('NumberofUnits',5) creates a wavelet nonlinearity estimator object
          with five nonlinearity units in wavelet expansion.
          Properties
          NumberofUnits
          Number of nonlinearity units in wavelet expansion, specified as a positive integer or one of the
          following values:
          • 'Auto' — The number of units are automatically determined from estimation data.
          • 'Interactive' — The number of units are determined during model estimation.
Default: 'Auto'
LinearTerm
Default: 'on'
Parameters
1-1468
                                                                                                   wavenet
The parameters are typically not assigned directly. They are estimated by the identification algorithm
(nlarx or nlhw) when wavenet is used in a Nonlinear ARX (idnlarx) or Hammerstein-Wiener
(idnlhw) model.
Options
Options specifying the initial wavelet nonlinearity structure, specified as a structure with the
following fields:
Output Arguments
NL — Wavelet nonlinearity estimator object
wavenet object
Algorithms
wavenet can be used in both Nonlinear ARX and Hammerstein-Wiener models.
   • If the Focus estimation option (see, nlarxOptions) is 'prediction', wavenet uses a fast,
     noniterative technique for estimating parameters [1]. Successive refinements after the first
     estimation use an iterative algorithm.
   • If Focus is 'simulation', wavenet uses an iterative technique for estimating parameters.
                                                                                                   1-1469
1   Functions
          References
          [1] Zhang, Q. “Using wavelet network in nonparametric estimation.” IEEE Trans. on Neural
                  Networks, Vol. 8, Number 2, March 1997, pp. 227-236.
          See Also
          nlarx | nlhw
Introduced in R2007a
1-1470
                                                                                              xperm
xperm
Reorder states in state-space models
Syntax
sys = xperm(sys,P)
Description
sys = xperm(sys,P) reorders the states of the state-space model sys according to the
permutation P. The vector P is a permutation of 1:NX, where NX is the number of states in sys. For
information about creating state-space models, see ss and dss.
Examples
Load a previously saved state space model ssF8 with four states.
load ltiexamples
ssF8
ssF8 =
  A =
                   PitchRate       Velocity         AOA    PitchAngle
   PitchRate            -0.7        -0.0458       -12.2             0
   Velocity                0         -0.014     -0.2904        -0.562
   AOA                     1        -0.0057        -1.4             0
   PitchAngle              1              0           0             0
  B =
                  Elevator    Flaperon
   PitchRate         -19.1        -3.1
   Velocity        -0.0119     -0.0096
   AOA               -0.14       -0.72
   PitchAngle            0           0
  C =
                     PitchRate       Velocity          AOA   PitchAngle
   FlightPath                0              0           -1            1
   Acceleration              0              0        0.733            0
  D =
                    Elevator     Flaperon
   FlightPath              0            0
   Acceleration       0.0768       0.1134
                                                                                            1-1471
1   Functions
          [y,P] = sort(ssF8.StateName);
          sys = xperm(ssF8,P)
sys =
                A =
                                    AOA    PitchAngle     PitchRate     Velocity
                 AOA               -1.4             0             1      -0.0057
                 PitchAngle           0             0             1            0
                 PitchRate        -12.2             0          -0.7      -0.0458
                 Velocity       -0.2904        -0.562             0       -0.014
                B =
                              Elevator   Flaperon
                 AOA             -0.14      -0.72
                 PitchAngle          0          0
                 PitchRate       -19.1       -3.1
                 Velocity      -0.0119    -0.0096
                C =
                                       AOA   PitchAngle     PitchRate     Velocity
                 FlightPath             -1            1             0            0
                 Acceleration        0.733            0             0            0
                D =
                                Elevator   Flaperon
                 FlightPath            0          0
                 Acceleration     0.0768     0.1134
          See Also
          dss | ss
Introduced in R2008b
1-1472
                                                                                              zero
zero
Zeros and gain of SISO dynamic system
Syntax
Z = zero(sys)
[Z,gain] = zero(sys)
[Z,gain] = zero(sys,J1,...,JN)
Description
Z = zero(sys) returns the zeros of the single-input, single-output (SISO) dynamic system model,
sys. The output is expressed as the reciprocal of the time units specified in sys.TimeUnit.
[Z,gain] = zero(sys,J1,...,JN) returns the zeros and gain of the entries in the model array
sys with subscripts J1,...,JN.
Examples
sys = tf([4.2,0.25,-0.004],[1,9.6,17]);
Z = zero(sys)
Z = 2×1
   -0.0726
    0.0131
Calculate the zero locations and zero-pole gain of the following transfer function:
sys = tf([4.2,0.25,-0.004],[1,9.6,17]);
[z,gain] = zero(sys)
                                                                                          1-1473
1   Functions
z = 2×1
                -0.0726
                 0.0131
gain = 4.2000
                                                     −1
          The zero locations are expressed in second    , because the time unit of the transfer function
          (H.TimeUnit) is seconds.
          load('tfArray.mat','sys');
          size(sys)
Find the zeros and gain values of the models in the array.
ans = 2×1
                -0.0726
                 0.0131
gain(:,:,1,1)
ans = 4.2000
          zero returns an array each for the zeros and the gain values respectively. Here, Z(:,:,1,1) and
          gain(:,:,1,1) corresponds to the zero and the gain value of the first model in the array, that is,
          sys(:,:,1,1).
          Input Arguments
          sys — Dynamic system
          dynamic system model | model array
          Dynamic system, specified as a SISO dynamic system model, or an array of SISO dynamic system
          models. Dynamic systems that you can use include continuous-time or discrete-time numeric LTI
          models such as tf, zpk, or ss models.
          If sys is a generalized state-space model genss or an uncertain state-space model uss, zero returns
          the zeros of the current or nominal value of sys. If sys is an array of models, zero returns the zeros
          of the model corresponding to its subscript J1,...,JN in sys. For more information on model
          arrays, see “Model Arrays” (Control System Toolbox).
1-1474
                                                                                                     zero
Indices of models in array whose zeros you want to extract, specified as a positive integer. You can
provide as many indices as there are array dimensions in sys. For example, if sys is a 4-by-5 array of
dynamic system models, the following command extracts the zeros for entry (2,3) in the array.
Z = zero(sys,2,3);
Output Arguments
Z — Zeros of the dynamic system
column vector | array
Zeros of the dynamic system, returned as a column vector or an array. If sys is:
• A single model, then Z is a column vector of zeros of the dynamic system model sys
• A model array, then Z is an array containing the zeros of each model in sys
Z is expressed as the reciprocal of the time units specified in sys.TimeUnit. For example, zero is
expressed in 1/minute if sys.TimeUnit = 'minutes'.
Zero-pole-gain of the dynamic system, returned as a scalar. In other words, gain is the value of K
when the model is written in zpk form.
Tips
• If sys has internal delays, zero sets all internal delays to zero, creating a zero-order Padé
  approximation. This approximation ensures that the system has a finite number of zeros. zero
  returns an error if setting internal delays to zero creates singular algebraic loops. To assess the
  stability of models with internal delays, use step or impulse.
• To calculate the transmission zeros of a multi-input, multi-output (MIMO) system, use tzero.
See Also
impulse | pole | pzmap | pzplot | step | tzero
Topics
“Pole and Zero Locations” (Control System Toolbox)
Introduced in R2012a
                                                                                                1-1475
1   Functions
          zgrid
          Generate z-plane grid of constant damping factors and natural frequencies
          Syntax
          zgrid
          zgrid(T)
          zgrid(zeta,wn)
          zgrid(zeta,wn,T)
          Description
          zgrid generates a grid of constant damping factors from 0 to 1 in steps of 0.1 and natural
          frequencies from 0 to π/T in steps of 0.1*π/T for root locus and pole-zero maps. The default steps of
          0.1*π/T represent fractions of the Nyquist frequencies. zgrid then plots the grid over the current
          axis. zgrid creates the grid over the plot without altering the current axis limits if the current axis
          contains a discrete z-plane root locus diagram or pole-zero map. Use this syntax to plot multiple
          systems with different sample times.
          Alternatively, you can select Grid from the context menu in the plot window to generate the same z-
          plane grid.
          zgrid(T) generates the z-plane grid by using default values for damping factor and natural
          frequency relative to the sample time T.
          zgrid(zeta,wn) plots a grid of constant damping factor and natural frequency lines for the
          damping factors and normalized natural frequencies in the vectors zeta and wn, respectively. When
          the sample time is not specified, the frequency values in wn are interpreted as normalized values, that
          is, wn/T.
          zgrid(zeta,wn,T) plots a grid of constant damping factor and natural frequency lines for the
          damping factors and natural frequencies in the vectors zeta and wn, relative to sample time T. zeta
          lines are independent for T but the wn lines depend on the sample time value. Use this syntax to
          create the z-plane grid with specific values of wn.
zgrid( ___ ,'new') clears the current axes first and sets hold on.
          zgrid(AX, ___ ) plots the z-plane grid on the Axes or UIAxes object in the current figure with the
          handle AX. Use this syntax when creating apps with zgrid in the App Designer.
Examples
1-1476
                                                                                                 zgrid
H =
rlocus(H)
zgrid
axis equal
For this example, consider a discrete-time transfer function sys with a sample time of 0.1s. Now plot
the pole-zero map of sys and visualize the default z-plane grid without specifying the sample time.
sys = tf([2 -3.4 1.5],[1 -1.6 0.8],0.1);
Ts = 0.1;
figure()
pzmap(sys)
zgrid()
axis equal
                                                                                              1-1477
1   Functions
                                                                                    π
          Observe that the frequencies on the z-plane grid are normalized in terms of f
                                                                                      . To obtain the true
                                                                                    T
          frequency values on the grid, specify the sample time with the zgrid command.
          figure()
          pzmap(sys)
          zgrid(Ts)
          axis equal
1-1478
                                                                                                  zgrid
Now, observe that the frequency values on the plot are true values, that is, they are non-normalized.
Input Arguments
zeta — Damping ratio
vector
Natural frequency values, specified as a vector. Natural frequencies are plotted as true values when T
is specified. When the sample time is not specified, zgrid normalizes the values as wn/T.
T — Sample time
positive scalar | -1
• A positive scalar representing the sampling period of a discrete-time system. The actual frequency
  values are displayed on the frequency grid.
• -1 for a discrete-time system with an unspecified sample time. The frequency values are displayed
  as normalized values f*π/T for the default grid.
                                                                                               1-1479
1   Functions
          zeta lines are independent of T while wn lines are dependent on the sample time. You must specify T
          to plot specific values of wn. When the sample time T is not specified, the required wn values are
          interpreted as normalized values, that is, wn/T.
          AX — Object handle
          Axes object | UIAxes object
          Object handle, specified as an Axes or UIAxes object. Use AX to create apps with zgrid in the App
          Designer.
          See Also
          pzmap | rlocus | sgrid
1-1480
                                                                                                 zpkdata
zpkdata
Access zero-pole-gain data
Syntax
[z,p,k] = zpkdata(sys)
[z,p,k,Ts] = zpkdata(sys)
[z,p,k,Ts,covz,covp,covk] = zpkdata(sys)
Description
[z,p,k] = zpkdata(sys) returns the zeros z, poles p, and gain(s) k of the zero-pole-gain model
sys. The outputs z and p are cell arrays with the following characteristics:
The output k is a matrix with as many rows as outputs and as many columns as inputs such that
k(i,j) is the gain of the transfer function from input j to output i. If sys is a transfer function or
state-space model, it is first converted to zero-pole-gain form using zpk.
[z,p,k] = zpkdata(sys,'v')
forces zpkdata to return the zeros and poles directly as column vectors rather than as cell arrays
(see example below).
You can access the remaining LTI properties of sys with get or by direct referencing, for example,
sys.Ts
sys.inputname
Examples
Example 1
                                                                                                 1-1481
1   Functions
          H = zpk({[0];[-0.5]},{[0.3];[0.1+i 0.1-i]},[1;2],-1)
          Zero/pole/gain from input to output...
                   z
           #1: -------
                (z-0.3)
                       2 (z+0.5)
            #2:   -------------------
                  (z^2 - 0.2z + 1.01)
          [z,p,k] = zpkdata(H)
          z =
              [      0]
              [-0.5000]
          p =
              [    0.3000]
              [2x1 double]
          k =
               1
               2
          To access the zeros and poles of the second output channel of H, get the content of the second cell in
          z and p by typing
          z{2,1}
          ans =
             -0.5000
          p{2,1}
          ans =
             0.1000+ 1.0000i
             0.1000- 1.0000i
Example 2
          Extract the ZPK matrices and their standard deviations for a 2-input, 1 output identified transfer
          function.
load iddata7
          h = iopzplot(sys1, sys2);
          showConfidence(h)
1-1482
                              zpkdata
See Also
get | ssdata | tfdata | zpk
                              1-1483
         2
Blocks
2     Blocks
               Description
               The Extended Kalman Filter block estimates the states of a discrete-time nonlinear system using the
               first-order discrete-time extended Kalman filter algorithm.
               Consider a plant with states x, input u, output y, process noise w, and measurement noise v. Assume
               that you can represent the plant as a nonlinear system.
               Using the state transition and measurement functions of the system and the extended Kalman filter
               algorithm, the block produces state estimates x for the current time step. For information about the
               algorithm, see “Extended and Unscented Kalman Filter Algorithms for Online State Estimation”.
               You create the nonlinear state transition function and measurement functions for the system and
               specify these functions in the block. The block supports state estimation of a system with multiple
               sensors that are operating at different sampling rates. You can specify up to five measurement
               functions, each corresponding to a sensor in the system. You can also specify the Jacobians of the
               state transition and measurement functions. If you do not specify them, the software numerically
               computes the Jacobians. For more information, see “State Transition and Measurement Functions” on
               page 2-14.
               Ports
               Input
               Measured system outputs corresponding to each measurement function that you specify in the block.
               The number of ports equals the number of measurement functions in your system. You can specify up
               to five measurement functions. For example, if your system has two sensors, you specify two
               measurement functions in the block. The first port y1 is available by default. When you click Apply,
               the software generates port y2 corresponding to the second measurement function.
2-2
                                                                                    Extended Kalman Filter
Specify the ports as N-dimensional vectors, where N is the number of quantities measured by the
corresponding sensor. For example, if your system has one sensor that measures the position and
velocity of an object, then there is only one port y1. The port is specified as a 2-dimensional vector
with values corresponding to position and velocity.
Dependencies
The first port y1 is available by default. Ports y2 to y5 are generated when you click Add
Measurement, and click Apply.
Data Types: single | double
Additional optional input argument to the state transition function f other than the state x and
process noise w. For information about state transition functions see, “State Transition and
Measurement Functions” on page 2-14.
Suppose that your system has nonadditive process noise, and the state transition function f has the
following form:
x(k+1) = f(x(k),w(k),StateTransitionFcnInputs)
Here k is the time step, and StateTransitionFcnInputs is an additional input argument other
than x and w.
If you create f using a MATLAB function (.m file), the software generates the port
StateTransitionFcnInputs when you click Apply. You can specify the inputs to this port as a scalar,
vector, or matrix.
If your state transition function has more than one additional input, use a Simulink Function block to
specify the function. When you use a Simulink Function block, you provide the additional inputs
directly to the Simulink Function block using Inport blocks. No input ports are generated for the
additional inputs in the Extended Kalman Filter block.
Dependencies
This port is generated only if both of the following conditions are satisfied:
• You specify f in Function using a MATLAB function, and f is on the MATLAB path.
• f requires only one additional input argument apart from x and w.
MeasurementFcn1Inputs,MeasurementFcn2Inputs,MeasurementFcn3Inputs,Measurement
Fcn4Inputs,MeasurementFcn5Inputs — Additional optional input argument to each
measurement function
scalar | vector | matrix
Additional optional inputs to the measurement functions other than the state x and measurement
noise v. For information about measurement functions see, “State Transition and Measurement
Functions” on page 2-14.
                                                                                                         2-3
2     Blocks
               MeasurementFcn1Inputs corresponds to the first measurement function that you specify, and so
               on. For example, suppose that your system has three sensors and nonadditive measurement noise,
               and the three measurement functions h1, h2, and h3 have the following form:
y1[k] = h1(x[k],v1[k],MeasurementFcn1Inputs)
y2[k] = h2(x[k],v2[k],MeasurementFcn2Inputs)
y3[k] = h3(x[k],v3[k])
               Here k is the time step, and MeasurementFcn1Inputs and MeasurementFcn2Inputs are the
               additional input arguments to h1 and h2.
               If you specify h1, h2, and h3 using MATLAB functions (.m files) in Function, the software generates
               ports MeasurementFcn1Inputs and MeasurementFcn2Inputs when you click Apply. You can
               specify the inputs to these ports as scalars, vectors, or matrices.
               If your measurement functions have more than one additional input, use Simulink Function blocks to
               specify the functions. When you use a Simulink Function block, you provide the additional inputs
               directly to the Simulink Function block using Inport blocks. No input ports are generated for the
               additional inputs in the Extended Kalman Filter block.
               Dependencies
               • You specify h in Function using a MATLAB function, and h is on the MATLAB path.
               • h requires only one additional input argument apart from x and v.
               Time-varying process noise covariance, specified as a scalar, vector, or matrix depending on the value
               of the Process noise parameter:
               • Process noise is Additive — Specify the covariance as a scalar, an Ns-element vector, or an Ns-
                 by-Ns matrix, where Ns is the number of states of the system. Specify a scalar if there is no cross-
                 correlation between process noise terms, and all the terms have the same variance. Specify a
                 vector of length Ns, if there is no cross-correlation between process noise terms, but all the terms
                 have different variances.
               • Process noise is Nonadditive — Specify the covariance as a W-by-W matrix, where W is the
                 number of process noise terms in the state transition function.
Dependencies
               This port is generated if you specify the process noise covariance as Time-Varying. The port appears
               when you click Apply.
               Data Types: single | double
2-4
                                                                                    Extended Kalman Filter
Time-varying measurement noise covariances for up to five measurement functions of the system,
specified as matrices. The sizes of the matrices depend on the value of the Measurement noise
parameter for the corresponding measurement function:
• Measurement noise is Additive — Specify the covariance as an N-by-N matrix, where N is the
  number of measurements of the system.
• Measurement noise is Nonadditive — Specify the covariance as a V-by-V matrix, where V is
  the number of measurement noise terms in the corresponding measurement function.
Dependencies
A port is generated if you specify the measurement noise covariance as Time-Varying for the
corresponding measurement function. The port appears when you click Apply.
Data Types: single | double
Suppose that measured output data is not available at all time points at the port y1 that corresponds
to the first measurement function. Use a signal value other than 0 at the Enable1 port to enable the
correction of estimated states when measured data is available. Specify the port value as 0 when
measured data is not available. Similarly, if measured output data is not available at all time points at
the port yi for the ith measurement function, specify the corresponding port Enablei as a value other
than 0.
Dependencies
A port corresponding to a measurement function is generated if you select Add Enable port for that
measurement function. The port appears when you click Apply.
Data Types: single | double | Boolean
Output
Estimated states, returned as a vector of size Ns, where Ns is the number of states of the system. To
access the individual states, use the Selector block.
When the Use the current measurements to improve state estimates parameter is selected, the
block outputs the corrected state estimate x [k k] at time step k, estimated using measured outputs
until time k. If you clear this parameter, the block returns the predicted state estimate x [k k − 1] for
time k, estimated using measured output until a previous time k-1. Clear this parameter if your filter
is in a feedback loop and there is an algebraic loop in your Simulink model.
Data Types: single | double
State estimation error covariance, returned as an Ns-by-Ns matrix, where Ns is the number of states
of the system. To access the individual covariances, use the Selector block.
                                                                                                      2-5
2     Blocks
Dependencies
               This port is generated if you select Output state estimation error covariance in the System
               Model tab, and click Apply.
               Data Types: single | double
               Parameters
               System Model Tab
State Transition
               The state transition function calculates the Ns-element state vector of the system at time step k+1,
               given the state vector at time step k. Ns is the number of states of the nonlinear system. You create
               the state transition function and specify the function name in Function. For example, if
               vdpStateFcn.m is the state transition function that you created and saved, specify Function as
               vdpStateFcn.
               The inputs to the function you create depend on whether you specify the process noise as additive or
               nonadditive in Process noise.
               • Process noise is Additive — The state transition function f specifies how the states evolve as a
                 function of state values at previous time step:
x(k+1) = f(x(k),Us1(k),...,Usn(k)),
                  where x(k) is the estimated state at time k, and Us1,...,Usn are any additional input
                  arguments required by your state transition function, such as system inputs or the sample time. To
                  see an example of a state transition function with additive process noise, type edit
                  vdpStateFcn at the command line.
               • Process noise is Nonadditive — The state transition function also specifies how the states
                 evolve as a function of the process noise w:
x(k+1) = f(x(k),w(k),Us1(k),...,Usn(k)).
For more information, see “State Transition and Measurement Functions” on page 2-14.
You can create f using a Simulink Function block or as a MATLAB function (.m file).
               • You can use a MATLAB function only if f has one additional input argument Us1 other than x and
                 w.
x(k+1) = f(x(k),w(k),Us1(k))
2-6
                                                                                    Extended Kalman Filter
Programmatic Use
Block Parameter: StateTransitionFcn
Type: character vector, string
Default: 'myStateTransitionFcn'
• off — The software computes the Jacobian numerically. This computation may increase
  processing time and numerical inaccuracy of the state estimation.
• on — You create a function to compute the Jacobian, and specify the name of the function in
  Jacobian. For example, if vdpStateJacobianFcn.m is the Jacobian function, specify Jacobian
  as vdpStateJacobianFcn. If you create the state transition function f using a Simulink Function
  block, then create the Jacobian using a Simulink Function block. If you create f using a MATLAB
  function (.m file), then create the Jacobian using a MATLAB function.
   The function calculates the partial derivatives of the state transition function with respect to the
   states and process noise. The number of inputs to the Jacobian function must equal the number of
   inputs of the state transition function and must be specified in the same order in both functions.
   The number of outputs of the Jacobian function depends on the Process noise parameter:
   • Process noise is Additive — The function calculates the partial derivative of the state
     transition function f with respect to the states (∂ f / ∂x). The output is an Ns-by-Ns Jacobian
     matrix, where Ns is the number of states.
      To see an example of a Jacobian function for additive process noise, type edit
      vdpStateJacobianFcn at the command line.
   • Process noise is Nonadditive — The function must also return a second output that is the
     partial derivative of the state transition function f with respect to the process noise terms
     (∂ f / ∂w). The second output is returned as an Ns-by-W matrix, where W is the number of
     process noise terms in the state transition function.
Programmatic Use
Block Parameter: HasStateTransitionJacobianFcn
Type: character vector
Values: 'off','on'
Default: 'off'
Block Parameter: StateTransitionJacobianFcn
Type: character vector, string
Default: ''
• Additive — Process noise w is additive, and the state transition function f that you specify in
  Function has the following form:
x(k+1) = f(x(k),Us1(k),...,Usn(k)),
   where x(k) is the estimated state at time k, and Us1,...,Usn are any additional input
   arguments required by your state transition function.
                                                                                                       2-7
2     Blocks
               • Nonadditive — Process noise is nonadditive, and the state transition function specifies how the
                 states evolve as a function of the state and process noise at the previous time step:
x(k+1) = f(x(k),w(k),Us1(k),...,Usn(k)).
               Programmatic Use
               Block Parameter: HasAdditiveProcessNoise
               Type: character vector
               Values: 'Additive', 'Nonadditive'
               Default: 'Additive'
               Time-invariant process noise covariance, specified as a scalar, vector, or matrix depending on the
               value of the Process noise parameter:
               • Process noise is Additive — Specify the covariance as a scalar, an Ns-element vector, or an Ns-
                 by-Ns matrix, where Ns is the number of states of the system. Specify a scalar if there is no cross-
                 correlation between process noise terms and all the terms have the same variance. Specify a
                 vector of length Ns, if there is no cross-correlation between process noise terms but all the terms
                 have different variances.
               • Process noise is Nonadditive — Specify the covariance as a W-by-W matrix, where W is the
                 number of process noise terms.
               If the process noise covariance is time-varying, select Time-varying. The block generates input port
               Q to specify the time-varying covariance.
               Dependencies
               This parameter is enabled if you do not specify the process noise as Time-Varying.
               Programmatic Use
               Block Parameter: ProcessNoise
               Type: character vector, string
               Default: '1'
               If you select this parameter, the block includes an additional input port Q to specify the time-varying
               process noise covariance.
               Programmatic Use
               Block Parameter: HasTimeVaryingProcessNoise
               Type: character vector
               Values: 'off', 'on'
               Default: 'off'
Initialization
               Initial state estimate value, specified as an Ns-element vector, where Ns is the number of states in the
               system. Specify the initial state values based on your knowledge of the system.
2-8
                                                                                   Extended Kalman Filter
Programmatic Use
Block Parameter: InitialState
Type: character vector, string
Default: '0'
State estimation error covariance, specified as a scalar, an Ns-element vector, or an Ns-by-Ns matrix,
where Ns is the number of states of the system. If you specify a scalar or vector, the software creates
an Ns-by-Ns diagonal matrix with the scalar or vector elements on the diagonal.
Specify a high value for the covariance when you do not have confidence in the initial state values
that you specify in Initial state.
Programmatic Use
Block Parameter: InitialStateCovariance
Type: character vector, string
Default: '1'
Measurement
The measurement function calculates the N-element output measurement vector of the nonlinear
system at time step k, given the state vector at time step k. You create the measurement function and
specify the function name in Function. For example, if vdpMeasurementFcn.m is the measurement
function that you created and saved, specify Function as vdpMeasurementFcn.
The inputs to the function you create depend on whether you specify the measurement noise as
additive or nonadditive in Measurement noise.
y(k) = h(x(k),Um1(k),...,Umn(k)),
   where y(k) and x(k) are the estimated output and estimated state at time k, and Um1,...,Umn
   are any optional input arguments required by your measurement function. For example, if you are
   using a sensor for tracking an object, an additional input could be the sensor position.
   To see an example of a measurement function with additive process noise, type edit
   vdpMeasurementFcn at the command line.
• Measurement noise is Nonadditive— The measurement function also specifies how the output
  measurement evolves as a function of the measurement noise v:
y(k) = h(x(k),v(k),Um1(k),...,Umn(k)).
   To see an example of a measurement function with nonadditive process noise, type edit
   vdpMeasurementNonAdditiveNoiseFcn.
For more information, see “State Transition and Measurement Functions” on page 2-14.
You can create h using a Simulink Function block or as a MATLAB function (.m file).
                                                                                                      2-9
2   Blocks
             • You can use a MATLAB function only if h has one additional input argument Um1 other than x and
               v.
y[k] = h(x[k],v[k],Um1(k))
             If you have multiple sensors in your system, you can specify multiple measurement functions. You can
             specify up to five measurement functions using the Add Measurement button. To remove
             measurement functions, use Remove Measurement.
             Programmatic Use
             Block Parameter: MeasurementFcn1, MeasurementFcn2, MeasurementFcn3,
             MeasurementFcn4, MeasurementFcn5
             Type: character vector, string
             Default: 'myMeasurementFcn'
             • off — The software computes the Jacobian numerically. This computation may increase
               processing time and numerical inaccuracy of the state estimation.
             • on — You create a function to compute the Jacobian of the measurement function h, and specify
               the name of the function in Jacobian. For example, if vdpMeasurementJacobianFcn.m is the
               Jacobian function, specify MeasurementJacobianFcn as vdpMeasurementJacobianFcn. If you
               create h using a Simulink Function block, then create the Jacobian using a Simulink Function
               block. If you create h using a MATLAB function (.m file), then create the Jacobian using a MATLAB
               function.
                The function calculates the partial derivatives of the measurement function h with respect to the
                states and measurement noise. The number of inputs to the Jacobian function must equal the
                number of inputs to the measurement function and must be specified in the same order in both
                functions. The number of outputs of the Jacobian function depends on the Measurement noise
                parameter:
                • Measurement noise is Additive — The function calculates the partial derivatives of the
                  measurement function with respect to the states (∂h/ ∂x). The output is as an N-by-Ns Jacobian
                  matrix, where N is the number of measurements of the system and Ns is the number of states.
                   To see an example of a Jacobian function for additive measurement noise, type edit
                   vdpMeasurementJacobianFcn at the command line.
                • Measurement noise is Nonadditive — The function also returns a second output that is the
                  partial derivative of the measurement function with respect to the measurement noise terms
                  (∂h/ ∂v). The second output is returned as an N-by-V Jacobian matrix, where V is the number of
                  measurement noise terms.
2-10
                                                                                  Extended Kalman Filter
Programmatic Use
Block Parameter: HasMeasurementJacobianFcn1, HasMeasurementJacobianFcn2,
HasMeasurementJacobianFcn3,
HasMeasurementJacobianFcn4,HasMeasurementJacobianFcn5
Type: character vector
Values: 'off','on'
Default: 'off'
Block Parameter: MeasurementJacobianFcn1, MeasurementJacobianFcn2,
MeasurementJacobianFcn3, MeasurementJacobianFcn4, MeasurementJacobianFcn5
Type: character vector
Default: ''
• Additive — Measurement noise v is additive, and the measurement function h that you specify
  in Function has the following form:
y(k) = h(x(k),Um1(k),...,Umn(k)),
   where y(k) and x(k) are the estimated output and estimated state at time k, and Um1,...,Umn
   are any optional input arguments required by your measurement function.
• Nonadditive — Measurement noise is nonadditive, and the measurement function specifies how
  the output measurement evolves as a function of the state and measurement noise:
y(k) = h(x(k),v(k),Um1(k),...,Umn(k)).
Programmatic Use
Block Parameter: HasAdditiveMeasurementNoise1, HasAdditiveMeasurementNoise2,
HasAdditiveMeasurementNoise3, HasAdditiveMeasurementNoise4,
HasAdditiveMeasurementNoise5
Type: character vector
Values: 'Additive', 'Nonadditive'
Default: 'Additive'
Time-invariant process noise covariance, specified as a scalar, vector, or matrix depending on the
value of the Process noise parameter:
• Process noise is Additive — Specify the covariance as a scalar, an Ns-element vector, or an Ns-
  by-Ns matrix, where Ns is the number of states of the system. Specify a scalar if there is no cross-
  correlation between process noise terms and all the terms have the same variance. Specify a
  vector of length Ns, if there is no cross-correlation between process noise terms but all the terms
  have different variances.
• Process noise is Nonadditive — Specify the covariance as a W-by-W matrix, where W is the
  number of process noise terms.
If the process noise covariance is time-varying, select Time-varying. The block generates input port
Q to specify the time-varying covariance.
                                                                                                     2-11
2   Blocks
Dependencies
             This parameter is enabled if you do not specify the process noise as Time-Varying.
             Programmatic Use
             Block Parameter: ProcessNoise
             Type: character vector, string
             Default: '1'
             If you select this parameter for the measurement noise covariance of the first measurement function,
             the block includes an additional input port R1. You specify the time-varying measurement noise
             covariance in R1. Similarly, if you select Time-varying for the ith measurement function, the block
             includes an additional input port Ri to specify the time-varying measurement noise covariance for
             that function.
             Programmatic Use
             Block Parameter: HasTimeVaryingMeasurementNoise1,
             HasTimeVaryingMeasurementNoise2, HasTimeVaryingMeasurementNoise3,
             HasTimeVaryingMeasurementNoise4, HasTimeVaryingMeasurementNoise5
             Type: character vector
             Values: 'off', 'on'
             Default: 'off'
             Add Enable Port — Enable correction of estimated states only when measured data is
             available
             off (default) | on
             Suppose that measured output data is not available at all time points at the port y1 that corresponds
             to the first measurement function. Select Add Enable port to generate an input port Enable1. Use a
             signal at this port to enable the correction of estimated states only when measured data is available.
             Similarly, if measured output data is not available at all time points at the port yi for the ith
             measurement function, select the corresponding Add Enable port.
             Programmatic Use
             Block Parameter: HasMeasurementEnablePort1, HasMeasurementEnablePort2,
             HasMeasurementEnablePort3, HasMeasurementEnablePort4, HasMeasurementEnablePort5
             Type: character vector
             Values: 'off', 'on'
             Default: 'off'
Settings
             When this parameter is selected, the block outputs the corrected state estimate x [k k] at time step k,
             estimated using measured outputs until time k. If you clear this parameter, the block returns the
             predicted state estimate x [k k − 1] for time k, estimated using measured output until a previous time
             k-1. Clear this parameter if your filter is in a feedback loop and there is an algebraic loop in your
             Simulink model.
2-12
                                                                                   Extended Kalman Filter
Programmatic Use
Block Parameter: UseCurrentEstimator
Type: character vector
Values: 'off', 'on'
Default: 'on'
Output state estimation error covariance — Output state estimation error covariance
off (default) | on
If you select this parameter, a state estimation error covariance output port P is generated in the
block.
Programmatic Use
Block Parameter: OutputStateCovariance
Type: character vector
Values: 'off','on'
Default: 'off'
Use this parameter to specify the data type for all block parameters.
Programmatic Use
Block Parameter: DataType
Type: character vector
Values: 'single', 'double'
Default: 'double'
Block sample time, specified as a positive scalar. If the sample times of your state transition and
measurement functions are different, select Enable multirate operation in the Multirate tab, and
specify the sample times in the Multirate tab instead.
Dependencies
This parameter is available if in the Multirate tab, the Enable multirate operation parameter is
off.
Programmatic Use
Block Parameter: SampleTime
Type: character vector, string
Default: '1'
Multirate Tab
Enable multirate operation — Enable specification of different sample times for state
transition and measurement functions
off (default) | on
Select this parameter if the sample times of the state transition and measurement functions are
different. You specify the sample times in the Multirate tab, in Sample time.
                                                                                                      2-13
2   Blocks
             Programmatic Use
             Block Parameter: EnableMultirate
             Type: character vector
             Values: 'off', 'on'
             Default: 'off'
             If the sample times for state transition and measurement functions are different, specify Sample
             time. Specify the sample times for the measurement functions as positive integer multiples of the
             state transition sample time. The sample times you specify correspond to the following input ports:
             • Ports corresponding to state transition function — Additional input to state transition function
               StateTransitionFcnInputs and time-varying process noise covariance Q. The sample times of
               these ports must always equal the state transition function sample time, but can differ from the
               sample time of the measurement functions.
             • Ports corresponding to ith measurement function — Measured output yi, additional input to
               measurement function MeasurementFcniInputs, enable signal at port Enablei, and time-
               varying measurement noise covariance Ri. The sample times of these ports for the same
               measurement function must always be the same, but can differ from the sample time for the state
               transition function and other measurement functions.
Dependencies
             This parameter is available if in the Multirate tab, the Enable multirate operation parameter is
             on.
             Programmatic Use
             Block Parameter: StateTransitionFcnSampleTime, MeasurementFcn1SampleTime1,
             MeasurementFcn1SampleTime2, MeasurementFcn1SampleTime3,
             MeasurementFcn1SampleTime4, MeasurementFcn1SampleTime5
             Type: character vector, string
             Default: '1'
             More About
             State Transition and Measurement Functions
             The algorithm computes the state estimates x of the nonlinear system using state transition and
             measurement functions specified by you. You can specify up to five measurement functions, each
             corresponding to a sensor in the system. The software lets you specify the noise in these functions as
             additive or nonadditive.
             • Additive Noise Terms — The state transition and measurements equations have the following
               form:
                Here f is a nonlinear state transition function that describes the evolution of states x from one
                time step to the next. The nonlinear measurement function h relates x to the measurements y at
                time step k. w and v are the zero-mean, uncorrelated process and measurement noises,
2-14
                                                                                   Extended Kalman Filter
   respectively. These functions can also have additional optional input arguments that are denoted
   by us and um in the equations. For example, the additional arguments could be time step k or the
   inputs u to the nonlinear system. There can be multiple such arguments.
   Note that the noise terms in both equations are additive. That is, x(k+1) is linearly related to the
   process noise w(k), and y(k) is linearly related to the measurement noise v(k). For additive
   noise terms, you do not need to specify the noise terms in the state transition and measurement
   functions. The software adds the terms to the output of the functions.
• Nonadditive Noise Terms — The software also supports more complex state transition and
  measurement functions where the state x[k] and measurement y[k] are nonlinear functions of the
  process noise and measurement noise, respectively. When the noise terms are nonadditive, the
  state transition and measurements equation have the following form:
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using Simulink® Coder™.
The state transition, measurement, and Jacobian functions that you specify must use only the
MATLAB commands and Simulink blocks that support code generation. For a list of blocks that
support code generation, see “Simulink Built-In Blocks That Support Code Generation” (Simulink
Coder). For a list of commands that support code generation, see “Functions and Objects Supported
for C/C++ Code Generation” (MATLAB Coder).
See Also
Blocks
Kalman Filter | Particle Filter | Unscented Kalman Filter
Functions
extendedKalmanFilter | particleFilter | unscentedKalmanFilter
Topics
“What Is Online Estimation?”
“Extended and Unscented Kalman Filter Algorithms for Online State Estimation”
“Validate Online State Estimation in Simulink”
“Troubleshoot Online State Estimation”
Introduced in R2017a
                                                                                                   2-15
2   Blocks
             Iddata Sink
             Export simulation data as iddata object to MATLAB workspace
             Library:            System Identification Toolbox
             Description
             The Iddata Sink block exports simulation data as an iddata object to the MATLAB workspace. The
             object stores the input and simulated output signals, sampled at the sample time that you specify. If
             you simulate your model from the model window, the block exports the object to the MATLAB base
             workspace. If you simulate the model programmatically, the object is exported to the MATLAB caller
             workspace. The caller workspace is the workspace of the function that called the currently running
             function.
             Ports
             Input
             Input of iddata object, specified as a scalar for single-input data. For multichannel data with Nu
             inputs, specify Input as a vector of length Nu.
             Data Types: double
             Output of iddata object, specified as a scalar for single-output data. For multichannel data with Ny
             outputs, specify Output as a vector of length Ny.
             Data Types: double
             Parameters
             IDDATA Name — Name of iddata object
             data (default) | variable name
             Name of iddata object, specified as a MATLAB variable name. The object is exported with this name
             to the MATLAB workspace.
             Sample time in seconds, specified as a finite positive number. The iddata object stores the input and
             output signals, sampled at the sample time that you specify.
2-16
                                          Iddata Sink
See Also
Iddata Source
Topics
“Simulate Identified Model in Simulink”
Introduced in R2008a
                                               2-17
2   Blocks
             Iddata Source
             Import time-domain data stored in iddata object in MATLAB workspace
             Library:           System Identification Toolbox
             Description
             The Iddata Source block imports the input-output time-domain data stored in an iddata object in the
             MATLAB workspace. You can use this block to import data for simulating a model in Simulink.
             Ports
             Output
             Input data stored in iddata object, returned as a scalar for single-input data and a vector of length
             Nu for multichannel data with Nu inputs. If z is the iddata object, the output at this port at
             simulation time t is z.InputData at time t. If t is greater than z.SamplingInstants(end), the
             maximum time in z, the input data is returned as 0 for each input channel.
             Data Types: double
             Output data stored in iddata object, returned as a scalar for single-output data and as a vector of
             length Ny for multichannel data with Ny outputs. If z is the iddata object, the output at this port at
             simulation time t is z.OutputData at time t. If t is greater than z.SamplingInstants(end), the
             maximum time in z, the output data is returned as 0 for each output channel.
             Data Types: double
             Parameters
             IDDATA object — Time-domain data to be imported
             iddata(1,1) (default) | iddata object
             Time-domain data that is to be imported, specified as an iddata object that you have created in the
             MATLAB workspace. The iddata object must contain only one experiment. For a multiple-experiment
             iddata object z, to specify an iddata object for experiment number kexp, specify IDDATA object
             as getexp(z,kexp).
2-18
                                                  Iddata Source
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using Simulink® Coder™.
See Also
Iddata Sink
Topics
“Simulate Identified Model in Simulink”
Introduced in R2008a
                                                         2-19
2   Blocks
             Idmodel
             Simulate identified linear model in Simulink software
             Library:             System Identification Toolbox / Models
             Description
             The Idmodel block simulates the output of an identified linear model using time-domain input data.
             The model is a state-space (idss), linear grey-box (idgrey), polynomial (idpoly), transfer function
             (idtf), or process (idproc) model that you previously estimated or created. For the simulation of
             state-space and linear grey-box models, you can specify the initial state values. For other linear
             models, initial conditions are set to zero. You can also add noise to the simulated output.
             Ports
             Input
             Simulation input data, specified as a scalar for a single-input model. The data must be time-domain
             data. For multi-input models, specify the input as an Nu-element vector, where Nu is the number of
             inputs. For example, you can use a Vector Concatenate block to concatenate scalar signals into a
             vector signal.
Note Do not use a Bus Creator or Mux block to produce the vector signal.
Output
             Simulated output from linear model, returned as a scalar for a single-output model and an Ny-
             element vector for a model with Ny outputs.
             Data Types: double
             Parameters
             Identified model — Linear model to be simulated
             idss(-1,1,1,0,'Ts',1) (default) | idss object | idgrey object | idpoly object | idtf object |
             idproc object
2-20
                                                                                                  Idmodel
Linear model to be simulated, specified as an idss, idgrey, idpoly, idtf, or idproc object. The
model can be continuous-time or discrete-time, with or without input-output delays. You previously
estimate or construct the linear model in the MATLAB workspace.
Initial state values of state-space (idss) and linear grey-box (idgrey) models, specified as an Nx-
element vector, where Nx is the number of states of the model. To estimate the initial states that
provide a best fit between measured data and the simulated response of the model for the same
input, use the findstates command.
For example, to compute initial states such that the response of the model M matches the simulated
output data in the data set z, specify X0, such that:
X0 = findstates(M,z)
For linear models other than idss or idgrey, the block assumes that initial conditions are zero.
If you want to reproduce the simulation results that you get in the Model Output plot window in the
System Identification app, or from the compare command:
1   If the identified model m is not a state-space or grey-box model, convert the model into state-
    space form (idss model), and specify the state-space model mss in the block.
    mss = idss(m);
2   Compute the initial state values that produce the best fit between the model output and the
    measured output signal using findstates. Specify the prediction horizon as Inf, that is,
    minimize the simulation error.
    X0 = findstates(mss,z,Inf);
3   Use the model mss and initial states X0 in the Idmodel block to perform the simulation. Specify
    the same input signal z for simulation that you used as validation data in the app or compare.
When you select this parameter, the block derives the noise amplitude from the linear model property
model.NoiseVariance. The software filters random Gaussian white noise with the noise transfer
function of the model and adds the resulting noise to the simulated model response. If you want to
add the same noise every time you run the Simulink model, specify the Noise seed(s) property.
For continuous-time models, the ideal variance of the noise term is infinite. In reality, you see a band-
limited noise that accounts for the time constants of the system. You can interpret the resulting
simulated output as filtered using a lowpass filter with a passband that does not distort the dynamics
from the input.
The Noise seed(s) property seeds the random number generator such that the block adds the same
noise to the simulated output every time you run the Simulink model. For information about using
seeds, see rng.
                                                                                                      2-21
2   Blocks
             For multi-output models, you can use independent noise realizations that generate the outputs with
             additive noise. Enter a vector of Ny nonnegative integer entries, where Ny is the number of output
             channels.
             For random restarts that vary from one simulation to another, specify Noise seed(s) as [].
             Dependency
             Extended Capabilities
             C/C++ Code Generation
             Generate C and C++ code using Simulink® Coder™.
             See Also
             Functions
             findstates | idgrey | idpoly | idproc | idss | idtf | sim
             Blocks
             Iddata Sink | Iddata Source
             Topics
             “Simulate Identified Model in Simulink”
Introduced in R2008a
2-22
                                                                                   Nonlinear ARX Model
Description
The Nonlinear ARX Model block simulates the output of a nonlinear ARX model using time-domain
input data. The model is an idnlarx model that you previously estimated or constructed in the
MATLAB workspace. You specify initial conditions for the simulation as either steady-state input and
output signal levels or as an initial state vector.
Ports
Input
Simulation input data, specified as a scalar for a single-input model. The data must be time-domain
data. For multi-input models, specify the input as an Nu-element vector, where Nu is the number of
inputs. For example, you can use a Vector Concatenate block to concatenate scalar signals into a
vector signal.
Note Do not use a Bus Creator or Mux block to produce the vector signal.
Output
Simulated output from nonlinear ARX model, returned as a scalar for a single-output model and an
Ny-element vector for a model with Ny outputs.
Data Types: double
Parameters
Model — Nonlinear ARX model to be simulated
idnlarx object
Nonlinear ARX model to be simulated, specified as an idnlarx object. You previously estimate or
construct the idnlarx model in the MATLAB workspace.
                                                                                                 2-23
2   Blocks
             The states of a nonlinear ARX model correspond to the dynamic elements of the nonlinear ARX model
             structure. The dynamic elements are the model regressors. Regressors can be the delayed input or
             output variables (standard regressors) or user-defined transformations of delayed input-output
             variables (custom regressors). For more information about the states of a nonlinear ARX model, see
             the idnlarx reference page.
For simulating nonlinear ARX models, you can specify the initial conditions one of the following:
             • Input and output values — Specify steady-state input and output signal levels in Input
               level and Output level, respectively.
             • State values — Specify a vector of length equal to the number of states in the model in
               Specify initial states as a vector.
To enable this parameter, specify Initial conditions as Input and output values.
To enable this parameter, specify Initial conditions as Input and output values.
             Initial state values of the model, specified as an Nx-element vector, where Nx is the number of states
             of the model. This parameter is named Vector of state values until you specify Model.
If you do not know the initial states, you can estimate these states as follows:
             • To simulate the model around a given input level when you do not know the corresponding output
               level, estimate the equilibrium state values using the findop command. For example, to simulate
               a model M about a steady-state point where the input is 1 and the output is unknown, specify the
               initial state values as X0, where
                X0 = findop(M,'steady',1,NaN)
             • To estimate the initial states that provide a best fit between measured data and the simulated
               response of the model for the same input, use the findstates command. For example, to
               compute initial states such that the response of the model M matches the output data in the data
               set z, specify X0, such that:
                X0 = findstates(M,z,Inf)
             • To continue a simulation from a previous simulation run, use the simulated input-output values
               from the previous simulation to compute the initial states X0 for the current simulation. Use the
2-24
                                                                                   Nonlinear ARX Model
   data2state command to compute X0. For example, suppose that firstSimData is a variable
   that stores the input and output values from a previous simulation. For a model M, you can specify
   X0, such that:
X0 = data2state(M,firstSimData)
Dependency
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using Simulink® Coder™.
See Also
Functions
findstates | idnlarx | idnlarx/findop | sim
Blocks
Iddata Sink | Iddata Source
Topics
“Identifying Nonlinear ARX Models”
“Simulate Identified Model in Simulink”
Introduced in R2008a
                                                                                                 2-25
2   Blocks
             Library
             System Identification Toolbox
             Description
             Simulates systems of nonlinear grey-box (idnlgrey) models.
Input
Output
             Parameters
             IDNLGREY model
                Name of idnlgrey variable in the MATLAB workspace.
             Initial state
                Specify the initial states as one of the following:
             See Also
             Functions
             idnlgrey
             Blocks
             Iddata Sink | Iddata Source
             Topics
             “Estimate Nonlinear Grey-Box Models”
2-26
                       Nonlinear Grey-Box Model
Introduced in R2008a
                                         2-27
2   Blocks
             Hammerstein-Wiener Model
             Simulate Hammerstein-Wiener model in Simulink software
             Library:         System Identification Toolbox / Models
             Description
             The Hammerstein-Wiener Model block simulates the output of a Hammerstein-Wiener model using
             time-domain input data. The model is an idnlhw model that you previously estimated or constructed
             in the MATLAB workspace. You specify initial conditions for the simulation as one of the following:
             For information about the structure of a Hammerstein-Wiener model, see “What are Hammerstein-
             Wiener Models?”.
             Ports
             Input
             Simulation input data, specified as a scalar for a single-input model. The data must be time-domain
             data. For multi-input models, specify the input as an Nu-element vector, where Nu is the number of
             inputs. For example, you can use a Vector Concatenate block to concatenate scalar signals into a
             vector signal.
Note Do not use a Bus Creator or Mux block to produce the vector signal.
Output
             Simulated output from Hammerstein-Wiener model, returned as a scalar for a single-output model
             and as an Ny-element vector for a model with Ny outputs.
             Data Types: double
             Parameters
             Model — Hammerstein-Wiener model to be simulated
             idnlhw object
2-28
                                                                                Hammerstein-Wiener Model
The states of a Hammerstein-Wiener model correspond to the states of the embedded linear idpoly
or idss model. For more information about the states, see the idnlhw reference page. You specify
Initial conditions as one of the following:
• Zero — Specifies zero initial state values, which correspond to a simulation starting from a state
  of rest.
• State values — You specify the state values in Specify a vector of state values. Specify the
  states as a vector of length equal to the number of states in the model.
If you do not know the initial states, you can estimate these states as follows:
   • To simulate the model around a given input level when you do not know the corresponding
     output level, you can estimate the equilibrium state values using the findop command.
      For example, to simulate a model M about a steady-state point where the input is 1 and the
      output is unknown, you can specify the initial state values as X0, where:
      X0 = findop(M,'steady',1,NaN)
   • To estimate the initial states that provide a best fit between measured data and the simulated
     response of the model for the same input, use the findstates command.
      For example, to compute initial states such that the response of the model M matches the
      simulated output data in the data set z, specify X0, such that:
X0 = findstates(M,z)
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using Simulink® Coder™.
See Also
Functions
findstates | idnlhw | idnlhw/findop | sim
Blocks
Iddata Sink | Iddata Source
Topics
“Identifying Hammerstein-Wiener Models”
“Simulate Identified Model in Simulink”
Introduced in R2008a
                                                                                                   2-29
2   Blocks
             Kalman Filter
             Estimate states of discrete-time or continuous-time linear system
             Library
             Estimators
             Description
             Use the Kalman Filter block to estimate states of a state-space plant model given process and
             measurement noise covariance data. The state-space model can be time-varying. A steady-state
             Kalman filter implementation is used if the state-space model and the noise covariance matrices are
             all time-invariant. A time-varying Kalman filter is used otherwise.
             Kalman filter provides the optimal solution to the following continuous or discrete estimation
             problems:
Continuous-Time Estimation
with known inputs u, white process noise w, and white measurement noise v satisfying:
                  E w(t) = E v(t) = 0
                  E[w(t)wT (t)] = Q(t)
                  E[w(t)vT (t)] = N(t)
                          t
                  E[v(t)v( ] = R(t)
             construct a state estimate x that minimizes the state estimation error covariance
                                      T
             P(t) = E[(x − x )(x − x ) ].
where
2-30
                                                                                          Kalman Filter
                      T
    Q(t) = G(t)Q(t)G (t),
    R(t) = R(t) + H(t)N(t) + NT (t)HT (t) + H(t)Q(t)HT (t),
    N(t) = G(t)(Q(t)HT (t) + N(t)) .
The Kalman filter uses the known inputs u and the measurements y to generate the state estimates x .
If you want, the block can also output the estimates of the true plant output y .
The block implements the steady-state Kalman filter when the system matrices (A(t), B(t), C(t),
D(t), G(t), H(t)) and noise covariance matrices (Q(t), R(t), N(t)) are constant (specified in the
Block Parameters dialog box). The steady-state Kalman filter uses a constant matrix P that minimizes
the steady-state estimation error covariance and solves the associated continuous-time algebraic
Riccati equation:
                                T
      P = lim E[(x − x )(x − x ) ] .
          t   ∞
Discrete-Time Estimation
    x n + 1   =  A n  x n   +  B n  u n   +  G n  w n ,
    y n   =  C n  x n   +  D n  u n   +  H n  w n   +  v n ,
with known inputs u, white process noise w and white measurement noise v satisfying
    E[w[n]] = E[v[n]] = 0,
    E[w[n]wT [n]] = Q[n],
    E[v[n]vT [n]] = R[n],
    E[w[n]vT [n]] = N[n] .
where the gain L[n] is calculated through the discrete Riccati equation:
                          T             C
    L[n] = (A[n]P[n]C [n] + N[n])( ,
                  T       C
    M[n] = P[n]C [n]( ,
                                 I
    Z[n] = (I − M[n]C[n])P[n]( + M[n]R[n]MT [n],
                               −1             A                  −1
    P[n + 1] = (A[n] − N[n]R         [n]C[n])Z( + Q[n] − N[n]R        [n]NT [n],
                                                                                                 2-31
2   Blocks
                                       T
                 Q[n] = G[n]Q[n]G [n],
                 R[n] = R[n] + H[n]N[n] + NT [n]HT [n] + H[n]Q[n]HT [n],
                 N[n] = G[n](Q[n]HT [n] + N[n]),
                 and
                                               x
                 P[n] = E[(x − x [n n − 1])( ],
                                           x
                 Z[n] = E[(x − x [n n])( ],
             The steady-state Kalman filter uses a constant matrix P that minimizes the steady-state estimation
             error covariance and solves the associated discrete-time algebraic Riccati equation.
             • The current estimator generates the state estimates x [n n] using all measurement available,
               including y[n]. The filter updates x [n n − 1] with y[n] and outputs:
y [n n − 1] = C[n]x [n n − 1] + D[n]u[n]
             The current estimator has better estimation accuracy compared to the delayed estimator, which is
             important for slow sample times. However, it has higher computational cost, making it harder to
             implement inside control loops. More specifically, it has direct feedthrough. This leads to an algebraic
             loop if the Kalman filter is used in a feedback loop that does not contain any delays (the feedback loop
             itself also has direct feedthrough). The algebraic loop can impact the speed of simulation. You cannot
             generate code if your model contains algebraic loops.
The Kalman Filter block differs from the kalman command in the following ways:
             • When calling kalman(sys,...), sys includes the G and H matrices. Specifically, sys.B has [B
               G] and sys.D has [D H]. When you provide a LTI variable to the Kalman Filter block, it does not
               assume that the LTI variable provided contains G and H. They are optional and separate.
             • The kalman command outputs [yhat;xhat] by default. The block only outputs xhat by default.
             Parameters
             The following table summarizes the Kalman Filter block parameters, accessible via the Block
             Parameter dialog box.
             Task                                                Parameters
             Specify filter settings                             • Time domain on page 2-33
                                                                 • Use the current measurement y[n] to
                                                                   improve xhat[n] on page 2-33
2-32
                                                                                           Kalman Filter
Task                                               Parameters
Specify the system model                           Model source on page 2-33 in Model
                                                   Parameters tab
Specify initial state estimates                    Source on page 2-34 in Model Parameters tab
Specify noise characteristics                      In Model Parameters tab:
Time domain
   When the Kalman Filter block is in a model with synchronous state control (see the State Control
   block), you cannot select Continuous-time.
Use the current estimator variant of the discrete-time Kalman filter. When not selected, the delayed
estimator (variant) is used.
Model source
Specify how the A, B, C, D matrices are provided to the block. Must be one of the following:
• Dialog: LTI State-Space Variable — Use the values specified in the LTI state-space
  variable. You must also specify the variable name in Variable. The sample time of the model must
                                                                                                  2-33
2   Blocks
                match the setting in the Time domain option, i.e. the model must be discrete-time if the Time
                domain is discrete-time.
             • Dialog: Individual A, B, C, D matrices — Specify values in the following block
               parameters:
Sample Time
             This option is available only when Time Domain is Discrete Time and Model Source is Dialog:
             Individual A, B, C, D matrices or External. The sample time is obtained from the LTI state-
             space variable if the Model Source is Dialog: LTI State-Space Variable.
             The default value is -1, which implies that the block inherits its sample time based on the context of
             the block within the model. All block input ports must have the same sample time.
Source
Specify how to enter the initial state estimates and initial state estimation error covariance:
             • Dialog — Specify the values directly in the dialog box. You must also specify the following
               parameters:
                • Initial states x[0] — Specify the initial state estimate as a real scalar or vector. If you specify
                  a scalar, all initial state estimates are set to this scalar. If you specify a vector, the length of the
                  vector must match with the number of states in the model.
                • State estimation error covariance P[0] (only when time-varying Kalman filter is used) —
                  Specify the initial state estimation error covariance P[0] for discrete-time Kalman filter or P(0)
                  for continuous-time Kalman filter. Must be specified as one of the following:
                   • Real nonnegative scalar. P is an Ns-by-Ns diagonal matrix with the scalar on the diagonals.
                     Ns is the number of states in the model.
                   • Vector of real nonnegative scalars. P is an Ns-by-Ns diagonal matrix with the elements of
                     the vector on the diagonals of P.
2-34
                                                                                              Kalman Filter
Specify whether to use the pre-identified Kalman Gain contained in the state-space plant model. This
option is available only when:
• Model Source is Dialog: LTI State-Space Variable and Variable is an identified state-
  space model (idss) with a nonzero K matrix.
• Time Invariant Q, Time Invariant R and Time Invariant N options are selected.
If the Use G and H matrices (default G=I and H=0) option is selected, Time Invariant G and
Time Invariant H options must also be selected.
Specify whether to use non-default values for the G and H matrices. If you select this option, you
must specify:
• G — Specify the G matrix. It must be a real matrix with as many rows as the A matrix. The default
  value is 1.
• Time-invariant G — Specify if the G matrix is time invariant. If you unselect this option, the block
  includes an additional input port G.
• H — Specify the H matrix. It must be a real matrix with as many rows as the C matrix and as many
  columns as the G matrix. The default value is 0.
• Time-invariant H — Specify if the H matrix is time invariant. If you unselect this option, the
  block includes an additional input port G.
• Number of process noise inputs — Specify the number of process noise inputs in the model.
  The default value is 1.
    This option is available only when Time-invariant G and Time-invariant H are cleared.
    Otherwise, this information is inferred from the G or H matrix.
• Real nonnegative scalar. Q is an Nw-by-Nw diagonal matrix with the scalar on the diagonals. Nw is
  the number of process noise inputs in the model.
• Vector of real nonnegative scalars. Q is an Nw-by-Nw diagonal matrix with the elements of the
  vector on the diagonals of Q.
• Nw-by-Nw positive semi-definite matrix.
Time Invariant Q
Specify if the Q matrix is time invariant. If you unselect this option, the block includes an additional
input port Q.
                                                                                                     2-35
2   Blocks
             • Real positive scalar. R is an Ny-by-Ny diagonal matrix with the scalar on the diagonals. Ny is the
               number of measured outputs in the model.
             • Vector of real positive scalars. R is an Ny-by-Ny diagonal matrix with the elements of the vector on
               the diagonals of R.
             • Ny-by-Ny positive-definite matrix.
Time Invariant R
             Specify if the R matrix is time invariant. If you unselect this option, the block includes an additional
             input port R.
             Process and measurement noise cross-covariance matrix. Specify it as a Nw-by-Ny matrix. The matrix
             [Q N; NT R] must be positive definite.
Time Invariant N
             Specify if the N matrix is time invariant. If you unselect this option, the block includes an additional
             input port N.
             Select this option if your model contains known inputs u(t) or u[k]. The option is selected by
             default. Unselecting this option removes the input port u from the block and removes the B, D and
             Number of inputs parameters from the block dialog box.
             Select this option if you want to control the measurement updates. The block includes an additional
             inport Enable. The Enable input port takes a scalar signal. This option is cleared by default.
             By default the block does measurement updates at each time step to improve the state and output
             estimates x and y based on measured outputs. The measurement update is skipped for the current
             sample time when the signal in the Enable port is 0. Concretely, the equation for state estimates
             become ẋ (t) = A(t)x (t) + B(t)u(t) for continuous-time Kalman filter and
             x [n + 1 n] = A[n]x [n n − 1] + B[n]u[n] for discrete-time.
External Reset
Option to reset estimated states and parameter covariance matrix using specified initial values.
             Suppose you reset the block at a time step, t. If the block is enabled at t, the software uses the initial
             parameter values specified either in the block dialog or the input ports P0 and X0 to estimate the
             states. In other words, at t, the block performs a time update and if it is enabled, a measurement
             update after the reset. The block outputs these updated estimates.
             • None (Default) — Estimated states x and state estimation error covariance matrix P values are not
               reset.
2-36
                                                                                         Kalman Filter
• Rising — Triggers a reset when the control signal rises from a negative or zero value to a
  positive value. If the initial value is negative, rising to zero triggers a reset.
• Falling — Triggers a reset when the control signal falls from a positive or a zero value to a
  negative value. If the initial value is positive, falling to zero triggers a reset.
• Either — Triggers a reset when the control signal is either rising or falling.
• Level — Triggers a reset in either of these cases:
When you choose an option other than None, a Reset input port is added to the block to provide the
reset control input signal.
Add y output port to the block to output the estimated model outputs. The option is cleared by
default.
Add P output port or Z output port to the block. The Z matrix is provided only when Time Domain is
Discrete Time and the Use the current measurement y[n] to improve xhat[n] is selected.
Otherwise, the P matrix, as described in the “Description” on page 2-30 section previously, is
provided.
Ports
Port Name          Port     Description
                   Type
                   (In/
                   Out)
u (Optional)       In       Known inputs, specified as a real scalar or vector.
y                  In       Measured outputs, specified as a real scalar or vector.
xhat               Out      Estimated states, returned as a real scalar or vector.
yhat (Optional)    Out      Estimated outputs, returned as a real scalar or vector.
P or Z (Optional) Out       State estimation error covariance, returned as a matrix.
A (Optional)       In       A matrix, specified as a real matrix.
B (Optional)       In       B matrix, specified as a real matrix.
C (Optional)       In       C matrix, specified as a real matrix.
D (Optional)       In       D matrix, specified as a real matrix.
G (Optional)       In       G matrix, specified as a real matrix.
H (Optional)       In       H matrix, specified as a real matrix.
                                                                                                  2-37
2   Blocks
                                 (In/
                                 Out)
             Q (Optional)        In      Q matrix, specified as a real scalar, vector or matrix.
             R (Optional)        In      R matrix, specified as a real scalar, vector or matrix.
             N (Optional)        In      N matrix, specified as a real matrix.
             P0 (Optional)       In      P matrix at initial time, specified as a real scalar, vector, or matrix.
             X0 (Optional)       In      Initial state estimates, specified as a real scalar or vector.
             Enable              In      Control signal to enable measurement updates, specified as a real scalar.
             (Optional)
             Reset (Optional) In         Control signal to reset state estimates, specified as a real scalar.
Note
             • All input ports except Enable and Reset must have the same data type (single or double).
             • Enable and Reset ports support single, double, int8, uint8, int16, uint16, int32,
               uint32, and boolean data types.
             Limitations
             • The plant and noise data must satisfy:
                • (C,A) detectable
                • R > 0 and Q − NR−1NT ≥ 0
                • (A − NR−1C, Q − NR−1NT ) has no uncontrollable mode on the imaginary axis (or unit circle in
                  discrete time) with the notation
                             T
                 Q = GQG
                 R = R + HN + NT HT + HQHT
                 N = G(QHT + N)
             • The continuous-time Kalman filter cannot be used in Function-Call Subsystems or Triggered
               Subsystems.
             References
             [1] Franklin, G.F., J.D. Powell, and M.L. Workman, Digital Control of Dynamic Systems, Second
                     Edition, Addison-Wesley, 1990.
2-38
                                                                         Kalman Filter
[2] Lewis, F., Optimal Estimation, John Wiley & Sons, Inc, 1986.
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using Simulink® Coder™.
See Also
Functions
extendedKalmanFilter | kalman | particleFilter | unscentedKalmanFilter
Blocks
Extended Kalman Filter | Particle Filter | Unscented Kalman Filter
Topics
“State Estimation Using Time-Varying Kalman Filter”
“What Is Online Estimation?”
“Validate Online State Estimation in Simulink”
“Troubleshoot Online State Estimation”
Introduced in R2014b
                                                                                2-39
2   Blocks
             Library
             Estimators
             Description
             Use the Model Type Converter block to convert the ARX, ARMAX, OE, or BJ model coefficients into
             state-space model matrices.
             The block inport, u, requires a bus. The number of elements depends on the input polynomial model
             type:
             • ARX — A, B
             • ARMAX — A, B, C
             • OE — B, F
             • BJ — B,C, D, F
             These bus elements must contain row vectors of the estimated coefficient values as outputted by the
             Recursive Polynomial Model Estimator block. For MISO data, specify B polynomial coefficients as a
             matrix where the i-th row parameters correspond to the i-th input. The coefficient values can vary
             with time. The Model Type Converter block converts these coefficients into the A, B, C, and D
             matrices of a discrete-time state-space model. The Model Type Converter block outport, y, returns a
             bus with elements that correspond to the A, B, C, and D matrices of the state-space model. If the
             signals in u are time-varying, then the state-space matrices are time-varying too.
             You can also estimate a state-space model online by using the Recursive Polynomial Model Estimator
             and Model Type Converter blocks together. Connect the outport of the Recursive Polynomial Model
             Estimator block to the inport of the Model Type Converter block to obtain online values of the state-
             space matrices. The conversion ignores the noise component of the models. In other words, the state-
             space matrices only capture the y(t)/u(t) relationship.
             Parameters
             Input model type
             Specify the model type coefficients to convert to state-space model matrices. Specify one of the
             following model types:
• ARX
2-40
                                                                                  Model Type Converter
• ARMAX
• OE
• BJ
Ports
Port              Port     Description
                  Type
                  (In/
                  Out)
u                 In       Estimated A, B, C, D and F polynomial coefficients, specified as a bus
                           with elements: A, B, C, D and F.
y                 Out      State-space model, returned as a bus with elements that correspond to
                           the A, B, C, and D matrices.
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using Simulink® Coder™.
See Also
Recursive Polynomial Model Estimator
Introduced in R2014a
                                                                                                    2-41
2   Blocks
             Particle Filter
             Estimate states of discrete-time nonlinear system using particle filter
             Library:             Control System Toolbox / State Estimation
                                  System Identification Toolbox / Estimators
             Description
             The Particle Filter block estimates the states of a discrete-time nonlinear system using the discrete-
             time particle filter algorithm.
             Consider a plant with states x, input u, output m, process noise w, and measurement y. Assume that
             you can represent the plant as a nonlinear system.
             The algorithm computes the state estimates x of the nonlinear system using the state transition and
             measurement likelihood functions you specify.
             You create the nonlinear state transition function and measurement likelihood functions for the
             system and specify these functions in the block. The block supports state estimation of a system with
             multiple sensors that are operating at different sampling rates. You can specify up to five
             measurement likelihood functions, each corresponding to a sensor in the system.
             Ports
             Input
             Measured system outputs corresponding to each measurement likelihood function that you specify in
             the block. The number of ports equals the number of measurement likelihood functions in your
             system. You can specify up to five measurement likelihood functions. For example, if your system has
             two sensors, you specify two measurement likelihood functions in the block. The first port y1 is
             available by default. Click Add Measurement, to generate port y2 corresponding to the second
             measurement likelihood function.
             Specify the ports as N-dimensional vectors, where N is the number of quantities measured by the
             corresponding sensor. For example, if your system has one sensor that measures the position and
2-42
                                                                                             Particle Filter
velocity of an object, then there is only one port y1. The port is specified as a two-dimensional vector
with values corresponding to position and velocity.
Dependencies
The first port y1 is available by default. Ports y2 to y5 are generated when you click Add
Measurement.
Optional input argument to the state transition function f other than the state x.
If you create f using a MATLAB function (.m file), the software generates the port
StateTransitionFcnInputs when you enter the name of your function, and click Apply.
If your state transition function has more than one additional input, use a Simulink Function block to
specify the function. When you use a Simulink Function block, you provide the additional inputs
directly to the Simulink Function block using Inport blocks. No input ports are generated for the
additional inputs in the Particle Filter block.
Dependencies
This port is generated only if both of the following conditions are satisfied:
• You specify f in Function using a MATLAB function, and f is on the MATLAB path.
• f requires only one additional input argument apart from particles.
MeasurementLikelihoodFcn1Inputs,...,MeasurementLikelihoodFcn5Inputs — Optional
input argument to each measurement likelihood function
scalar | vector | matrix
Optional inputs to the measurement likelihood functions other than the state x and measurement y.
If you specify two measurement inputs using MATLAB functions (.m files) in Function, the software
generates ports MeasurementLikelihoodFcn1Inputs and MeasurementLikelihoodFcn2Inputs
when you click Apply. You can specify the inputs to these ports as scalars, vectors, or matrices.
If your measurement likelihood functions have more than one additional input, use Simulink Function
blocks to specify the functions. When you use a Simulink Function block, you provide the additional
inputs directly to the Simulink Function block using Inport blocks. No input ports are generated for
the additional inputs in the Particle Filter block.
Dependencies
• You specify measurement input h in Function using a MATLAB function, and h is on the MATLAB
  path.
• h requires only one additional input argument apart from particles and measurement.
                                                                                                     2-43
2   Blocks
             For example, consider that measured output data is not available at all time points at the port y1 that
             corresponds to the first measurement likelihood function. Then, use a signal value other than 0 at the
             Enable1 port to enable the correction of estimated states when measured data is available. Specify
             the port value as 0 when measured data is not available. Similarly, if measured output data is not
             available at all time points at the port yi for the ith measurement likelihood function, specify the
             corresponding port Enablei as a value other than 0.
             Dependencies
             If you select Add Enable port for a measurement likelihood function, a port corresponding to that
             measurement likelihood function is generated. The port appears when you click Apply.
Output
             Estimated states, returned as a vector of size Ns, where Ns is the number of states of the system. To
             access the individual states, use the Selector block.
             When the Use the current measurements to improve state estimates parameter is selected, the
             block outputs the corrected state estimate x [k k] at time step k, estimated using measured outputs
             until time k. If you clear this parameter, the block returns the predicted state estimate x [k k − 1] for
             time k, estimated using measured output until a previous time k-1. Clear this parameter if your filter
             is in a feedback loop and there is an algebraic loop in your Simulink model.
             State estimation error covariance, returned as an Ns-by-Ns matrix, where Ns is the number of states
             of the system. To access the individual covariances, use the Selector block.
             You can output the error covariance only if you select Output state estimation error covariance in
             the Block outputs, Multirate tab, and click Apply.
             Dependencies
             This parameter is available if in the Block outputs, Multirate tab, the State estimation method
             parameter is set to 'Mean'.
             Particle values used for state estimation, returned as an Ns-by-Np or Np-by-Ns array. Ns is the
             number of states of the system, and Np is the number of particles.
2-44
                                                                                               Particle Filter
Dependencies
This port is generated if you select Output all particles in the Block outputs, Multirate tab, and
click Apply.
Particle weights used for state estimation, returned as a 1-by-Np or Np-by-1 vector, where Np is the
number of particles used for state estimation.
Dependencies
This port is generated if you select Output weights in the Block outputs, Multirate tab, and click
Apply.
Parameters
System Model Tab
State Transition
The particle filter state transition function calculates the particles at time step k+1, given particles at
time step k per the dynamics of your system and process noise. This function has the syntax:
where, particles and particlesNext have dimensions Ns-by-Np if State Orientation is specified as
'column', or Np-by-Ns if State Orientation is specified as 'row'. Also, param_i represents
optional input arguments you may specify. For more information on optional input arguments, see
“StateTransitionFcnInputs” on page 2-0 .
You create the state transition function and specify the function name in Function. For example, if
vdpParticleFilterStateFcn.m is the state transition function that you created and saved, specify
Function as 'vdpParticleFilterStateFcn'.
You can create Function using a Simulink Function block or as a MATLAB function (.m file).
Programmatic Use
Block Parameter: StateTransitionFcn
Type: character vector, string
Default: 'vdpParticleFilterStateFcn'
                                                                                                       2-45
2   Blocks
Initialization
             Number of particles used in the filter, specified as a positive scalar integer. Each particle represents a
             state hypothesis in the system. A higher number of particles increases the state estimation accuracy,
             but also increases the computational effort required to run the filter.
             Programmatic Use
             Block Parameter: NumberOfParticles
             Type: positive scalar integer
             Default: 1000
             If you choose 'Gaussian', the initial set of particles or state hypotheses are distributed per the
             multivariate Gaussian distribution, where you specify the Mean and Covariance. The initial weight
             of all particles is assumed to be equal.
             If you choose 'Uniform', the initial set of particles are distributed per the uniform distribution,
             where you specify the upper and lower State bounds. The initial weight of all particles is assumed to
             be equal.
             'Custom' allows you to specify your own set of initial particles and their weights. You can use
             arbitrary probability distributions for Particles and Weights to initialize the filter.
             Programmatic Use
             Block Parameter: InitialDistribution
             Type: character vector
             Values: 'Gaussian', 'Uniform', 'Custom'
             Default: 'Gaussian'
             Initial mean value of particles, specified as a vector. The number of states to be estimated defines the
             length of the vector.
             Dependencies
             This parameter is available if in the System model tab, the Distribution parameter is set to
             Gaussian.
             Programmatic Use
             Block Parameter: InitialMean
             Type: array
             Default: [0,0]
2-46
                                                                                                Particle Filter
• A scalar, then it must be positive. The covariance is assumed to be a [Ns Ns] matrix with this
  scalar on the diagonals. Here, Ns is the number of states.
• A vector, then each element must be positive. The covariance is assumed to be a [Ns Ns] matrix
  with the elements of the vector on the diagonals.
• A matrix, then it must be positive semidefinite.
Dependencies
This parameter is available if in the System model tab, the Distribution parameter is set to
Gaussian.
Programmatic Use
Block Parameter: InitialCovariance
Type: scalar, vector, or matrix
Default: 1
Circular variables used for state estimation, specified as a scalar, or Ns-element vector, where Ns is
the number of states.
If Circular Variables is specified as a scalar, the software extends it to a vector where each element
is equal to this scalar. Circular (or angular) distributions use a probability density function with a
range of [-π π]. Use circular variables if some of the states in your system represent angular
quantities like the orientation of an object.
Programmatic Use
Block Parameter: CircularVariables
Type: scalar, vector
Default: 0
• 'column', then the first input argument to the state transition and measurement likelihood
  function is [Ns Np]. In this case, ith column of this matrix is the ith particle (state hypothesis). Also,
  the states estimates xhat is output as a [Ns 1] vector. Here, Ns is the number of states, and Np is
  the number of particles.
• 'row', then the first input argument to the state transition and measurement likelihood function
  is [Np Ns], and each row of this matrix contains a particle. Also, the states estimates xhat is
  output as a [1 Ns] vector.
Programmatic Use
Block Parameter: StateOrientation
Type: character vector
Values: 'column', 'row'
Default: 'column'
                                                                                                        2-47
2   Blocks
Initial bounds on system states, specified as an Ns-by-2 array, where Ns is the number of states.
             The ith row lists the lower and upper bound of the uniform distribution for the initial distribution of
             particles of the ith state.
             Dependencies
             This parameter is available if in the System model tab, the Distribution parameter is set to
             Uniform.
             Programmatic Use
             Block Parameter: InitialStateBounds
             Type: array
             Default: [-3 3;-3 3]
             Custom particle distribution for state estimation, specified as an Ns-by-Np or Np-by-Ns array. Ns is
             the number of states of the system, and Np is the number of particles.
Dependencies
             This parameter is available if in the System model tab, the Distribution parameter is set to
             Custom.
             Programmatic Use
             Block Parameter: InitialParticles
             Type: array
             Default: []
             Custom particle weight values for state estimation, specified as a 1-by-Np or Np-by-1 positive vector,
             where Np is the number of particles used for state estimation.
Dependencies
             This parameter is available if in the System model tab, the Distribution parameter is set to
             Custom.
2-48
                                                                                          Particle Filter
Programmatic Use
Block Parameter: InitialWeights
Type: positive vector
Default: []
Measurement
The measurement likelihood function calculates the likelihood of particles (state hypotheses) using
the sensor measurements. For each state hypothesis (particle), the function first calculates an Nm-
element measurement hypothesis vector. Then the likelihood of each measurement hypothesis is
calculated based on the sensor measurement and the measurement noise probability distribution. this
function has the syntax:
likelihood = h(particles, measurement, param1, param2, ...)
where, likelihood is an Np-element vector, where Np is the number of particles. particles have
dimensions Ns-by-Np if State Orientation is specified as 'column', or Np-by-Ns if State
Orientation is specified as 'row'. measurement is an Nm-element vector where, Nm is the number
of measurements your sensor provides. param_i represents optional input arguments you may specify.
For more information on optional input arguments, see
“MeasurementLikelihoodFcn1Inputs,...,MeasurementLikelihoodFcn5Inputs” on page 2-0 .
You create the measurement likelihood function and specify the function name in Function. For
example, if vdpMeasurementLikelihoodFcn.m is the measurement likelihood function that you
created and saved, specify Function as 'vdpMeasurementLikelihoodFcn'.
You can create Function using a Simulink Function block or as a MATLAB function (.m file).
• You can use a MATLAB function only if h has zero or one additional input argument param_i
  other than Particles and Measurement.
If you have multiple sensors in your system, you can specify multiple measurement likelihood
functions. You can specify up to five measurement likelihood functions using the Add Measurement
button. To remove measurement likelihood functions, use Remove Measurement.
Programmatic Use
Block Parameter: MeasurementLikelihoodFcn1, MeasurementLikelihoodFcn2,
MeasurementLikelihoodFcn3, MeasurementLikelihoodFcn4, MeasurementLikelihoodFcn5
Type: character vector, string
Default: 'vdpMeasurementLikelihoodFcn'
Add Enable Port — Enable correction of estimated states only when measured data is
available
off (default) | on
Suppose that measured output data is not available at all time points at the port y1 that corresponds
to the first measurement likelihood function. To generate an input port Enable1, select Add Enable
                                                                                                  2-49
2   Blocks
             port. Use a signal at this port to enable the correction of estimated states only when measured data
             is available. Similarly, if measured output data is not available at all time points at the port yi for the
             ith measurement likelihood function, select the corresponding Add Enable port.
             Programmatic Use
             Block Parameter: HasMeasurementEnablePort1, HasMeasurementEnablePort2,
             HasMeasurementEnablePort3, HasMeasurementEnablePort4, HasMeasurementEnablePort5
             Type: character vector
             Values: 'off', 'on'
             Default: 'off'
Resampling
             • 'Multinomial'
             • 'Systematic'
             • 'Stratified'
             Programmatic Use
             Block Parameter: ResamplingMethod
             Type: character vector
             Values: 'Multinomial', 'Systemic', 'Stratified'
             Default: 'Multinomial'
             Method to determine when resampling occurs, specified as either 'Ratio' or 'Interval'. The
             'Ratio' value triggers resampling based on the ratio of effective total particles. The 'Interval'
             value triggers resampling at regular time steps of the particle filter operation.
             Programmatic Use
             Block Parameter: TriggerMethod
             Type: character vector
             Values: 'Ratio', 'Interval'
             Default: 'Ratio'
             Minimum effective particle ratio — Minimum desired ratio of the effective number of
             particles to the total number of particles
             0.5 (default) | positive scalar
             Minimum desired ratio of the effective number of particles to the total number of particles, specified
             as a positive scalar. The effective number of particles is a measure of how well the current set of
             particles approximates the posterior distribution. A lower effective particle ratio implies that a lower
             number of particles are contributing to the estimation and resampling is required.
             If the ratio of the effective number of particles to the total number of particles falls below the
             minimum effective particle ratio, a resampling step is triggered.
2-50
                                                                                        Particle Filter
Dependencies
This parameter is available if in the System model tab, the Trigger method parameter is set to
Ratio.
Programmatic Use
Block Parameter: MinEffectiveParticleRatio
Type: scalar
Values: Range [0,1]
Default: 0.5
Fixed interval between resampling, specified as a positive scalar integer. The sampling interval
determines during which correction steps the resampling is executed. For example, a value of two
means the resampling is executed every second correction step. A value of inf means that
resampling is never executed.
Dependencies
This parameter is available if in the System model tab, the Trigger method parameter is set to
Interval.
Programmatic Use
Block Parameter: SamplingInterval
Type: positive scalar integer
Default: 1
Whether the random numbers are repeatable, specified as either 'Repeatable' or 'Not
repeatable'. If you want to be able to produce the same result more than once, set Randomness
to 'Repeatable', and specify the same random number generator seed value in Seed.
Programmatic Use
Block Parameter: Randomness
Type: character vector
Values: 'Repeatable', 'Not repeatable'
Default: 'Repeatable'
This parameter is available if in the System model tab, the Randomness parameter is set to
'Repeatable'.
Programmatic Use
Block Parameter: Seed
Type: scalar
                                                                                                 2-51
2   Blocks
Default: 0
Settings
             Use this parameter to specify the data type for all block parameters.
             Programmatic Use
             Block Parameter: DataType
             Type: character vector
             Values: 'single', 'double'
             Default: 'double'
             Use the Sample time parameter if your state transition and all measurement likelihood functions
             have the same sample time. Otherwise, select the Enable multirate operation option in the
             Multirate tab, and specify sample times in the same tab.
             Dependencies
             This parameter is available if in the Block output, Multirate tab, the Enable multirate operation
             parameter is off.
             Programmatic Use
             Block Parameter: SampleTime
             Type: character vector, string
             Default: '1'
Outputs
             State Estimation Method — Method used for extracting a state estimate from particles
             'Mean' (default) | 'MaxWeight' | 'None'
Method used for extracting a state estimate from particles, specified as one of the following:
             • 'Mean' — The Particle Filter block outputs the weighted mean of the particles, depending on the
               parameters Weights and Particles, as the state estimate.
             • 'Maxweight' — The Particle Filter block outputs the particle with the highest weight as the state
               estimate.
             • 'None' — Use this option to implement a custom state estimation method by accessing all
               particles using the Output all particles parameter from the Block outputs, Multirate tab.
             Programmatic Use
             Block Parameter: StateEstimationMethod
             Type: character vector, string
             Values: 'Mean', 'MaxWeight', 'None'
             Default: 'Mean'
2-52
                                                                                              Particle Filter
If you select this parameter, an output port for particles used in the estimation, Particles is
generated in the block.
• If the StateOrientation parameter is specified as 'column', then the particles are output as
  an Ns-by-Np array. Ns is the number of states of the system, and Np is the number of particles.
• If the StateOrientation parameter is specified as 'row', then the particles are output as an
  Np-by-Ns array.
Programmatic Use
Block Parameter: OutputParticles
Type: character vector
Values: 'off', 'on'
Default: 'off'
If you select this parameter, an output port for particle weights used in the estimation, Weights is
generated in the block.
• If the StateOrientation parameter is specified as 'column', then the particle weights are
  output as a 1-by-Np vector. Here, where each weight is associated with the particle in the same
  column in the Particles array. Np is the number of particles used for state estimation.
• If the StateOrientation parameter is specified as 'row', then the particle weights are output
  as a Np-by-1 vector.
Programmatic Use
Block Parameter: OutputWeights
Type: character vector
Values: 'off', 'on'
Default: 'off'
Output state estimation error covariance — Output state estimation error covariance
'off' (default) | 'on'
If you select this parameter, a state estimation error covariance output port, P is generated in the
block.
Dependencies
This parameter is available if in the Block outputs, Multirate tab, the State estimation method
parameter is set to 'Mean'.
Programmatic Use
Block Parameter: OutputStateCovariance
Type: character vector
Values: 'off', 'on'
Default: 'off'
Use the current measurements to improve state estimates — Option to use current
measurements for state estimation
'on' (default) | 'off'
                                                                                                      2-53
2   Blocks
             When this parameter is selected, the block outputs the corrected state estimate x [k k] at time step k,
             estimated using measured outputs until time k. If you clear this parameter, the block returns the
             predicted state estimate x [k k − 1] for time k, estimated using measured output until a previous time
             k-1. Clear this parameter if your filter is in a feedback loop and there is an algebraic loop in your
             Simulink model.
             Programmatic Use
             Block Parameter: UseCurrentEstimator
             Type: character vector
             Values: 'on', 'off'
             Default: 'on'
Multirate
             Enable multirate operation — Enable specification of different sample times for state
             transition and measurement likelihood functions
             'off' (default) | 'on'
             Select this parameter if the sample times of the state transition or any of the measurement likelihood
             functions differ from the rest. You specify the sample times in the Multirate tab, in Sample time.
             Programmatic Use
             Block Parameter: EnableMultirate
             Type: character vector
             Values: 'off', 'on'
             Default: 'off'
             Sample times — State transition and measurement likelihood function sample times
             positive scalar
             If the sample times for state transition and measurement likelihood functions are different, specify
             Sample time. Specify the sample times for the measurement functions as positive integer multiples
             of the state transition sample time. The sample times you specify correspond to the following input
             ports:
             • Ports corresponding to state transition function — Additional input to state transition function
               StateTransitionFcnInputs. The sample times of these ports must always equal the state
               transition function sample time, but can differ from the sample time of the measurement
               likelihood functions.
             • Ports corresponding to ith measurement likelihood function — Measured output yi, additional
               input to measurement likelihood function MeasurementLikelihoodFcniInputs, enable signal at
               port Enablei. The sample times of these ports for the same measurement likelihood function
               must always be the same, but can differ from the sample time for the state transition function and
               other measurement likelihood functions.
Dependencies
             This parameter is available if in the Block outputs, Multirate tab, the Enable multirate operation
             parameter is on.
             Programmatic Use
             Block Parameter: StateTransitionFcnSampleTime,
             MeasurementLikelihoodFcn1SampleTime1, MeasurementLikelihoodFcn1SampleTime2,
2-54
                                                                                       Particle Filter
MeasurementLikelihoodFcn1SampleTime3, MeasurementLikelihoodFcn1SampleTime4,
MeasurementLikelihoodFcn1SampleTime5
Type: character vector, string
Default: '1'
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using Simulink® Coder™.
The state transition and measurement likelihood functions that you specify must use only the
MATLAB commands and Simulink blocks that support code generation. For a list of blocks that
support code generation, see “Simulink Built-In Blocks That Support Code Generation” (Simulink
Coder). For a list of commands that support code generation, see “Functions and Objects Supported
for C/C++ Code Generation” (MATLAB Coder).
See Also
Blocks
Extended Kalman Filter | Kalman Filter | Unscented Kalman Filter
Functions
extendedKalmanFilter | particleFilter | unscentedKalmanFilter
Topics
“Parameter and State Estimation in Simulink Using Particle Filter Block”
“Validate Online State Estimation in Simulink”
“Troubleshoot Online State Estimation”
“Estimate States of Nonlinear System with Multiple, Multirate Sensors”
Introduced in R2018a
                                                                                               2-55
2   Blocks
             Description
             The Recursive Least Squares Estimator estimates the parameters of a system using a model that is
             linear in those parameters. Such a system has the following form:
y(t) = H(t)θ(t) .
             y and H are known quantities that you provide to the block to estimate θ. The block can provide both
             infinite-history [1] and finite-history [2] (also known as sliding-window), estimates for θ. For more
             information on these methods, see “Recursive Algorithms for Online Parameter Estimation”.
             The block supports several estimation methods and data input formats. Configurable options in the
             block include:
             For a given time step t, y(t) and H(t) correspond to the Output and Regressors inports of the
             Recursive Least Squares Estimator block, respectively. θ(t) corresponds to the Parameters outport.
             For example, suppose that you want to estimate a scalar gain, θ, in the system y = h2θ. Here, y is
             linear with respect to θ. You can use the Recursive Least Squares Estimator block to estimate θ.
             Specify y and h2 as inputs to the Output and Regressor inports.
             Ports
             Input
             Regressors input signal H(t). The Input Processing and Number of Parameters parameters define
             the dimensions of the signal:
2-56
                                                                           Recursive Least Squares Estimator
Measured output signal y(t). The Input Processing parameter defines the dimensions of the signal:
External signal that allows you to enable and disable estimation updates. If the signal value is:
• true — Estimate and output the parameter values for the time step.
• false — Do not estimate the parameter values, and output the most recent previously estimated
  value.
Dependencies
Reset parameter estimation to its initial conditions. The value of the External reset parameter
determines the trigger type. The trigger type dictates whether the reset occurs on a signal that is
rising, falling, either rising or falling, level, or on level hold.
Dependencies
To enable this port, select any option other than None in the External reset dropdown.
Data Types: single | double | Boolean | int8 | int16 | int32 | uint8 | uint16 | uint32
Initial parameter estimates, supplied from a source external to the block. The block uses this inport at
the beginning of the simulation or when you trigger an algorithm reset using the Reset signal.
The Number of Parameters parameter defines the dimensions of the signal. If there are N
parameters, the signal is N-by-1.
Dependencies
To enable this port, set History to Infinite and Initial Estimate to External.
Data Types: single | double
                                                                                                      2-57
2   Blocks
             Initial parameter covariances, supplied from a source external to the block. For details, see the
             Parameter Covariance Matrix parameter.The block uses this inport at the beginning of the
             simulation or when you trigger an algorithm reset using the Reset signal.
             Dependencies
             • History to Infinite
             • Estimation Method to Forgetting Factor or Kalman Filter
             • Initial Estimate to External
             Initial values of the regressors in the initial data window when using finite-history (sliding-window)
             estimation, supplied from an external source. The Window length parameter W and the Number of
             Parameters parameter N define the dimensions of this signal, which is W-by-N.
             The InitialRegressors signal controls the initial behavior of the algorithm. The block uses this inport
             at the beginning of the simulation or whenever the Reset signal triggers.
             If the initial buffer is set to 0 or does not contain enough information, you see a warning message
             during the initial phase of your estimation. The warning should clear after a few cycles. The number
             of cycles it takes for sufficient information to be buffered depends upon the order of your polynomials
             and your input delays. If the warning persists, you should evaluate the content of your signals.
             Dependencies
             To enable this port, set History to Finite and Initial Estimate to External.
             Data Types: single | double
             Initial set of output measurements when using finite-history (sliding-window) estimation, supplied
             from an external source. The signal to this port must be a W-by-1 vector, where W is the window
             length.
             The InitialOutputs signal controls the initial behavior of the algorithm. The block uses this inport at
             the beginning of the simulation or whenever the Reset signal triggers.
             If the initial buffer is set to 0 or does not contain enough information, you see a warning message
             during the initial phase of your estimation. The warning should clear after a few cycles. The number
             of cycles it takes for sufficient information to be buffered depends upon the order of your polynomials
             and your input delays. If the warning persists, you should evaluate the content of your signals.
             Dependencies
             To enable this port, set History to Finite, and Initial Estimate to External.
             Data Types: single | double
2-58
                                                                       Recursive Least Squares Estimator
Output
Estimated parameters θ(t), returned as an N-by-1 vector where N is the number of parameters.
Data Types: single | double
Dependencies
Parameter estimation error covariance P, returned as an N-by-N matrix, where N is the number of
parameters. For details, see the Output Parameter Covariance Matrix parameter.
Dependencies
Parameters
Model Parameters
                                                                                                   2-59
2   Blocks
                • If History is Infinite, specify the Initial Parameter Values and Parameter Covariance
                  Matrix parameters.
                • If History is Finite, specify the Number of Parameters, the Initial Regressors, and the
                  Initial Outputs parameters.
             • External — Specify initial parameter estimates as an input signal to the block.
                Specify the Number of Parameters parameter. Your setting for the History parameter
                determines which additional signals to connect to the relevant ports:
             Programmatic Use
             Block Parameter: InitialEstimateSource
             Type: character vector, string
             Values: 'None', 'Internal', 'External'
             Default: 'None'
             Specify the number of parameters to estimate in the model, equal to the number of elements in the
             parameter θ(t) vector.
             Dependencies
             An alternative way to specify the number of parameters N to estimate is by using the Initial
             Parameter Values parameter, for which you define an initial estimate vector with N elements. This
             approach covers the one remaining combination, where History is Infinite and Initial Estimate
             is Internal. For more information, see Initial Parameter Values.
             Programmatic Use
             Block Parameter: InitialParameterData
             Type: positive integer
             Default: 2
             • Real positive scalar, α — Covariance matrix is an N-by-N diagonal matrix, with α as the diagonal
               elements.
             • Vector of real positive scalars, [α1,...,αN] — Covariance matrix is an N-by-N diagonal matrix, with
               [α1,...,αN] as the diagonal elements.
             • N-by-N symmetric positive-definite matrix.
2-60
                                                                          Recursive Least Squares Estimator
• History to Infinite
• Initial Estimate to None or Internal
• Estimation Method to Forgetting Factor or Kalman Filter
Programmatic Use
Block Parameter: P0
Type: scalar, vector, or matrix
Default: 1e4
Specify initial parameter values as a vector of length N, where N is the number of parameters to
estimate.
Dependencies
To enable this parameter, set History to Infinite and Initial Estimate to Internal.
Programmatic Use
Block Parameter: InitialParameterData
Type: real vector
Default: [1 1]
Specify the initial values of the regressors buffer when using finite-history (sliding window)
estimation. The Window length parameter W and the Number of Parameters parameter N define
the dimensions of the regressors buffer, which is W-by-N.
The Initial Regressors parameter controls the initial behavior of the algorithm. The block uses this
parameter at the beginning of the simulation or whenever the Reset signal triggers.
When the initial value is set to 0, the block populates the buffer with zeros.
If the initial buffer is set to 0 or does not contain enough information, you see a warning message
during the initial phase of your estimation. The warning should clear after a few cycles. The number
of cycles it takes for sufficient information to be buffered depends upon the order of your polynomials
and your input delays. If the warning persists, you should evaluate the content of your signals.
Dependencies
To enable this parameter, set History to Finite and Initial Estimate to Internal.
Programmatic Use
Block Parameter: InitialRegressors
Type: real matrix
Default: 0
                                                                                                     2-61
2   Blocks
             Specify initial values of the measured outputs buffer when using finite-history (sliding-window)
             estimation. This parameter is a W-by-1 vector, where W is the window length.
When the initial value is set to 0, the block populates the buffer with zeros.
             If the initial buffer is set to 0 or does not contain enough information, you see a warning message
             during the initial phase of your estimation. The warning should clear after a few cycles. The number
             of cycles it takes for sufficient information to be buffered depends upon the order of your polynomials
             and your input delays. If the warning persists, you should evaluate the content of your signals.
             The Initial Outputs parameter controls the initial behavior of the algorithm. The block uses this
             parameter at the beginning of the simulation or whenever the Reset signal triggers.
             Dependencies
             To enable this parameter, set History to Finite and Initial Estimate to Internal .
             Programmatic Use
             Block Parameter: InitialOutputs
             Type: real vector
             Default: 0
             Specifying frame-based data adds an extra dimension of M to some of your data inports and outports,
             where M is the number of time steps in a frame. These ports are:
             • Regressors
             • Output
             • Error
             For more information, see the port descriptions in “Ports” on page 2-56.
             Programmatic Use
             Block Parameter: InputProcessing
             Type: character vector, string
             Values: 'Sample-based', 'Frame-based'
             Default: 'Sample-based'
2-62
                                                                        Recursive Least Squares Estimator
Specify the data sample time, whether by individual samples for sample-based processing (ts), or by
frames for frame-based processing (tf = Mts), where M is the frame length. When you set Sample
Time to its default value of -1, the block inherits its ts or tf based on the signal.
The History parameter determines what type of recursive algorithm you use:
• Infinite — Algorithms in this category aim to produce parameter estimates that explain all data
  since the start of the simulation. These algorithms retain the history in a data summary. The block
  maintains this summary within a fixed amount of memory that does not grow over time.
   The block provides multiple algorithms of the Infinite type. Selecting this option enables the
   Estimation Method parameter with which you specify the algorithm.
• Finite — Algorithms in this category aim to produce parameter estimates that explain only a
  finite number of past data samples. The block uses all of the data within a finite window, and
  discards data once that data is no longer within the window bounds. This method is also called
  sliding-window estimation.
Selecting this option enables the Window Length parameter that sizes the sliding window.
For more information on recursive estimation methods, see “Recursive Algorithms for Online
Parameter Estimation”
Programmatic Use
Block Parameter: History
Type: character vector, string
Values: 'Infinite', 'Finite'
Default: 'Infinite'
The Window Length parameter determines the number of time samples to use for the sliding-
window estimation method. Choose a window size that balances estimation performance with
computational and memory burden. Sizing factors include the number and time variance of the
parameters in your model. Always specify Window Length in samples, even if you are using frame-
based input processing.
Window Length must be greater than or equal to the number of estimated parameters.
Suitable window length is independent of whether you are using sample-based or frame-based input
processing. However, when using frame-based processing, Window Length must be greater than or
equal to the number of samples (time steps) contained in the frame.
                                                                                                   2-63
2   Blocks
Dependencies
             Specify the estimation algorithm when performing infinite-history estimation. When you select any of
             these methods, the block enables additional related parameters.
             Forgetting factor and Kalman filter algorithms are more computationally intensive than gradient and
             normalized gradient methods. However, these more intensive methods have better convergence
             properties than the gradient methods. For more information about these algorithms, see “Recursive
             Algorithms for Online Parameter Estimation”.
             Programmatic Use
             Block Parameter: EstimationMethod
             Type: character vector, string
             Values: 'Forgetting Factor','Kalman Filter','Normalized Gradient','Gradient'
             Default: 'Forgetting Factor'
             The forgetting factor λ specifies if and how much old data is discounted in the estimation. Suppose
             that the system remains approximately constant over T0 samples. You can choose λ such that:
                         1
                 T0 =
                        1−λ
             To enable this parameter, set History to Infinite and Estimation Method to Forgetting
             Factor.
             Programmatic Use
             Block Parameter: AdaptationParameter
             Type: scalar
             Values: (0 1] range
             Default: 1
             Process Noise Covariance — Process noise covariance for Kalman filter estimation
             method
             1 (default) | nonnegative scalar | vector of nonnegative scalars | symmetric positive semidefinite
             matrix
2-64
                                                                       Recursive Least Squares Estimator
Process Noise Covariance prescribes the elements and structure of the noise covariance matrix for
the Kalman filter estimation. Using N as the number of parameters to estimate, specify the Process
Noise Covariance as one of the following:
• Real nonnegative scalar, α — Covariance matrix is an N-by-N diagonal matrix, with α as the
  diagonal elements.
• Vector of real nonnegative scalars, [α1,...,αN] — Covariance matrix is an N-by-N diagonal matrix,
  with [α1,...,αN] as the diagonal elements.
• N-by-N symmetric positive semidefinite matrix.
The Kalman filter algorithm treats the parameters as states of a dynamic system and estimates these
parameters using a Kalman filter. Process Noise Covariance is the covariance of the process noise
acting on these parameters. Zero values in the noise covariance matrix correspond to constant
coefficients, or parameters. Values larger than 0 correspond to time-varying parameters. Use large
values for rapidly changing parameters. However, expect the larger values to result in noisier
parameter estimates. The default value is 1.
Dependencies
To enable this parameter, set History to Infinite and Estimation Method to Kalman Filter.
Programmatic Use
Block Parameter: AdaptationParameter
Type: scalar, vector, matrix
Default: 1
The adaptation gain γ scales the influence of new measurement data on the estimation results for the
gradient and normalized gradient methods. When your measurements are trustworthy, or in other
words have a high signal-to-noise ratio, specify a larger value for γ. However, setting γ too high can
cause the parameter estimates to diverge. This divergence is possible even if the measurements are
noise free.
When Estimation Method is NormalizedGradient, Adaptation Gain should be less than 2. With
either gradient method, if errors are growing in time (in other words, estimation is diverging), or
parameter estimates are jumping around frequently, consider reducing Adaptation Gain.
Dependencies
To enable this parameter, set History to Infinite and Estimation Method to Normalized
Gradient or to Gradient.
Programmatic Use
Block Parameter: AdaptationParameter
Type: scalar
Default: 1
Normalization Bias — Bias for adaptation gain scaling for normalized gradient estimation
method
eps (default) | nonnegative scalar
The normalized gradient algorithm scales the adaptation gain at each step by the square of the two-
norm of the gradient vector. If the gradient is close to zero, the near-zero denominator can cause
                                                                                                  2-65
2   Blocks
             jumps in the estimated parameters. Normalization Bias is the term introduced to the denominator
             to prevent these jumps. Increase Normalization Bias if you observe jumps in estimated parameters.
             Dependencies
             To enable this parameter, set History to Infinite and Estimation Method to Normalized
             Gradient.
             Programmatic Use
             Block Parameter: NormalizationBias
             Type: scalar
             Default: eps
Block Options
             Use the Error outport signal to validate the estimation. For a given time step t, the estimation error
             e(t) is calculated as:
             where y(t) is the measured output that you provide, and yest(t) is the estimated output using the
             regressors H(t) and parameter estimates θ(t-1).
             Programmatic Use
             Block Parameter: OutputError
             Type: character vector, string
             Values: 'off','on',
             Default: 'off'
             Use the Covariance outport signal to examine parameter estimation uncertainty. The software
             computes parameter covariance P assuming that the residuals, e(t), are white noise, and the variance
             of these residuals is 1.
             The interpretation of P depends on the estimation approach you specify in History and Estimation
             Method as follows:
2-66
                                                                          Recursive Least Squares Estimator
Programmatic Use
Block Parameter: OutputP
Type: character vector, string
Values: 'off','on'
Default: 'off'
Use the Enable signal to provide a control signal that enables or disables parameter estimation. The
block estimates the parameter values for each time step that parameter estimation is enabled. If you
disable parameter estimation at a given step, t, then the software does not update the parameters for
that time step. Instead, the block outputs the last estimated parameter values.
   • Your regressors or output signal become too noisy, or do not contain information at some time
     steps
   • Your system enters a mode where the parameter values do not change in time
Programmatic Use
Block Parameter: AddEnablePort
Type: character vector, string
Values: 'off','on'
Default: 'off'
Set the External reset parameter to both add a Reset inport and specify the inport signal condition
that triggers a reset of algorithm states to their specified initial values. Reset the estimation, for
example, if parameter covariance is becoming too large because of lack of either sufficient excitation
or information in the measured signals.
Suppose that you reset the block at a time step, t. If the block is enabled at t, the software uses the
initial parameter values specified in Initial Estimate to estimate the parameter values. In other
words, at t, the block performs a parameter update using the initial estimate and the current values
of the inports.
If the block is disabled at t and you reset the block, the block outputs the values specified in Initial
Estimate.
                                                                                                     2-67
2   Blocks
                • Control signal changes from nonzero at the previous time step to zero at the current time step.
             • Level hold — Trigger reset when the control signal is nonzero at the current time step.
             When you choose any option other than None, the software adds a Reset inport to the block. You
             provide the reset control input signal to this inport.
             Programmatic Use
             Block Parameter: ExternalReset
             Type: character vector, string
             Values: 'None','Rising','Falling', 'Either', 'Level', 'Level hold'
             Default: 'None'
             References
             [1] Ljung, L. System Identification: Theory for the User. Upper Saddle River, NJ: Prentice-Hall PTR,
                     1999, pp. 363–369.
             [2] Zhang, Q. "Some Implementation Aspects of Sliding Window Least Squares Algorithms." IFAC
                     Proceedings. Vol. 33, Issue 15, 2000, pp. 763-768.
             Extended Capabilities
             C/C++ Code Generation
             Generate C and C++ code using Simulink® Coder™.
             See Also
             Kalman Filter | Recursive Polynomial Model Estimator
             Topics
             “Estimate Parameters of System Using Simulink Recursive Estimator Block”
             “Online Recursive Least Squares Estimation”
             “Preprocess Online Parameter Estimation Data in Simulink”
             “Validate Online Parameter Estimation Results in Simulink”
             “Generate Online Parameter Estimation Code in Simulink”
             “Recursive Algorithms for Online Parameter Estimation”
Introduced in R2014a
2-68
                                                                          Recursive Polynomial Model Estimator
Description
Model Structures
Use the Recursive Polynomial Model Estimator block to estimate discrete-time input-output
polynomial and time-series models.
• AR — A(q)y(t) = e(t)
• ARMA — A(q)y(t) = C(q)e(t)
• ARX — A(q)y(t) = B(q)u(t – nk) + e(t)
• ARMAX — A(q)y(t) = B(q)u(t – nk) + C(q)e(t)
•                 B(q)
    OE — y(t) =        u(t − nk) + e(t)
                  F(q)
•                 B(q)             C(q)
    BJ — y(t) =        u(t − nk) +      e(t)
                  F(q)             D(q)
q is the time-shift operator and nk is the input delay. u(t) is the input, y(t) is the output, and e(t) is the
error. For MISO models, there are as many B(q) polynomials as the number of inputs.
The orders of these models correspond to the maximum number of time shifts, as represented by the
exponent of q. For instance, the order na is represented in the A(q) polynomial by:
An equivalent representation applies to the C(q), D(q), and F(q) polynomials and their corresponding
orders nc, nd, and nf.
The B(q) polynomial is unique with respect to the others, because this polynomial operates on the
input and contains the system zeros. For B(q), the order nb is the order of the polynomial B(q) + 1:
The orders na, nb, nc, nd, nf, and input delay nk are known ahead of time. Specify these values as
block parameters. Provide u(t) and y(t) through the Inputs and Outputs inports, respectively. The
block estimates the set of A(q), B(q), C(q), D(q), and F(q) coefficients that the model structure uses
and outputs them in the Parameters outport. During the estimation, the block constrains the
estimated C, D, and F polynomials to a stable region with roots in the unit disk, while allowing the
estimated A and B polynomials to be unstable. The Parameters outport provides a bus signal with
the following elements:
                                                                                                         2-69
2   Blocks
             For example, suppose that you want to estimate the coefficients for the following SISO ARMAX
             model:
             y, u, na, nb, nc, and nk are known quantities that you provide to the block. For each time step, t, the
             block estimates the A, B, and C parameter values, constraining only the C polynomial to a stable
             region. The block then outputs these estimated values using the Parameters outport.
Block Capabilities
             The block supports several estimation methods and data input formats. The block can provide both
             infinite-history [1] and finite-history [2] (also known as sliding-window) estimates for θ. Configurable
             options in the block include:
             • Multiple inputs (ARX model structure only) — See the Inputs port.
             • Sample-based or frame-based data format — See the Input Processing parameter.
             • Multiple infinite-history estimation methods [1] — See the Estimation Method parameter.
             • Infinite-history (all model structures) or finite-history (AR, ARX, or OE model structures only) —
               See the History parameter.
             • Initial conditions, enable flag, and reset trigger — See the Initial Estimate, Add enable port,
               and External Reset parameters.
             For more information on the estimation methods, see “Recursive Algorithms for Online Parameter
             Estimation”.
             Ports
             Input
             Input signal u(t). The Input Processing parameter and the number of inputs nu define the
             dimensions of the signal. Only the ARX model structure can have multiple inputs, with nu greater
             than 1.
Dependencies
To enable this port, set the Model Structure parameter to ARX, ARMAX, BJ, or OE.
2-70
                                                                        Recursive Polynomial Model Estimator
Measured output signal y(t). The Input Processing parameter defines the dimensions of the signal:
External signal that allows you to enable and disable estimation updates. If the signal value is:
• true — Estimate and output the parameter values for the time step.
• false — Do not estimate the parameter values, and output the most recent previously estimated
  value.
Dependencies
Reset parameter estimation to its initial conditions. The value of the External reset parameter
determines the trigger type. The trigger type dictates whether the reset occurs on a signal that is
rising, falling, either rising or falling, level, or on level hold.
Dependencies
To enable this port, select any option other than None in the External reset dropdown.
Data Types: single | double | Boolean | int8 | int16 | int32 | uint8 | uint16 | uint32
Initial parameter estimates, supplied from a source external to the block. The block uses this inport at
the beginning of the simulation or when you trigger an algorithm reset using the Reset signal.
For information on the contents of the InitialParameters bus object, see the Parameters port
description.
Dependencies
To enable this port, set History to Infinite and Initial Estimate to External.
Data Types: single | double
                                                                                                      2-71
2   Blocks
             Initial parameter covariances, supplied from a source external to the block. For details, see the
             Parameter Covariance Matrix parameter. The block uses this inport at the beginning of the
             simulation or when you trigger an algorithm reset using the Reset signal.
             Dependencies
             • History to Infinite
             • Estimation Method to Forgetting Factor or Kalman Filter
             • Initial Estimate to External
             Initial set of inputs when using finite-history (sliding-window) estimation, supplied from an external
             source.
             • If Model Structure is ARX, then the signal to this port must be a (W–1+max(nb)+max(nk))-by-nu
               matrix, where W is the window length and nu is the number of inputs. nb is the vector of B(q)
               polynomial orders and nk is the vector of input delays.
             • If Model Structure is OE, then the signal to this port must be a (W–1+nb+nk)-by-1 vector, where
               W is the window length. nb is the vector of B(q) polynomial orders and nk is the vector of input
               delays.
The block uses this inport at the beginning of the simulation or whenever the Reset signal triggers.
             If the initial buffer is set to 0 or does not contain enough information, you see a warning message
             during the initial phase of your estimation. The warning should clear after a few cycles. The number
             of cycles it takes for sufficient information to be buffered depends upon the order of your polynomials
             and your input delays. If the warning persists, you should evaluate the content of your signals.
             Dependencies
             • History to Finite
             • Model Structure to ARX or OE
             • Initial Estimate to External
             Initial set of output measurements when using finite-history (sliding-window) estimation, supplied
             from an external source.
             • If Model Structure is AR or ARX, then the signal to this port must be a (W+na)-by-1 vector, where
               W is the window length and na is the polynomial order of A(q).
             • If Model Structure is OE, then the signal to this port must be a (W+nf)-by-1 vector, where W is
               the window length and nf is the polynomial order of F(q).
2-72
                                                                     Recursive Polynomial Model Estimator
The block uses this inport at the beginning of the simulation or whenever the Reset signal triggers.
If the initial buffer is set to 0 or does not contain enough information, you see a warning message
during the initial phase of your estimation. The warning should clear after a few cycles. The number
of cycles it takes for sufficient information to be buffered depends upon the order of your polynomials
and your input delays. If the warning persists, you should evaluate the content of your signals.
Dependencies
• History to Finite
• Model Structure to AR, ARX, or OE
• Initial Estimate to External
Output
Estimated polynomial coefficients, returned as a bus. The bus contains an element for each of the A,
B, C, D, and F polynomials that correspond to the structure that you specify in Model Structure (see
“Model Structures” on page 2-69 ).
Each bus element is a vector signal containing the associated polynomial coefficients. For example,
the A element contains [1 a1(t) ... ana(t)].
Estimated C, D, and F values are constrained to be stable discrete-time polynomials. That is, these
polynomials all have roots within the unit circle. Estimated A and B polynomials are allowed to be
unstable.
Data Types: single | double
Dependencies
Parameter estimation error covariance P, returned as an N-by-N matrix, where N is the number of
parameters. For details, see the Output Parameter Covariance Matrix parameter.
                                                                                                   2-73
2   Blocks
Dependencies
             Parameters
             Model Structure
Model Parameters
                Specify the parameters that the block enables based on your choice of model structure and
                estimation method.
                • Specify the set of Number of Parameters () parameters that the block enables based on your
                  Model Structure. For instance, if your setting for Model Structure is AR, specify the
                  Number of Parameters in A(q) (na) parameter.
                • Specify the Input Delay (nk) parameter that the block enables when your model structure
                  uses a B(q) element.
                • Specify the Parameter Covariance Matrix if Estimation Method is Forgetting Factor
                  or Kalman Filter.
             • Internal — Specify initial parameter estimates internally to the block.
                • Specify the initial parameter values Initial () parameters that the block enables based on your
                  Model Structure and History. For instance, if your setting for Model Structure is AR and
                  History is Infinite, specify the Initial A(q) parameter.
                • Specify the Input Delay (nk) parameter that the block enables when your model structure
                  uses a B(q) element.
2-74
                                                                     Recursive Polynomial Model Estimator
   Specify the Number of Parameters () parameters that the block enables based on your Model
   Structure. Your setting for Model Structure and for the History parameter determines which
   signals to connect to the relevant ports:
Programmatic Use
Block Parameter: InitialEstimateSource
Type: character vector, string
Values: 'None', 'Internal', 'External'
Default: 'None'
• Set History to Infinite, Model Structure to AR, ARX, ARMA, or ARMAX, and Initial Estimate to
  None or External.
• Set History to Finite, Model Structure to AR or ARX, and Initial Estimate to None or
  External.
Programmatic Use
Block Parameter: A0
Type: non-negative integer
Default: 1
For MISO systems using an ARX model structure, specify nb as a vector with as many elements as
there are inputs. Each element of this vector represents the order of the B(q) polynomial associated
with the corresponding input. For example, suppose that you have a two-input MISO system whose
                     B1     0 b11 0
B(q) elements are:       =             . The zero at the beginning of each polynomial represents a
                     B2     0 b21 b22
single input delay for each input (see the Initial B(q) parameter description). The trailing zero in B1
is for equalizing the length of the polynomials and has no impact on estimation. nb for each
                                                                                                   2-75
2   Blocks
             polynomial is equal to the number of estimated parameters following the initial zero, or 1 for input 1
             and 2 for input 2. Specify Number of Parameters in B(q) (nb) as [1 2], and Input Delay (nk) as
             [1 1].
             Dependencies
             • Set History to Infinite, Model Structure to ARX, ARMAX, BJ, or OE, and Initial Estimate to
               None or External.
             • Set History to Finite with Model Structure of ARX or OE and Initial Estimate to None or
               External.
             Programmatic Use
             Block Parameter: B0
             Type: positive integer
             Default: 1
             To enable this parameter, set History to Infinite, Model Structure to ARMA, ARMAX, or BJ, and
             Initial Estimate to None or External
             Programmatic Use
             Block Parameter: C0
             Type: positive integer
             Default: 1
             To enable this parameter, set History to Infinite, Model Structure to BJ, and Initial Estimate to
             None or External.
             Programmatic Use
             Block Parameter: D0
             Type: positive integer
             Default: 1
2-76
                                                                      Recursive Polynomial Model Estimator
Dependencies
To enable this parameter, set Initial Estimate to None or External and either:
• History to Infinite, Model Structure to OE or BJ, and Initial Estimate to None or External
• History to Finite, Model Structure to OE, and Initial Estimate to None or External
.
Programmatic Use
Block Parameter: F0
Type: positive integer
Default: 1
Specify the input delay as an integer representing the number of time steps that occur before the
input affects the output. This delay is also called the dead time in the system. The block encodes the
input delay as fixed leading zeros of the B(q) polynomial. For more information, see the B(q)
parameter description.
For MISO systems with ARX model structure, specify nk as a vector with elements specifying the
delay for each input. This vector is of length nu, where nu is the number of inputs.
For example, suppose that you have a two-input MISO system whose B(q) elements are:
 B1      0 b11 b12
     =              . The zeros at the beginning of the polynomials represent a single-sample delay for
 B2      0 0 b21
the first input, and a two-sample delay for the second input (see the Initial B(q) parameter
description). nb for each polynomial is equal to the number of estimated parameters following the
initial zeros, or 2 for input 1 and 1 for input 2. Specify Input Delay (nk) as [1 2], and Number of
Parameters in B(q) (nb) as [2 1].
Dependencies
• Set History to Infinite, Model Structure to ARX, ARMAX, OE, or BJ, and Initial Estimate to
  None or External.
• Set History to Finite, Model Structure to ARX or OE, and Initial Estimate to None or
  External.
Programmatic Use
Block Parameter: nk
Type: non-negative integer vector
Default: 1
• Real positive scalar, α — Covariance matrix is an N-by-N diagonal matrix, with α as the diagonal
  elements.
• Vector of real positive scalars, [α(a),α(b),α(c), α(d), α(f)] — Covariance matrix is an N-by-N
  diagonal matrix, with [α(a),α(b),α(c),α(d), α(f)] as the diagonal elements. α(a) is a vector of the
                                                                                                    2-77
2   Blocks
                covariance for each coefficient of the A polynomial. Similarly, α(b), α(c), α(d) and α(f) are vectors
                containing the covariance of the coefficients of the B, C, D and F polynomials, respectively.
             • N-by-N symmetric positive-definite matrix.
                • AR — N = na
                •                     Nu
                    ARX — N = na +    ∑    nbi
                                     i=1
                • ARMA — N = na + nc
                • ARMAX — N = na + nb + nc
                • OE — N = nb + nf
                • BJ — N = nb + nc + nd + nf
Dependencies
             • History to Infinite
             • Initial Estimate to None or Internal
             • Estimation Method to Forgetting Factor or Kalman Filter
             The block uses this parameter at the beginning of the simulation or whenever the Reset signal
             triggers.
             Programmatic Use
             Block Parameter: P0
             Type: scalar, vector, or matrix
             Default: 1e4
Specify the initial estimate of the A(q) polynomial coefficients as a row vector of length na+1.
             Programmatic Use
             Block Parameter: A0
             Type: real vector
             Default: [1 eps]
2-78
                                                                      Recursive Polynomial Model Estimator
Specify the initial estimate of the B(q) polynomial coefficients as a row vector of length nb+nk. For
multiple-input models, specify a matrix where the ith row corresponds to the ith input.
The block counts the leading zeros in B(q) and interprets them as input delay nk. Those zeros are
fixed throughout the estimation. nb is the number of elements after the first nonzero element in B(q).
The block estimates the value of these nb elements.
For example:
Programmatic Use
Block Parameter: B0
Type: real vector or matrix
Default: [0 eps]
Specify the initial estimate of the C(q) polynomial coefficients as a row vector of length nc+1.
The coefficients must define a stable discrete-time polynomial, that is, have all polynomial roots
within the unit circle.
Dependencies
• History to Infinite
• Model Structure to ARMA, ARMAX, or BJ
• Initial Estimate to Internal
Programmatic Use
Block Parameter: C0
Type: real vector
Default: [1 eps]
Specify the initial estimate of the D(q) polynomial coefficients as a row vector of length nd+1.
                                                                                                     2-79
2   Blocks
             The coefficients must define a stable discrete-time polynomial, that is, have all polynomial roots
             within the unit circle.
             Dependencies
             • History to Infinite
             • Model Structure to BJ
             • Initial Estimate to Internal
             Programmatic Use
             Block Parameter: D0
             Type: real vector
             Default: [1 eps]
Specify the initial estimate of the F(q) polynomial coefficients as a row vector of length nf+1.
             The coefficients must define a stable discrete-time polynomial, that is, have all polynomial roots
             within the unit circle.
             Dependencies
             • Model Structure to OE or to BJ
             • Initial Estimate to Internal
             Programmatic Use
             Block Parameter: F0
             Type: real vector
             Default: [1 eps]
             Specify initial values of the inputs buffer when using finite-history (sliding window) estimation. The
             buffer dimensions accommodate the specified window length, the regressors associated with
             polynomials within that window, the input delays, and the number of inputs. These elements drive a
             matrix size of:
             where W is the window length and nu is the number of inputs. nb is the vector of B(q) polynomial
             orders and nk is the vector of input delays.
When the initial value is set to 0, the block populates the buffer with zeros.
2-80
                                                                       Recursive Polynomial Model Estimator
If the initial buffer is set to 0 or does not contain enough information, you see a warning message
during the initial phase of your estimation. The warning should clear after a few cycles. The number
of cycles it takes for sufficient information to be buffered depends upon the order of your polynomials
and your input delays. If the warning persists, you should evaluate the content of your signals.
The block uses this parameter at the beginning of the simulation or whenever the Reset signal
triggers.
Dependencies
• History to Finite
• Model Structure to ARX or OE
• Initial Estimate to Internal
Programmatic Use
Block Parameter: InitialInputs
Type: real matrix
Default: 0
Specify initial values of the measured outputs buffer when using finite-history (sliding-window)
estimation. The buffer dimensions accommodate the specified window length and the regressors
associated with the polynomials within that window.
• AR or ARX model structure — (W+na)-by-1 vector, where W is the window length and na is the
  polynomial order of A(q).
• OE model structure — (W+nf)-by-1 vector, where W is the window length and nf is the polynomial
  order of F(q).
When the initial value is set to 0, the block populates the buffer with zeros.
If the initial buffer is set to 0 or does not contain enough information, you see a warning message
during the initial phase of your estimation. The warning should clear after a few cycles. The number
of cycles it takes for sufficient information to be buffered depends upon the order of your polynomials
and your input delays. If the warning persists, you should evaluate the content of your signals.
The block uses this parameter at the beginning of the simulation or whenever the Reset signal
triggers.
Dependencies
• History to Finite
• Model Structure to AR, ARX, or OE
• Initial Estimate to Internal
                                                                                                     2-81
2   Blocks
             Programmatic Use
             Block Parameter: InitialOutputs
             Type: real vector
             Default: 0
             Specifying frame-based data adds an extra dimension of M to some of your data inports and outports,
             where M is the number of time steps in a frame. These ports are:
             • Inputs
             • Output
             • Error
             For more information, see the port descriptions in “Ports” on page 2-70.
             Programmatic Use
             Block Parameter: InputProcessing
             Type: character vector, string
             Values: 'Sample-based', 'Frame-based'
             Default: 'Sample-based'
             Specify the data sample time, whether by individual samples for sample-based processing (ts), or by
             frames for frame-based processing (tf = Mts), where M is the frame length. When you set Sample
             Time to its default value of –1, the block inherits its ts or tf based on the signal.
Algorithm Options
The History parameter determines what type of recursive algorithm you use:
2-82
                                                                    Recursive Polynomial Model Estimator
• Infinite — Algorithms in this category aim to produce parameter estimates that explain all data
  since the start of the simulation. These algorithms retain the history in a data summary. The block
  maintains this summary within a fixed amount of memory that does not grow over time.
   The block provides multiple algorithms of the Infinite type. Selecting this option enables the
   Estimation Method parameter with which you specify the algorithm.
• Finite — Algorithms in this category aim to produce parameter estimates that explain only a
  finite number of past data samples. The block uses all of the data within a finite window, and
  discards data once that data is no longer within the window bounds. This method is also called
  sliding-window estimation.
   The block provides one algorithm of the Finite type. You can use this option only with the AR,
   ARX, and OE model structures.
For more information on recursive estimation methods, see “Recursive Algorithms for Online
Parameter Estimation”
Programmatic Use
Block Parameter: History
Type: character vector, string
Values: 'Infinite', 'Finite'
Default: 'Infinite'
The Window Length parameter determines the number of time samples to use for the finite-history
(sliding-window) estimation method. Choose a window size that balances estimation performance
with computational and memory burden. Sizing factors include the number and time variance of the
parameters in your model. Always specify Window Length in samples, even if you are using frame-
based input processing.
Window Length must be greater than or equal to the number of estimated parameters.
Suitable window length is independent of whether you are using sample-based or frame-based input
processing. However, when using frame-based processing, Window Length must be greater than or
equal to the number of samples (time steps) contained in the frame.
Dependencies
Specify the estimation algorithm when performing infinite-history estimation. When you select any of
these methods, the block enables additional related parameters.
                                                                                                  2-83
2   Blocks
             Forgetting factor and Kalman filter algorithms are more computationally intensive than gradient and
             normalized gradient methods. However, these more intensive methods have better convergence
             properties than the gradient methods. For more information about these algorithms, see “Recursive
             Algorithms for Online Parameter Estimation”.
             Programmatic Use
             Block Parameter: EstimationMethod
             Type: character vector, string
             Values: 'Forgetting Factor','Kalman Filter','Normalized Gradient','Gradient'
             Default: 'Forgetting Factor'
             The forgetting factor λ specifies if and how much old data is discounted in the estimation. Suppose
             that the system remains approximately constant over T0 samples. You can choose λ such that:
                         1
                 T0 =
                        1−λ
             To enable this parameter, set History to Infinite and Estimation Method to Forgetting
             Factor.
             Programmatic Use
             Block Parameter: AdaptationParameter
             Type: scalar
             Values: (0 1] range
             Default: 1
             Process Noise Covariance — Process noise covariance for Kalman filter estimation
             method
             1 (default) | nonnegative scalar | vector of nonnegative scalars | symmetric positive semidefinite
             matrix
             Process Noise Covariance prescribes the elements and structure of the noise covariance matrix for
             the Kalman filter estimation. Using N as the number of parameters to estimate, specify the Process
             Noise Covariance as one of the following:
             • Real nonnegative scalar, α — Covariance matrix is an N-by-N diagonal matrix, with α as the
               diagonal elements.
             • Vector of real nonnegative scalars, [α1,...,αN] — Covariance matrix is an N-by-N diagonal matrix,
               with [α1,...,αN] as the diagonal elements.
             • N-by-N symmetric positive semidefinite matrix.
             The Kalman filter algorithm treats the parameters as states of a dynamic system and estimates these
             parameters using a Kalman filter. Process Noise Covariance is the covariance of the process noise
             acting on these parameters. Zero values in the noise covariance matrix correspond to constant
2-84
                                                                    Recursive Polynomial Model Estimator
coefficients, or parameters. Values larger than 0 correspond to time-varying parameters. Use large
values for rapidly changing parameters. However, expect the larger values to result in noisier
parameter estimates. The default value is 1.
Dependencies
To enable this parameter, set History to Infinite and Estimation Method to Kalman Filter.
Programmatic Use
Block Parameter: AdaptationParameter
Type: scalar, vector, matrix
Default: 1
The adaptation gain γ scales the influence of new measurement data on the estimation results for the
gradient and normalized gradient methods. When your measurements are trustworthy, or in other
words have a high signal-to-noise ratio, specify a larger value for γ. However, setting γ too high can
cause the parameter estimates to diverge. This divergence is possible even if the measurements are
noise free.
When Estimation Method is NormalizedGradient, Adaptation Gain should be less than 2. With
either gradient method, if errors are growing in time (in other words, estimation is diverging), or
parameter estimates are jumping around frequently, consider reducing Adaptation Gain.
Dependencies
To enable this parameter, set History to Infinite and Estimation Method to Normalized
Gradient or to Gradient.
Programmatic Use
Block Parameter: AdaptationParameter
Type: scalar
Default: 1
Normalization Bias — Bias for adaptation gain scaling for normalized gradient estimation
method
eps (default) | nonnegative scalar
The normalized gradient algorithm scales the adaptation gain at each step by the square of the two-
norm of the gradient vector. If the gradient is close to zero, the near-zero denominator can cause
jumps in the estimated parameters. Normalization Bias is the term introduced to the denominator
to prevent these jumps. Increase Normalization Bias if you observe jumps in estimated parameters.
Dependencies
To enable this parameter, set History to Infinite and Estimation Method to Normalized
Gradient.
Programmatic Use
Block Parameter: NormalizationBias
Type: scalar
Default: eps
                                                                                                  2-85
2   Blocks
Block Options
             Use the Error outport signal to validate the estimation. For a given time step t, the estimation error
             e(t) is calculated as:
             where y(t) is the measured output that you provide, and yest(t) is the estimated output using the
             regressors H(t) and parameter estimates θ(t-1).
             Programmatic Use
             Block Parameter: OutputError
             Type: character vector, string
             Values: 'off','on',
             Default: 'off'
             Use the Covariance outport signal to examine parameter estimation uncertainty. The software
             computes parameter covariance P assuming that the residuals, e(t), are white noise, and the variance
             of these residuals is 1.
             The interpretation of P depends on the estimation approach you specify in History and Estimation
             Method as follows:
             Programmatic Use
             Block Parameter: OutputP
             Type: character vector, string
             Values: 'off','on'
             Default: 'off'
             Use the Enable signal to provide a control signal that enables or disables parameter estimation. The
             block estimates the parameter values for each time step that parameter estimation is enabled. If you
2-86
                                                                       Recursive Polynomial Model Estimator
disable parameter estimation at a given step, t, then the software does not update the parameters for
that time step. Instead, the block output contains the last estimated parameter values.
• Your regressors or output signal become too noisy, or do not contain information at some time
  steps
• Your system enters a mode where the parameter values do not change in time
Programmatic Use
Block Parameter: AddEnablePort
Type: character vector, string
Values: 'off','on'
Default: 'off'
Set the External reset parameter to both add a Reset inport and specify the inport signal condition
that triggers a reset of algorithm states to their specified initial values. Reset the estimation, for
example, if parameter covariance is becoming too large because of lack of either sufficient excitation
or information in the measured signals. The External reset parameter determines the timing for the
reset.
Suppose that you reset the block at a time step, t. If the block is enabled at t, the software uses the
initial parameter values specified in Initial Estimate to estimate the parameter values. In other
words, at t, the block performs a parameter update using the initial estimate and the current values
of the inports.
If the block is disabled at t and you reset the block, the block output contains the values specified in
Initial Estimate.
When you choose any option other than None, the software adds a Reset inport to the block. You
provide the reset control input signal to this inport.
Programmatic Use
Block Parameter: ExternalReset
Type: character vector, string
                                                                                                     2-87
2   Blocks
             References
             [1] Ljung, L. System Identification: Theory for the User. Upper Saddle River, NJ: Prentice-Hall PTR,
                     1999, pp. 363–369.
             [2] Zhang, Q. "Some Implementation Aspects of Sliding Window Least Squares Algorithms." IFAC
                     Proceedings. Vol. 33, Issue 15, 2000, pp. 763–768.
             Extended Capabilities
             C/C++ Code Generation
             Generate C and C++ code using Simulink® Coder™.
             See Also
             Kalman Filter | Recursive Least Squares Estimator
             Topics
             “Estimate Parameters of System Using Simulink Recursive Estimator Block”
             “Online Recursive Least Squares Estimation”
             “Preprocess Online Parameter Estimation Data in Simulink”
             “Validate Online Parameter Estimation Results in Simulink”
             “Generate Online Parameter Estimation Code in Simulink”
             “Recursive Algorithms for Online Parameter Estimation”
Introduced in R2014a
2-88
                                                                                  Unscented Kalman Filter
Description
The Unscented Kalman Filter block estimates the states of a discrete-time nonlinear system using the
discrete-time unscented Kalman filter algorithm.
Consider a plant with states x, input u, output y, process noise w, and measurement noise v. Assume
that you can represent the plant as a nonlinear system.
Using the state transition and measurement functions of the system and the unscented Kalman filter
algorithm, the block produces state estimates x for the current time step. For information about the
algorithm, see “Extended and Unscented Kalman Filter Algorithms for Online State Estimation”.
You create the nonlinear state transition function and measurement functions for the system and
specify these functions in the block. The block supports state estimation of a system with multiple
sensors that are operating at different sampling rates. You can specify up to five measurement
functions, each corresponding to a sensor in the system. For more information, see “State Transition
and Measurement Functions” on page 2-101.
Ports
Input
Measured system outputs corresponding to each measurement function that you specify in the block.
The number of ports equals the number of measurement functions in your system. You can specify up
to five measurement functions. For example, if your system has two sensors, you specify two
measurement functions in the block. The first port y1 is available by default. When you click Apply,
the software generates port y2 corresponding to the second measurement function.
Specify the ports as N-dimensional vectors, where N is the number of quantities measured by the
corresponding sensor. For example, if your system has one sensor that measures the position and
                                                                                                   2-89
2   Blocks
             velocity of an object, then there is only one port y1. The port is specified as a 2-dimensional vector
             with values corresponding to position and velocity.
             Dependencies
             The first port y1 is available by default. Ports y2 to y5 are generated when you click Add
             Measurement, and click Apply.
             Data Types: single | double
             Additional optional input argument to the state transition function f other than the state x and
             process noise w. For information about state transition functions see, “State Transition and
             Measurement Functions” on page 2-101.
             Suppose that your system has nonadditive process noise, and the state transition function f has the
             following form:
x(k+1) = f(x(k),w(k),StateTransitionFcnInputs).
             Here k is the time step, and StateTransitionFcnInputs is an additional input argument other
             than x and w.
             If you create f using a MATLAB function (.m file), the software generates the port
             StateTransitionFcnInputs when you click Apply. You can specify the inputs to this port as a scalar,
             vector, or matrix.
             If your state transition function has more than one additional input, use a Simulink Function block to
             specify the function. When you use a Simulink Function block, you provide the additional inputs
             directly to the Simulink Function block using Inport blocks. No input ports are generated for the
             additional inputs in the Unscented Kalman Filter block.
             Dependencies
This port is generated only if both of the following conditions are satisfied:
             • You specify f in Function using a MATLAB function, and f is on the MATLAB path.
             • f requires only one additional input argument apart from x and w.
             MeasurementFcn1Inputs,MeasurementFcn2Inputs,MeasurementFcn3Inputs,Measurement
             Fcn4Inputs,MeasurementFcn5Inputs — Additional optional input argument to each
             measurement function
             scalar | vector | matrix
             Additional optional inputs to the measurement functions other than the state x and measurement
             noise v. For information about measurement functions see, “State Transition and Measurement
             Functions” on page 2-101.
             MeasurementFcn1Inputs corresponds to the first measurement function that you specify, and so
             on. For example, suppose that your system has three sensors and nonadditive measurement noise,
             and the three measurement functions h1, h2, and h3 have the following form:
2-90
                                                                                 Unscented Kalman Filter
y1[k] = h1(x[k],v[k],MeasurementFcn1Inputs)
y2[k] = h2(x[k],v[k],MeasurementFcn2Inputs)
y3[k] = h3(x[k],v[k])
Here k is the time step, and MeasurementFcn1Inputs and MeasurementFcn2Inputs are the
additional input arguments to h1 and h2.
If you specify h1, h2, and h3 using MATLAB functions (.m files) in Function, the software generates
ports MeasurementFcn1Inputs and MeasurementFcn2Inputs when you click Apply. You can
specify the inputs to these ports as scalars, vectors, or matrices.
If your measurement functions have more than one additional input, use Simulink Function blocks to
specify the functions. When you use a Simulink Function block, you provide the additional inputs
directly to the Simulink Function block using Inport blocks. No input ports are generated for the
additional inputs in the Unscented Kalman Filter block.
Dependencies
• You specify h in Function using a MATLAB function, and h is on the MATLAB path.
• h requires only one additional input argument apart from x and v.
Time-varying process noise covariance, specified as a scalar, vector, or matrix depending on the value
of the Process noise parameter:
• Process noise is Additive — Specify the covariance as a scalar, an Ns-element vector, or an Ns-
  by-Ns matrix, where Ns is the number of states of the system. Specify a scalar if there is no cross-
  correlation between process noise terms, and all the terms have the same variance. Specify a
  vector of length Ns, if there is no cross-correlation between process noise terms, but all the terms
  have different variances.
• Process noise is Nonadditive — Specify the covariance as a W-by-W matrix, where W is the
  number of process noise terms in the state transition function.
Dependencies
This port is generated if you specify the process noise covariance as Time-Varying. The port appears
when you click Apply.
Data Types: single | double
Time-varying measurement noise covariances for up to five measurement functions of the system,
specified as matrices. The sizes of the matrices depend on the value of the Measurement noise
parameter for the corresponding measurement function:
                                                                                                  2-91
2   Blocks
             • Measurement noise is Additive — Specify the covariance as an N-by-N matrix, where N is the
               number of measurements of the system.
             • Measurement noise is Nonadditive — Specify the covariance as a V-by-V matrix, where V is
               the number of measurement noise terms in the corresponding measurement function.
Dependencies
             A port is generated if you specify the measurement noise covariance as Time-Varying for the
             corresponding measurement function. The port appears when you click Apply.
             Data Types: single | double
             Suppose that measured output data is not available at all time points at the port y1 that corresponds
             to the first measurement function. Use a signal value other than 0 at the Enable1 port to enable the
             correction of estimated states when measured data is available. Specify the port value as 0 when
             measured data is not available. Similarly, if measured output data is not available at all time points at
             the port yi for the ith measurement function, specify the corresponding port Enablei as a value other
             than 0.
             Dependencies
             A port corresponding to a measurement function is generated if you select Add Enable port for that
             measurement function. The port appears when you click Apply.
             Data Types: single | double | Boolean
Output
             Estimated states, returned as a vector of size Ns, where Ns is the number of states of the system. To
             access the individual states, use the Selector block.
             When the Use the current measurements to improve state estimates parameter is selected, the
             block outputs the corrected state estimate x [k k] at time step k, estimated using measured outputs
             until time k. If you clear this parameter, the block returns the predicted state estimate x [k k − 1] for
             time k, estimated using measured output until a previous time k-1. Clear this parameter if your filter
             is in a feedback loop and there is an algebraic loop in your Simulink model.
             Data Types: single | double
             State estimation error covariance, returned as an Ns-by-Ns matrix, where Ns is the number of states
             of the system. To access the individual covariances, use the Selector block.
             Dependencies
             This port is generated if you select Output state estimation error covariance in the System
             Model tab, and click Apply.
2-92
                                                                                 Unscented Kalman Filter
Parameters
System Model Tab
State Transition
The state transition function calculates the Ns-element state vector of the system at time step k+1,
given the state vector at time step k. Ns is the number of states of the nonlinear system. You create
the state transition function and specify the function name in Function. For example, if
vdpStateFcn.m is the state transition function that you created and saved, specify Function as
vdpStateFcn.
The inputs to the function you create depend on whether you specify the process noise as additive or
nonadditive in Process noise.
• Process noise is Additive — The state transition function f specifies how the states evolve as a
  function of state values at previous time step:
x(k+1) = f(x(k),Us1(k),...,Usn(k)),
   where x(k) is the estimated state at time k, and Us1,...,Usn are any additional input
   arguments required by your state transition function, such as system inputs or the sample time. To
   see an example of a state transition function with additive process noise, type edit
   vdpStateFcn at the command line.
• Process noise is Nonadditive — The state transition function also specifies how the states
  evolve as a function of the process noise w:
x(k+1) = f(x(k),w(k),Us1(k),...,Usn(k)).
For more information, see “State Transition and Measurement Functions” on page 2-101.
You can create f using a Simulink Function block or as a MATLAB function (.m file).
• You can use a MATLAB function only if f has one additional input argument Us1 other than x and
  w.
x(k+1) = f(x(k),w(k),Us1(k))
Programmatic Use
Block Parameter: StateTransitionFcn
Type: character vector, string
Default: 'myStateTransitionFcn'
                                                                                                  2-93
2   Blocks
             • Additive — Process noise w is additive, and the state transition function f that you specify in
               Function has the following form:
x(k+1) = f(x(k),Us1(k),...,Usn(k)),
                where x(k) is the estimated state at time k, and Us1,...,Usn are any additional input
                arguments required by your state transition function.
             • Nonadditive — Process noise is nonadditive, and the state transition function specifies how the
               states evolve as a function of the state and process noise at the previous time step:
x(k+1) = f(x(k),w(k),Us1(k),...,Usn(k)).
             Programmatic Use
             Block Parameter: HasAdditiveProcessNoise
             Type: character vector
             Values: 'Additive', 'Nonadditive'
             Default: 'Additive'
             Time-invariant process noise covariance, specified as a scalar, vector, or matrix depending on the
             value of the Process noise parameter:
             • Process noise is Additive — Specify the covariance as a scalar, an Ns-element vector, or an Ns-
               by-Ns matrix, where Ns is the number of states of the system. Specify a scalar if there is no cross-
               correlation between process noise terms and all the terms have the same variance. Specify a
               vector of length Ns, if there is no cross-correlation between process noise terms but all the terms
               have different variances.
             • Process noise is Nonadditive — Specify the covariance as a W-by-W matrix, where W is the
               number of process noise terms.
             If the process noise covariance is time-varying, select Time-varying. The block generates input port
             Q to specify the time-varying covariance.
             Dependencies
             This parameter is enabled if you do not specify the process noise as Time-Varying.
             Programmatic Use
             Block Parameter: ProcessNoise
             Type: character vector, string
             Default: '1'
             If you select this parameter, the block includes an additional input port Q to specify the time-varying
             process noise covariance.
2-94
                                                                                  Unscented Kalman Filter
Programmatic Use
Block Parameter: HasTimeVaryingProcessNoise
Type: character vector
Values: 'off', 'on'
Default: 'off'
Initialization
Initial state estimate value, specified as an Ns-element vector, where Ns is the number of states in the
system. Specify the initial state values based on your knowledge of the system.
Programmatic Use
Block Parameter: InitialState
Type: character vector, string
Default: '0'
State estimation error covariance, specified as a scalar, an Ns-element vector, or an Ns-by-Ns matrix,
where Ns is the number of states of the system. If you specify a scalar or vector, the software creates
an Ns-by-Ns diagonal matrix with the scalar or vector elements on the diagonal.
Specify a high value for the covariance when you do not have confidence in the initial state values
that you specify in Initial state.
Programmatic Use
Block Parameter: InitialStateCovariance
Type: character vector, string
Default: '1'
The unscented Kalman filter algorithm treats the state of the system as a random variable with a
mean state value and variance. To compute the state and its statistical properties at the next time
step, the algorithm first generates a set of state values distributed around the mean value by using
the unscented transformation. These generated state values are called sigma points. The algorithm
uses each of the sigma points as an input to the state transition and measurement functions to get a
new set of transformed state points and measurements. The transformed points are used to compute
the state and state estimation error covariance value at the next time step.
The spread of the sigma points around the mean state value is controlled by two parameters Alpha
and Kappa. A third parameter, Beta, impacts the weights of the transformed points during state and
measurement covariance calculations:
• Alpha — Determines the spread of the sigma points around the mean state value. Specify as a
  scalar value between 0 and 1 (0 < Alpha <= 1). It is usually a small positive value. The spread of
  sigma points is proportional to Alpha. Smaller values correspond to sigma points closer to the
  mean state.
                                                                                                   2-95
2   Blocks
             • Kappa — A second scaling parameter that is typically set to 0. Smaller values correspond to
               sigma points closer to the mean state. The spread is proportional to the square-root of Kappa.
             • Beta — Incorporates prior knowledge of the distribution of the state. For Gaussian distributions,
               Beta = 2 is optimal.
             If you know the distribution of state and state covariance, you can adjust these parameters to capture
             the transformation of higher-order moments of the distribution. The algorithm can track only a single
             peak in the probability distribution of the state. If there are multiple peaks in the state distribution of
             your system, you can adjust these parameters so that the sigma points stay around a single peak. For
             example, choose a small Alpha to generate sigma points close to the mean state value.
             Characterization of the state distribution that is used to adjust weights of transformed sigma points,
             specified as a scalar value greater than or equal to 0. For Gaussian distributions, Beta = 2 is the
             optimal choice.
             Spread of sigma points around mean state value, specified as a scalar value between 0 and 3 (0 <=
             Kappa <= 3). Kappa is typically specified as 0. Smaller values correspond to sigma points closer to
             the mean state. The spread is proportional to the square root of Kappa. For more information, see
             the description for Alpha.
             Programmatic Use
             Block Parameter: Kappa
             Type: character vector, string
             Default: '0'
Measurement
             The measurement function calculates the N-element output measurement vector of the nonlinear
             system at time step k, given the state vector at time step k. You create the measurement function and
             specify the function name in Function. For example, if vdpMeasurementFcn.m is the measurement
             function that you created and saved, specify Function as vdpMeasurementFcn.
2-96
                                                                               Unscented Kalman Filter
The inputs to the function you create depend on whether you specify the measurement noise as
additive or nonadditive in Measurement noise.
y(k) = h(x(k),Um1(k),...,Umn(k)),
   where y(k) and x(k) are the estimated output and estimated state at time k, and Um1,...,Umn
   are any optional input arguments required by your measurement function. For example, if you are
   using a sensor for tracking an object, an additional input could be the sensor position.
   To see an example of a measurement function with additive process noise, type edit
   vdpMeasurementFcn at the command line.
• Measurement noise is Nonadditive— The measurement function also specifies how the output
  measurement evolves as a function of the measurement noise v:
y(k) = h(x(k),v(k),Um1(k),...,Umn(k)).
   To see an example of a measurement function with nonadditive process noise, type edit
   vdpMeasurementNonAdditiveNoiseFcn.
For more information, see “State Transition and Measurement Functions” on page 2-101.
You can create h using a Simulink Function block or as a MATLAB function (.m file).
• You can use a MATLAB function only if h has one additional input argument Um1 other than x and
  v.
y[k] = h(x[k],v[k],Um1(k))
If you have multiple sensors in your system, you can specify multiple measurement functions. You can
specify up to five measurement functions using the Add Measurement button. To remove
measurement functions, use Remove Measurement.
Programmatic Use
Block Parameter: MeasurementFcn1, MeasurementFcn2, MeasurementFcn3,
MeasurementFcn4, MeasurementFcn5
Type: character vector, string
Default: 'myMeasurementFcn'
• Additive — Measurement noise v is additive, and the measurement function h that you specify
  in Function has the following form:
                                                                                                2-97
2   Blocks
y(k) = h(x(k),Um1(k),...,Umn(k)),
                where y(k) and x(k) are the estimated output and estimated state at time k, and Um1,...,Umn
                are any optional input arguments required by your measurement function.
             • Nonadditive — Measurement noise is nonadditive, and the measurement function specifies how
               the output measurement evolves as a function of the state and measurement noise:
y(k) = h(x(k),v(k),Um1(k),...,Umn(k)).
             Programmatic Use
             Block Parameter: HasAdditiveMeasurementNoise1, HasAdditiveMeasurementNoise2,
             HasAdditiveMeasurementNoise3, HasAdditiveMeasurementNoise4,
             HasAdditiveMeasurementNoise5
             Type: character vector
             Values: 'Additive', 'Nonadditive'
             Default: 'Additive'
             Time-invariant measurement noise covariance, specified as a matrix. The size of the matrix depends
             on the value of the Measurement noise parameter:
             • Measurement noise is Additive — Specify the covariance as an N-by-N matrix, where N is the
               number of measurements of the system.
             • Measurement noise is Nonadditive — Specify the covariance as a V-by-V matrix, where V is
               the number of measurement noise terms.
             If the measurement noise covariance is time-varying, select Time-varying. The block generates input
             port Ri to specify the time-varying covariance for the ith measurement function.
             Dependencies
             This parameter is enabled if you do not specify the process noise as Time-Varying.
             Programmatic Use
             Block Parameter: MeasurementNoise1, MeasurementNoise2, MeasurementNoise3,
             MeasurementNoise4, MeasurementNoise5
             Type: character vector, string
             Default: '1'
             If you select this parameter for the measurement noise covariance of the first measurement function,
             the block includes an additional input port R1. You specify the time-varying measurement noise
             covariance in R1. Similarly, if you select Time-varying for the ith measurement function, the block
             includes an additional input port Ri to specify the time-varying measurement noise covariance for
             that function.
             Programmatic Use
             Block Parameter: HasTimeVaryingMeasurementNoise1,
             HasTimeVaryingMeasurementNoise2, HasTimeVaryingMeasurementNoise3,
             HasTimeVaryingMeasurementNoise4, HasTimeVaryingMeasurementNoise5
2-98
                                                                                  Unscented Kalman Filter
Add Enable Port — Enable correction of estimated states only when measured data is
available
off (default) | on
Suppose that measured output data is not available at all time points at the port y1 that corresponds
to the first measurement function. Select Add Enable port to generate an input port Enable1. Use a
signal at this port to enable the correction of estimated states only when measured data is available.
Similarly, if measured output data is not available at all time points at the port yi for the ith
measurement function, select the corresponding Add Enable port.
Programmatic Use
Block Parameter: HasMeasurementEnablePort1, HasMeasurementEnablePort2,
HasMeasurementEnablePort3, HasMeasurementEnablePort4, HasMeasurementEnablePort5
Type: character vector
Values: 'off', 'on'
Default: 'off'
Settings
When this parameter is selected, the block outputs the corrected state estimate x [k k] at time step k,
estimated using measured outputs until time k. If you clear this parameter, the block returns the
predicted state estimate x [k k − 1] for time k, estimated using measured output until a previous time
k-1. Clear this parameter if your filter is in a feedback loop and there is an algebraic loop in your
Simulink model.
Programmatic Use
Block Parameter: UseCurrentEstimator
Type: character vector
Values: 'off', 'on'
Default: 'on'
Output state estimation error covariance — Output state estimation error covariance
off (default) | on
If you select this parameter, a state estimation error covariance output port P is generated in the
block.
Programmatic Use
Block Parameter: OutputStateCovariance
Type: character vector
Values: 'off','on'
Default: 'off'
Use this parameter to specify the data type for all block parameters.
                                                                                                      2-99
2   Blocks
             Programmatic Use
             Block Parameter: DataType
             Type: character vector
             Values: 'single', 'double'
             Default: 'double'
             Block sample time, specified as a positive scalar. If the sample times of your state transition and
             measurement functions are different, select Enable multirate operation in the Multirate tab, and
             specify the sample times in the Multirate tab instead.
             Dependencies
             This parameter is available if in the Multirate tab, the Enable multirate operation parameter is
             off.
             Programmatic Use
             Block Parameter: SampleTime
             Type: character vector, string
             Default: '1'
Multirate Tab
             Enable multirate operation — Enable specification of different sample times for state
             transition and measurement functions
             off (default) | on
             Select this parameter if the sample times of the state transition and measurement functions are
             different. You specify the sample times in the Multirate tab, in Sample time.
             Programmatic Use
             Block Parameter: EnableMultirate
             Type: character vector
             Values: 'off', 'on'
             Default: 'off'
             If the sample times for state transition and measurement functions are different, specify Sample
             time. Specify the sample times for the measurement functions as positive integer multiples of the
             state transition sample time. The sample times you specify correspond to the following input ports:
             • Ports corresponding to state transition function — Additional input to state transition function
               StateTransitionFcnInputs and time-varying process noise covariance Q. The sample times of
               these ports must always equal the state transition function sample time, but can differ from the
               sample time of the measurement functions.
             • Ports corresponding to ith measurement function — Measured output yi, additional input to
               measurement function MeasurementFcniInputs, enable signal at port Enablei, and time-
               varying measurement noise covariance Ri. The sample times of these ports for the same
               measurement function must always be the same, but can differ from the sample time for the state
               transition function and other measurement functions.
2-100
                                                                                  Unscented Kalman Filter
Dependencies
This parameter is available if in the Multirate tab, the Enable multirate operation parameter is
on.
Programmatic Use
Block Parameter: StateTransitionFcnSampleTime, MeasurementFcn1SampleTime1,
MeasurementFcn1SampleTime2, MeasurementFcn1SampleTime3,
MeasurementFcn1SampleTime4, MeasurementFcn1SampleTime5
Type: character vector, string
Default: '1'
More About
State Transition and Measurement Functions
The algorithm computes the state estimates x of the nonlinear system using state transition and
measurement functions specified by you. You can specify up to five measurement functions, each
corresponding to a sensor in the system. The software lets you specify the noise in these functions as
additive or nonadditive.
• Additive Noise Terms — The state transition and measurements equations have the following
  form:
   Here f is a nonlinear state transition function that describes the evolution of states x from one
   time step to the next. The nonlinear measurement function h relates x to the measurements y at
   time step k. w and v are the zero-mean, uncorrelated process and measurement noises,
   respectively. These functions can also have additional optional input arguments that are denoted
   by us and um in the equations. For example, the additional arguments could be time step k or the
   inputs u to the nonlinear system. There can be multiple such arguments.
   Note that the noise terms in both equations are additive. That is, x(k+1) is linearly related to the
   process noise w(k), and y(k) is linearly related to the measurement noise v(k). For additive
   noise terms, you do not need to specify the noise terms in the state transition and measurement
   functions. The software adds the terms to the output of the functions.
• Nonadditive Noise Terms — The software also supports more complex state transition and
  measurement functions where the state x[k] and measurement y[k] are nonlinear functions of the
  process noise and measurement noise, respectively. When the noise terms are nonadditive, the
  state transition and measurements equation have the following form:
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using Simulink® Coder™.
The state transition and measurement functions that you specify must use only the MATLAB
commands and Simulink blocks that support code generation. For a list of blocks that support code
                                                                                                  2-101
2   Blocks
             generation, see “Simulink Built-In Blocks That Support Code Generation” (Simulink Coder). For a list
             of commands that support code generation, see “Functions and Objects Supported for C/C++ Code
             Generation” (MATLAB Coder).
             See Also
             Blocks
             Extended Kalman Filter | Kalman Filter | Particle Filter
             Functions
             extendedKalmanFilter | particleFilter | unscentedKalmanFilter
             Topics
             “What Is Online Estimation?”
             “Extended and Unscented Kalman Filter Algorithms for Online State Estimation”
             “Validate Online State Estimation in Simulink”
             “Troubleshoot Online State Estimation”
Introduced in R2017a
2-102