Accelerating the pace of engineering and science

# Documentation Center

• Trial Software

# estimate

Class: ssm

Estimate state-space model parameters

## Syntax

• EstMdl = estimate(Mdl,Y,params0) example
• EstMdl = estimate(Mdl,Y,params0,Name,Value) example
• [EstMdl,estParams,EstParamCov,logL,Output] = estimate(___) example

## Description

example

EstMdl = estimate(Mdl,Y,params0) estimates the parameters of Mdl using the Kalman filter and maximum likelihood, where:

• Mdl is a state-space model (ssm).

• Y is the observed response series.

• params0 is the vector of initial values for unknown parameters.

The software returns EstMdl, which is the estimated state-space model (ssm) that stores the estimated coefficient matrices and initial state means, covariances, and distributions.

• For explicitly specified state-space models (that is, you specified Mdl without using a parameter-to-matrix mapping function), the software estimates all NaN values in the coefficient matrices (Mdl.A, Mdl.B, Mdl.C, and Mdl.D) and the initial state means and covariance matrix (Mdl.Mean0 and Mdl.Cov0).

• For implicitly specified state-space models (that is, you specified Mdl using a parameter-to-matrix mapping function, which the software stores in Mdl.ParamMap), you define the model and the location of the unknown parameters using the parameter-to-matrix mapping function. Implicitly specify a state-space model to estimate complex models, impose parameter constraints, and estimate initial states. The parameter-to-mapping function can also accommodate additional output arguments.

example

EstMdl = estimate(Mdl,Y,params0,Name,Value) estimates the state-space model Mdl with additional options specified by one or more Name,Value pair arguments.

For example, pass in predictor data to include a linear regression component to the observation equation, control how the results appear in the Command Window, and indicate which estimation method to use for the parameter covariance matrix.

example

• estParams, a vector containing the estimated parameters

• EstParamCov, the estimated variance-covariance matrix of the estimated parameters

• logL, the optimized loglikelihood value

• Output, optimization diagnostic information structure

using any of the input arguments in the previous syntaxes.

## Tips

Constrained likelihood objective function maximization

• You can specify any combination of linear inequality, linear equality, and upper and lower bound constraints on the parameters.

• If a parameter is unbounded below, then set 'lb',-Inf.

• If a parameter is unbounded above, then set 'ub',Inf.

• It is good practice to avoid equality and inequality constraints during optimization. For example, if you want to constrain the parameter w to be positive, then implicitly specify the state-space model using a parameter-to-matrix mapping function, set w = exp(s) within the function, and use unconstrained optimization to estimate s. Subsequently, s can assume any real value, but w must be positive.

Predictors and corresponding coefficients

• The state-space model Mdl does not carry the predictors (Zt) nor their corresponding regression coefficients (β). The predictor series serve as observation deflators. Subsequently, the deflated data set is YtZtβ, where:

• , that is, Z is a T-byd matrix.

• zjt is the period t value of predictor j.

• β is a d-by-n matrix of regression coefficients.

• To include an overall mean to the observation model, include a column of 1s in Zt.

• If you want to account for predictor effects when you simulate (simulate), then you must deflate the observations manually. To deflate the observations, use

• If the state equation requires predictors, then expand the states by the constant 1 and the predictors.

• If the regression model is complex, then consider implicitly defining the state space model. For example, define the parameter-to-matrix mapping function using the following syntax pattern.

function [A,B,C,D,Mean0,Cov0,StateType,DeflateY] = ParamMap(params,Y,Z)
...
DeflateY = Y - exp(params(9) + params(10)*Z);
...
end

In this example, Y is the matrix of observations and Z is the matrix of predictors. The function returns DeflateY, which is the matrix of deflated observations. Specify Y and Z in the Workspace, and then pass ParamMap to ssm using the following syntax pattern.

Mdl = ssm(@(params)ParamMap(params,Y,Z))

This is also useful if each response series requires a distinct set of predictors.

• If the state equation requires predictors, then any one of the following:

• Expanding the states by including the constant 1 state.

• Expanding the states by including the predictors.

• If the model is time varying with respect the observed responses, then the software does not support including predictors. If the observation vectors among different periods vary in length, then the software cannot determine which coefficients to use to deflate the observed responses.

• The software accommodates missing data. Indicate missing data using NaN values in the observed responses (Y).

• It is good practice to check the convergence status of the optimization routine by displaying Output.ExitFlag.

• If the optimization algorithm does not converge, then you can increase the number of iterations using the 'Options' name-value pair argument.

• If the optimization algorithm does not converge, then consider using refine, which might help you obtain better initial parameter values for optimization.

## Input Arguments

expand all

### Mdl — State-space modelssm model

State-space model containing unknown parameters, specified as an ssm model returned by ssm.

### Y — Observed response datacell vector of numeric vectors | matrix

Observed response data to which Mdl is fit, specified as a cell vector of numeric vectors or a matrix.

• If Mdl is time invariant with respect to the observation equation, then Y is a T-by-n matrix, where each row corresponds to a period and each column corresponds to a particular observation in the model. Therefore, T is the sample size and m is the number of observations per period. The last row of Y contains the latest observations.

• If Mdl is time varying with respect to the observation equation, then Y is a T-by-1 cell vector. Each element of the cell vector corresponds to a period and contains an nt-dimensional vector of observations for that period. The corresponding dimensions of the coefficient matrices in Mdl.C{t} and Mdl.D{t} must be consistent with the matrix in Y{t} for all periods. The last cell of Y contains the latest observations.

Data Types: double | cell

### params0 — Unknown parameter initial valuesnumeric vector

Unknown parameter initial values for numerical maximum likelihood estimation, specified as a numeric vector.

The elements of params0 correspond to the unknown parameters in the state-space model matrices A, B, C, and D, and, optionally, the initial state mean Mean0 and covariance matrix Cov0.

• If you created Mdl explicitly (that is, by specifying the matrices without a parameter-to-matrix mapping function), then the software maps the elements of params to NaNs in the state-space model matrices and initial state values. The software searches for NaNs column-wise following the order A, B, C, D, Mean0, and Cov0.

• If you created Mdl implicitly (that is, by specifying the matrices with a parameter-to-matrix mapping function), then you must set initial parameter values for the state-space model matrices, initial state values, and state types within the parameter-to-matrices mapping function.

Data Types: double

### 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 single quotes (' '). You can specify several name and value pair arguments in any order as Name1,Value1,...,NameN,ValueN.

## Estimation Options

### 'Beta0' — Initial values of regression coefficientsmatrix

Initial values of regression coefficients, specified as the comma-separated pair consisting of 'Beta0' and a matrix.

The number of rows in Beta0 must equal the number of columns in Y. Beta0 and Predictors must have the same number of columns.

By default, the ordinary least-squares estimate of Y onto Predictors.

Data Types: double

### 'CovMethod' — Asymptotic covariance estimation method'OPG' (default) | 'Hessian' | 'Sandwich'

Asymptotic covariance estimation method, specified as the comma-separated pair consisting of 'CovMethod' and a string.

Set CovMethod using a value in this table.

ValueDescription
'Hessian'Negative, inverted Hessian matrix
'Sandwich'Both Hessian and OPG

Example: 'CovMethod','Sandwich'

Data Types: char

### 'Display' — Command Window display option'params' (default) | 'diagnostics' | 'full' | 'iter' | 'off' | cell vector of strings

Command Window display option, specified as the comma-separated pair consisting of 'Display' and a string or cell vector of strings.

Set Display using any combination of values in this table.

Valueestimate Displays
'diagnostics'Optimization diagnostics
'full'Maximum likelihood parameter estimates, standard errors, t statistics, iterative optimization information, and optimization diagnostics
'iter'Iterative optimization information
'off'Nothing in the Command Window
'params'Maximum likelihood parameter estimates, standard errors, and t statistics

For example,

• To run a simulation where you are fitting many models, and therefore want to suppress all output, use 'Display','off'.

• To display all estimation results and the optimization diagnostics, use 'Display',{'params','diagnostics'}.

Data Types: char | cell

### 'Options' — Optimization optionsoptimoptions optimization controller

Optimization options, specified as the comma-separated pair consisting of 'Options' and an optimoptions optimization controller. Options replaces default optimization options of the optimizer. For details on altering default values of the optimizer, see the optimization controller optimoptions, the constrained optimization function fmincon, or the unconstrained optimization function fminunc in Optimization Toolbox™.

For example, suppose that you want to change the constraint tolerance to 1e-6. Set Options = optimoptions(@fmincon,'TolCon',1e-6,'Algorithm','sqp') and then pass Options into estimate using 'Options',Options.

By default:

• For constrained optimization, estimate maximizes the likelihood objective function using fmincon and its default options, but sets 'Algorithm','interior-point'.

• For unconstrained optimization, estimate maximizes the likelihood objective function using fminunc and its default options, but sets 'Algorithm','quasi-newton'.

### 'Predictors' — Predictor variables in state-space model observation equation[] (default) | matrix

Predictor variables in the state-space model observation equation, specified as the comma-separated pair consisting of 'Predictors' and a matrix. The columns of Predictors correspond to individual predictor variables. Predictors must have T rows, where row t corresponds to the observed predictors at period t (Zt) in the expanded observation equation

That is, the software deflates the observations using the regression component. β is the time-invariant vector of regression coefficients that the software estimates with all other parameters.

If there are n observations per period, then the software regresses all predictor series onto each observation. Subsequently, the software returns d-by-n matrix of fitted regression coefficient vectors for each observation series, where d is the number of columns of Predictors.

If you specify Predictors, then Mdl must be time invariant. Otherwise, the software returns an error.

By default, the software excludes a regression component from the state-space model.

Data Types: double

### 'SquareRoot' — Square root filter method flagfalse (default) | true

Square root filter method flag, specified as the comma-separated pair consisting of 'SquareRoot' and true or false.

Example: 'SquareRoot',true

Data Types: logical

### 'Tolerance' — Forecast uncertainty threshold0 (default) | nonnegative scalar

Forecast uncertainty threshold, specified as the comma-separated pair consisting of 'Tolerance' and a nonnegative scalar.

If the forecast uncertainty for a particular observation is less than Tolerance during numerical estimation, then the software removes the uncertainty corresponding to the observation from the forecast covariance matrix before its inversion.

It is best practice to set Tolerance to a small number, for example, le-15, to overcome numerical obstacles during estimation.

Example: 'Tolerance',le-15

Data Types: double

### 'Univariate' — Univariate treatment of multivariate series flagfalse (default) | true

Univariate treatment of a multivariate series flag, specified as the comma-separated pair consisting of 'Univariate' and true or false.

DtDt' must be diagonal, where Dt is one of the following:

• The matrix D{t} in a time-varying state-space model

• The matrix D in a time-invariant state-space model

Example: 'Univariate',true

Data Types: logical

## Constrained Optimization Options for fmincon

### 'Aeq' — Linear equality constraint parameter transformermatrix

Linear equality constraint parameter transformer for constrained likelihood objective function maximization, specified as the comma-separated pair consisting of 'Aeq' and a matrix.

If you specify Aeq and beq, then estimate maximizes the likelihood objective function using the equality constraint where θ is a vector containing every Mdl parameter.

The number of rows of Aeq is the number of constraints, and the number of columns is the number of parameters that the software estimates. Order the columns of Aeq by Mdl.A, Mdl.B, Mdl.C, Mdl.D, Mdl.Mean0, Mdl.Cov0, and the regression coefficient (if the model has one).

Specify Aeq and beq together, otherwise estimate returns an error.

Aeq directly corresponds to the input argument Aeq of fmincon, not to the state-transition coefficient matrix Mdl.A.

By default, if you did not specify any constraint (linear inequality, linear equality, or upper and lower bound), then estimate maximizes the likelihood objective function using unconstrained maximization.

### 'Aineq' — Linear inequality constraint parameter transformermatrix

Linear inequality constraint parameter transformer for constrained likelihood objective function maximization, specified as the comma-separated pair consisting of 'Aineq' and a matrix.

If you specify Aineq and bineq, then estimate maximizes the likelihood objective function using the inequality constraint where θ is a vector containing every Mdl parameter.

The number of rows of Aineq is the number of constraints, and the number of columns is the number of parameters that the software estimates. Order the columns of Aineq by Mdl.A, Mdl.B, Mdl.C, Mdl.D, Mdl.Mean0, Mdl.Cov0, and the regression coefficient (if the model has one).

Specify Aineq and bineq together, otherwise estimate returns an error.

Aineq directly corresponds to the input argument A of fmincon, not to the state-transition coefficient matrix Mdl.A.

By default, if you did not specify any constraint (linear inequality, linear equality, or upper and lower bound), then estimate maximizes the likelihood objective function using unconstrained maximization.

Data Types: double

### 'beq' — Linear equality constraints of transformed parametersnumeric vector

Linear equality constraints of the transformed parameters for constrained likelihood objective function maximization, specified as the comma-separated pair consisting of 'beq' and a numeric vector.

If you specify Aeq and beq, then estimate maximizes the likelihood objective function using the equality constraint where θ is a vector containing every Mdl parameter..

Specify Aeq and beq together, otherwise estimate returns an error.

beq directly corresponds to the input argument beq of fmincon, and is not associated with any component of Mdl.

By default, if you did not specify any constraint (linear inequality, linear equality, or upper and lower bound), then estimate maximizes the likelihood objective function using unconstrained maximization.

Data Types: double

### 'bineq' — Linear inequality constraint upper boundsnumeric vector

Linear inequality constraint upper bounds of the transformed parameters for constrained likelihood objective function maximization, specified as the comma-separated pair consisting of 'bineq' and a numeric vector.

If you specify Aineq and bineq, then estimate maximizes the likelihood objective function using the inequality constraint where θ is a vector containing every Mdl parameter.

Specify Aineq and bineq together, otherwise estimate returns an error.

bineq directly corresponds to the input argument b of fmincon, and is not associated with any component of Mdl.

By default, if you did not specify any constraint (linear inequality, linear equality, or upper and lower bound), then estimate maximizes the likelihood objective function using unconstrained maximization.

Data Types: double

### 'lb' — Lower bounds of parametersnumeric vector

Lower bounds of the parameters for constrained likelihood objective function maximization, specified as the comma-separated pair consisting of 'lb' and a numeric vector.

If you specify lb and ub, then estimate maximizes the likelihood objective function subject to where θ is a vector containing every Mdl parameter.

Order the elements of lb by Mdl.A, Mdl.B, Mdl.C, Mdl.D, Mdl.Mean0, Mdl.Cov0, and the regression coefficient (if the model has one).

By default, if you did not specify any constraint (linear inequality, linear equality, or upper and lower bound), then estimate maximizes the likelihood objective function using unconstrained maximization.

Data Types: double

### 'ub' — Upper bounds of parametersnumeric vector

Upper bounds of the parameters for constrained likelihood objective function maximization, specified as the comma-separated pair consisting of 'ub' and a numeric vector.

If you specify lb and ub, then estimate maximizes the likelihood objective function subject to where θ is a vector every Mdl parameter.

Order the elements of ub by Mdl.A, Mdl.B, Mdl.C, Mdl.D, Mdl.Mean0, Mdl.Cov0, and the regression coefficient (if the model has one).

By default, if you did not specify any constraint (linear inequality, linear equality, or upper and lower bound), then estimate maximizes the likelihood objective function using unconstrained maximization.

Data Types: double

## Output Arguments

expand all

### EstMdl — State-space model containing parameter estimatesssm model

State-space model containing the parameter estimates, returned as an ssm model.

estimate uses maximum likelihood to calculate all parameter estimates. EstMdl stores the parameter estimates in the coefficient matrices (EstMdl.A, EstMdl.B, EstMdl.C, and EstMdl.D), and the initial state means and covariance matrix (EstMdl.Mean0 and EstMdl.Cov0), regardless of specifying Mdl explicitly. For the estimated regression coefficient, see estParams.

### estParams — Maximum likelihood estimates of model parametersnumeric, column vector

Maximum likelihood estimates of the model parameters known to the optimizer, returned as a numeric vector. estParams has the same dimensions as params0.

estimate arranges the estimates in estParams corresponding to unknown parameters in this order.

1. EstMdl.A(:), that is, estimates in EstMdl.A listed column-wise

2. EstMdl.B(:)

3. EstMdl.C(:)

4. EstMdl.D(:)

5. EstMdl.Mean0

6. EstMdl.Cov0(:)

7. In models with predictors, estimated regression coefficients listed column-wise

Data Types: double

### EstParamCov — Variance-covariance matrix of maximum likelihood estimatesmatrix

Variance-covariance matrix of maximum likelihood estimates of the model parameters known to the optimizer, returned as a matrix.

The rows and columns contain the covariances of the parameter estimates. The standard errors of the parameter estimates are the square root of the entries along the main diagonal.

estimate uses OPG to perform covariance matrix estimation.

estimate arranges the estimates in the rows and columns of EstParamCov corresponding to unknown parameters in this order.

1. EstMdl.A(:), that is, estimates in EstMdl.A listed column-wise

2. EstMdl.B(:)

3. EstMdl.C(:)

4. EstMdl.D(:)

5. EstMdl.Mean0

6. EstMdl.Cov0(:)

7. In models with predictors, estimated regression coefficients listed column-wise

Data Types: double

### logL — Optimized loglikelihood valuescalar

Optimized loglikelihood value, returned as a scalar.

Data Types: double

### Output — Optimization informationstructure array

Optimization information, returned as a structure array.

This table describes the fields of Output.

FieldDescription
ExitFlagOptimization exit flag that describes the exit condition. For details, see fmincon and fminunc.
OptionsOptimization options that the optimizer used for numerical estimation. For details, see optimoptions.

Data Types: struct

## Definitions

### State-Space Model

A state-space model is a discrete-time, stochastic model that contains two sets of equations: one describing how a latent process transitions in time (the state equation), and another describing how an observer measures the latent process at each period (the observation equation).

Symbolically, you can write a linear, multivariate, Gaussian state-space model using the following system of equations

for t = 1,...,T.

• , which is an mt-dimensional state vector describing the dynamics of some, possibly unobservable, phenomenon at period t.

• , which is an nt-dimensional observation vector describing how the states are measured by observers at period t.

• At is the mt-by-mt – 1 state-transition matrix describing how the states at time t transition to the states at period t – 1.

• Bt is the mt-by-kt state-disturbance-loading matrix describing how the states at period t combine with the innovations at period t.

• Ct is the nt-by-mt measurement-sensitivity matrix describing how the observations at period t relate to the states at period t.

• Dt is the nt-by-ht observation-innovation matrix describing how the observations at period t combine with the observation errors at period t.

• The matrices At, Bt, Ct, and Dt are referred to as coefficient matrices, and might contain unknown parameters.

• , which is a kt-dimensional, Gaussian, white-noise, unit-variance vector of state disturbances at period t.

• , which is an ht-dimensional, Gaussian, white-noise, unit-variance vector of observation innovations at period t.

• εt and ut are uncorrelated.

To write a time-invariant state-space model, drop the t subscripts of all coefficient matrices and dimensions.

### Time-Invariant Model

In a time-invariant state-space model:

• The coefficient matrices are equivalent for all periods.

• The number of states, state disturbances, observations, and observation innovations are the same for all periods.

For example, for all t, the following system of equations

represents a time-invariant state-space model.

### Time-Varying Model

In a time-varying state-space model:

• The coefficient matrices might change from period to period.

• The number of states, state disturbances, observations, and observation innovations might change from period to period. For example, this might happen if there is a regime shift or one of the states or observations cannot be measured during the sampling time frame. Also, you can model seasonality using time-varying models.

To illustrate a regime shift, suppose, for t = 1,..,10

for t = 11

and for t = 1,..,T

There are three sets of state transition matrices, whereas there are only two sets of the other coefficient matrices.

## Examples

expand all

### Fit a Time-Invariant State-Space Model to Data

This example generates data from a known model, and then fits a state-space model to the data.

Suppose that a latent process is this AR(1) process

where is Gaussian with mean 0 and standard deviation 1.

Generate a random series of 100 observations from , assuming that the series starts at 1.5.

T = 100;
ARMdl = arima('AR',0.5,'Constant',0,'Variance',1);
x0 = 1.5;
rng(1); % For reproducibility
x = simulate(ARMdl,T,'Y0',x0);


Suppose further that the latent process is subject to additive measurement error as indicated in the equation

where is Gaussian with mean 0 and standard deviation 0.1.

Use the random latent state process (x) and the observation equation to generate observations.

y = x + 0.1*randn(T,1);


Together, the latent process and observation equations compose a state-space model. Supposing that the coefficients and variances are unknown parameters, the state-space model is

Specify the state-transition matrix. Use NaN values for unknown parameters.

A = NaN;


B = NaN;


Specify the measurement-sensitivity coefficient matrix.

C = 1;


Specify the observation-innovation coefficient matrix

D = NaN;


Specify the state-space model using the coefficient matrices. Also, specify the initial state mean, variance, and distribution (which is stationary).

Mean0 = 0;
Cov0 = 10;
StateType = 0;
Mdl = ssm(A,B,C,D,'Mean0',Mean0,'Cov0',Cov0,'StateType',StateType);


Mdl is an ssm model. Verify that the model is correctly specified using the display in the Command Window.

Pass the observations to estimate to estimate the parameter. Set a starting value for the parameter to params0. and must be positive, so set the lower bound constraints using the 'lb' name-value pair argument. Specify that the lower bound of is -Inf.

params0 = [0.9; 0.5; 0.1];
EstMdl = estimate(Mdl,y,params0,'lb',[-Inf; 0; 0])

Method: Maximum likelihood (fmincon)
Sample size: 100
Logarithmic  likelihood:     -140.532
Akaike   info criterion:      287.064
Bayesian info criterion:      294.879
|     Coeff      Std Err   t Stat    Prob
-------------------------------------------------
c(1) | 0.45425       0.19870   2.28611  0.02225
c(2) | 0.89013       0.30359   2.93205  0.00337
c(3) | 0.38750       0.57858   0.66975  0.50302
|
|  Final State   Std Dev   t Stat    Prob
x(1) | 1.52989       0.35621   4.29498  0.00002

EstMdl =

State vector length: 1
Observation vector length: 1
State disturbance vector length: 1
Observation innovation vector length: 1
Sample size supported by model: Unlimited

State variables: x1, x2,...
State disturbances: u1, u2,...
Observation series: y1, y2,...
Observation innovations: e1, e2,...

State equation:
x1(t) = (0.45)x1(t-1) + (0.89)u1(t)

Observation equation:
y1(t) = x1(t) + (0.39)e1(t)

Initial state distribution:

Initial state means
x1
0

Initial state covariance matrix
x1
x1  10

State types
x1
Stationary



EstMdl is an ssm model. The results of the estimation appear in the Command Window, contain the fitted state-space equations, and contain a table of parameter estimates, their standard errors, t statistics, and p-values.

You can use or display, for example the
fitted state-transition matrix using dot notation.
EstMdl.A

ans =

0.4543



Pass EstMdl to forecast to forecast observations, or to simulate to conduct a Monte Carlo study.

### Fit a Time-Varying State-Space Model to Data

This example generates data from a known model, and then fits a state-space model to the data.

Suppose that a latent process comprises an AR(2) and an MA(1) model. There are 50 periods, and the MA(1) process drops out of the model for the final 25 periods. Subsequently, the state equation for the first 25 periods is

and for the last 25 periods, it is

where u1,t and u2,t are Gaussian with mean 0 and standard deviation 1.

Generate a random series of 50 observations from x1,t and x2,t, assuming that the series starts at 1.5 and 1, respectively.

T = 50;
ARMdl = arima('AR',{0.7,-0.2},'Constant',0,'Variance',1);
MAMdl = arima('MA',0.6,'Constant',0,'Variance',1);
x0 = [1.5 1; 1.5 1];
rng(1);
x = [simulate(ARMdl,T,'Y0',x0(:,1)),...
[simulate(MAMdl,T/2,'Y0',x0(:,2));nan(T/2,1)]];

The last 25 values for the simulated MA(1) data are NaNs.

Suppose further that the latent processes are measured using

for the first 25 periods, and

for the last 25 periods, where εt is Gaussian with mean 0 and standard deviation 1.

Use the random latent state process (x) and the observation equation to generate observations.

y = 2*nansum(x')'+randn(T,1);

Together, the latent process and observation equations compose a state-space model. Supposing that the coefficients are unknown parameters, the state-space model is

for the first 25 periods,

for period 26, and

for the last 24 periods.

Create the function Ar2MAParamMap.m, which specifies how the parameters in params map to the state-space model matrices, the initial state values, and the type of state.

function [A,B,C,D,Mean0,Cov0,StateType] = AR2MAParamMap(params,T)
%AR2MAParamMap Time-variant state-space model parameter mapping function
%
% This function maps the vector params to the state-space matrices (A, B,
% C, and D), the initial state value and the initial state variance (Mean0
% and Cov0), and the type of state (StateType). From periods 1 to T/2, the
% state model is an AR(2) and an MA(1) model, and the observation model is
% the sum of the two states. From periods T/2 + 1 to T, the state model is
% just the AR(2) model.
A1 = {[params(1) params(2) 0 0; 1 0 0 0; 0 0 0 params(3); 0 0 0 0]};
B1 = {[1 0; 0 0; 0 1; 0 1]};
C1 = {params(4)*[1 0 1 0]};
Mean0 = ones(4,1);
Cov0 = 10*eye(4);
StateType = [0 0 0 0];
A2 = {[params(1) params(2) 0 0; 1 0 0 0]};
B2 = {[1; 0]};
A3 = {[params(1) params(2); 1 0]};
B3 = {[1; 0]};
C3 = {params(5)*[1 0]};
A = [repmat(A1,T/2,1);A2;repmat(A3,(T-2)/2,1)];
B = [repmat(B1,T/2,1);B2;repmat(B3,(T-2)/2,1)];
C = [repmat(C1,T/2,1);repmat(C3,T/2,1)];
D = 1;
end



Specify the state-space model by passing the function AR2MAParamMap as a function handle to ssm.

Mdl = ssm(@(params)AR2MAParamMap(params,T))
Mdl =

The state space model is implicitly defined by the function:
@(params)AR2MAParamMap(params,T)

The software implicitly defines the state-space model. Usually, you cannot verify state-space models that you implicitly define.

Pass the observed responses (y) to estimate to estimate the parameters. Set positive, random initial values for the unknown parameters.

params0 = rand(5,1);
EstMdl = estimate(Mdl,y,params0)
Method: Maximum likelihood (fminunc)
Sample size: 50
Logarithmic  likelihood:     -114.957
Akaike   info criterion:      239.913
Bayesian info criterion:      249.473
|     Coeff       Std Err   t Stat     Prob
---------------------------------------------------
c(1) |  0.47870       0.26634    1.79733  0.07229
c(2) |  0.00809       0.27179    0.02976  0.97626
c(3) |  0.55735       0.80958    0.68844  0.49118
c(4) |  1.62679       0.41622    3.90849  0.00009
c(5) |  1.90022       0.49564    3.83390  0.00013
|
|   Final State   Std Dev    t Stat    Prob
x(1) | -0.81229       0.46815   -1.73511  0.08272
x(2) | -0.31449       0.45917   -0.68490  0.49341

EstMdl =

State vector length: Time-varying
Observation vector length: 1
State disturbance vector length: Time-varying
Observation innovation vector length: 1
Sample size supported by model: 50

State variables: x1, x2,...
State disturbances: u1, u2,...
Observation series: y1, y2,...
Observation innovations: e1, e2,...

State equations of period 1, 2, 3,..., 25:
x1(t) = (0.48)x1(t-1) + (8.09e-03)x2(t-1) + u1(t)
x2(t) = x1(t-1)
x3(t) = (0.56)x4(t-1) + u2(t)
x4(t) = u2(t)

State equations of period 26:
x1(t) = (0.48)x1(t-1) + (8.09e-03)x2(t-1) + u1(t)
x2(t) = x1(t-1)

State equations of period 27, 28, 29,..., 50:
x1(t) = (0.48)x1(t-1) + (8.09e-03)x2(t-1) + u1(t)
x2(t) = x1(t-1)

Observation equation of period 1, 2, 3,..., 25:
y1(t) = (1.63)x1(t) + (1.63)x3(t) + e1(t)

Observation equation of period 26, 27, 28,..., 50:
y1(t) = (1.90)x1(t) + e1(t)

Initial state distribution:

Initial state means
x1  x2  x3  x4
1   1   1   1

Initial state covariance matrix
x1  x2  x3  x4
x1  10  0   0   0
x2  0   10  0   0
x3  0   0   10  0
x4  0   0   0   10

State types
x1          x2          x3          x4
Stationary  Stationary  Stationary  Stationary 

The estimated parameters are within 1 standard error of their true values, but the standard errors are quite high. Likelihood surfaces of state-space models might contain local maxima. Therefore, it is good practice to try several initial parameter values, or consider using refine.

You can pass the estimated state-space model EstMdl to forecast to forecast responses or state values.

### Estimate a State-Space Model That Includes a Regression Component

Suppose that the linear relationship between the change in the unemployment rate and the nominal gross national product (nGNP) growth rate is of interest. Suppose further that the first difference of the unemployment rate is an ARMA(1,1) series. Symbolically, and in state-space form, the model is

where:

• is the change in the unemployment rate at time t.

• is a dummy state for the MA(1) effect.

• is the observed change in the unemployment being deflated by the growth rate of nGNP ( ).

• is the Gaussian series of state disturbances having mean 0 and standard deviation 1.

• is the Gaussian series of observation innovations having mean 0 and standard deviation .

Load the Nelson-Plosser data set, which contains the unemployment rate and nGNP series, among other things.

load Data_NelsonPlosser


Preprocess the data by taking the natural logarithm of the nGNP series, and the first difference of each. Also, remove the starting NaN values from each series.

gnpn = Dataset.GNPN(~isnan(Dataset.GNPN)); % Remove NaNs
u = Dataset.UR(~isnan(Dataset.GNPN));      % The effective nGNP series is shorter
T = size(gnpn,1);                          % Sample size
Z = [ones(T-1,1) diff(log(gnpn))];
y = diff(u);


This example proceeds using series without NaN values. However, using the Kalman filter framework, the software can accommodate series containing missing values.

Specify the state-transition coefficient matrix.

A = [NaN NaN; 0 0];


B = [1 0;1 0];


Specify the measurement-sensitivity coefficient matrix.

C = [1 0];


Specify the observation-innovation coefficient matrix.

D = NaN;


Specify the state-space model using ssm.

Mdl = ssm(A,B,C,D);


Estimate the model parameters, and use a random set of initial parameter values for optimization. Specify the regression component and its initial value for optimization using the 'Predictors' and 'Beta0' name-value pair arguments, respectively. Display the estimates and all optimization diagnostic information. Restrict the estimate of to all positive, real numbers.

rng(1);
params0 = rand(3,1);
params0(3) = abs(params0(3));
EstMdl = estimate(Mdl,y,params0,'Predictors',Z,'Display','full',...
'Beta0',randn(2,1),'lb',[-Inf,-Inf,0,-Inf,-Inf]);

____________________________________________________________
Diagnostic Information

Number of variables: 5

Functions
Objective:                            @(c)-fML(c,Mdl,Y,Predictors,unitFlag,sqrtFlag,mexFlag,mexTvFlag,tol,ind)
Hessian:                              finite-differencing (or Quasi-Newton)

Constraints
Nonlinear constraints:                do not exist

Number of linear inequality constraints:    0
Number of linear equality constraints:      0
Number of lower bound constraints:          1
Number of upper bound constraints:          0

Algorithm selected
interior-point

____________________________________________________________
End diagnostic information
First-order      Norm of
Iter F-count            f(x)  Feasibility   optimality         step
0       6    3.711823e+02    0.000e+00    6.428e+02
1      15    3.681082e+02    0.000e+00    2.985e+00    8.797e+01
2      23    3.667416e+02    0.000e+00    5.961e+00    1.080e+00
3      29    3.496648e+02    0.000e+00    1.490e+00    6.814e+00
4      35    3.403527e+02    0.000e+00    6.398e-01    8.106e+00
5      42    3.396726e+02    0.000e+00    1.876e+00    2.795e+00
6      48    3.364198e+02    0.000e+00    7.535e-01    1.018e+01
7      54    3.363132e+02    0.000e+00    6.443e-01    1.165e+00
8      60    3.360348e+02    0.000e+00    6.508e-01    3.419e+00
9      66    3.353765e+02    0.000e+00    6.624e-01    7.146e+00
10      73    3.337678e+02    0.000e+00    6.782e-01    1.840e+01
11      80    3.335190e+02    0.000e+00    6.821e-01    7.466e+00
12      86    3.300191e+02    0.000e+00    1.239e+01    2.636e+00
13      98    3.287010e+02    0.000e+00    6.991e-01    1.321e+00
14     104    3.281554e+02    0.000e+00    7.053e-01    4.397e+00
15     110    3.256848e+02    0.000e+00    7.341e-01    1.969e+01
16     116    3.244770e+02    0.000e+00    7.485e-01    7.471e+00
17     122    3.136846e+02    0.000e+00    1.446e+00    7.419e+01
18     130    3.087802e+02    0.000e+00    1.245e+01    9.598e+01
19     136    2.941740e+02    0.000e+00    9.347e+00    2.779e+01
20     147    2.870536e+02    0.000e+00    1.072e+01    2.104e+01
21     153    2.862781e+02    0.000e+00    1.855e+01    6.221e+01
22     160    2.831350e+02    0.000e+00    5.132e+00    9.099e+00
23     166    2.824867e+02    0.000e+00    3.182e+00    2.676e+01
24     172    2.812413e+02    0.000e+00    9.699e-01    3.372e+00
25     178    2.792069e+02    0.000e+00    4.316e+00    8.175e+00
26     184    2.784745e+02    0.000e+00    1.973e+00    1.050e+01
27     190    2.778346e+02    0.000e+00    7.420e-01    5.660e+00
28     196    2.761344e+02    0.000e+00    5.820e+00    1.073e+01
29     202    2.730350e+02    0.000e+00    1.513e+01    1.832e+01
30     208    2.699245e+02    0.000e+00    3.902e+01    5.248e+01

First-order      Norm of
Iter F-count            f(x)  Feasibility   optimality         step
31     214    2.579725e+02    0.000e+00    3.247e+01    9.722e+01
32     220    2.417672e+02    0.000e+00    6.423e+00    1.112e+02
33     226    1.935178e+02    0.000e+00    3.628e+01    8.825e+01
34     234    1.736048e+02    0.000e+00    2.961e+01    1.753e+01
35     240    1.550356e+02    0.000e+00    1.175e+01    2.059e+01
36     252    1.431259e+02    0.000e+00    4.434e+01    1.028e+01
37     266    1.323516e+02    0.000e+00    1.389e+01    1.288e+00
38     273    1.290338e+02    0.000e+00    1.471e+01    1.193e+00
39     282    1.092555e+02    0.000e+00    1.587e+01    9.285e+00
40     290    1.074473e+02    0.000e+00    4.406e+01    1.420e+00
41     296    1.061052e+02    0.000e+00    1.193e+01    7.832e+00
42     302    1.030490e+02    0.000e+00    1.647e+01    4.313e+00
43     308    1.031979e+02    0.000e+00    1.135e+01    1.289e+00
44     315    1.002698e+02    0.000e+00    4.662e+00    1.962e+00
45     322    9.983285e+01    0.000e+00    9.313e-01    3.311e-01
46     328    9.978089e+01    0.000e+00    1.091e+00    6.069e-01
47     334    9.975885e+01    0.000e+00    8.145e-01    6.801e-02
48     340    9.975060e+01    0.000e+00    1.027e+00    1.297e-01
49     346    9.972684e+01    0.000e+00    3.398e-01    4.909e-02
50     352    9.972531e+01    0.000e+00    1.111e-01    2.084e-02
51     358    9.972591e+01    0.000e+00    9.999e-02    3.374e-02
52     364    9.972457e+01    0.000e+00    2.121e-02    1.704e-02
53     370    9.972454e+01    0.000e+00    2.791e-03    2.339e-03
54     376    9.972454e+01    0.000e+00    3.324e-04    3.275e-04
55     382    9.972454e+01    0.000e+00    2.000e-04    3.061e-05
56     388    9.972454e+01    0.000e+00    4.000e-05    1.506e-05
57     394    9.972454e+01    0.000e+00    1.144e-05    4.120e-06
58     400    9.972454e+01    0.000e+00    6.358e-06    1.430e-06
59     406    9.972454e+01    0.000e+00    1.907e-06    8.373e-07
60     415    9.972454e+01    0.000e+00    2.861e-06    3.231e-08

First-order      Norm of
Iter F-count            f(x)  Feasibility   optimality         step
61     425    9.972454e+01    0.000e+00    3.633e-06    6.435e-08

Local minimum possible. Constraints satisfied.

fmincon stopped because the size of the current step is less than
the default value of the step size tolerance and constraints are
satisfied to within the default value of the constraint tolerance.

Method: Maximum likelihood (fmincon)
Sample size: 61
Logarithmic  likelihood:     -99.7245
Akaike   info criterion:      205.449
Bayesian info criterion:      211.782
|      Coeff       Std Err    t Stat     Prob
----------------------------------------------------------
c(1)      |  -0.34098       0.29608    -1.15164  0.24948
c(2)      |   1.05003       0.41377     2.53771  0.01116
c(3)      |   0.48592       0.36790     1.32079  0.18657
y <- z(1) |   1.36121       0.22338     6.09358   0
y <- z(2) | -24.46711       1.60018   -15.29024   0
|
|    Final State   Std Dev     t Stat    Prob
x(1)      |   1.01264       0.44690     2.26592  0.02346
x(2)      |   0.77718       0.58917     1.31912  0.18713


Optimization information and a table of estimates and statistics output to the Command Window. EstMdl is an ssm model, and you can access its properties using dot notation.

### Compare Estimates from State-Space Model Filtering Methods

The software implements the Kalman filter using the covariance filter by default, but you can specify to use the square-root filter instead. This example compares estimates from each method using simulated data.

Suppose that a latent process is an AR(1). Subsequently, the state equation is

where is Gaussian with mean 0 and standard deviation 0.3.

Generate a random series of 100 observations from , assuming that the series starts at 1.5.

T = 100;
ARMdl = arima('AR',0.5,'Constant',0,'Variance',0.3^2);
x0 = 1.5;
rng(1); % For reproducibility
x = simulate(ARMdl,T,'Y0',x0);


Suppose further that the latent process is subject to additive measurement error. Subsequently, the observation equation is

where is Gaussian with mean 0 and standard deviation 0.1.

Use the random latent state process (x) and the observation equation to generate observations.

y = x + 0.1*randn(T,1);


Together, the latent process and observation equations compose a state-space model. Supposing that the coefficients and variances are unknown parameter, the state-space model is

Specify the state-transition coefficient matrix. Use NaN values for unknown parameters.

A = NaN;


B = NaN;


Specify the measurement-sensitivity coefficient matrix.

C = 1;


Specify the observation-innovation coefficient matrix.

D = NaN;


Specify the state-space model using the coefficient matrices. Also, specify the initial state mean, variance, and distribution (which is stationary).

Mean0 = 0;
Cov0 = 10;
StateType = 0;
Mdl = ssm(A,B,C,D,'Mean0',Mean0,'Cov0',Cov0,'StateType',StateType);


Mdl is an ssm model.

Estimate the parameters using estimate two ways:

• Using the default, simple Kalman filter

• Using the square root filter variation

In both cases, specify that no output should be returned to the Command Window. This is good practice if you plan on running estimate multiple times (such as a Monte Carlo simulation).

params0 = [10,10,10];
[~,estParamsSKF,EstParamCovSKF,logLSKF,OutputSKF] = estimate(Mdl,y,params0,...
'Display','off');
[~,estParamsSR,EstParamCovSR,logLSR,OutputSR] = estimate(Mdl,y,params0,...
'Squareroot',true,'Display','off');


Check that the algorithms converged properly by printing the exit flag properties of OutputSKF and OutputSR.

exitFlagSKF = OutputSKF.ExitFlag
exitFlagSR = OutputSR.ExitFlag

exitFlagSKF =

1

exitFlagSR =

1



Both algorithms have an exit flag of 1, which indicates that the software met the convergence criteria.

Compare the estimates from each algorithm.

fprintf('\n Parameter Estimates\n')
table(estParamsSKF',estParamsSR','VariableNames',...
{'SimpleKalmanFilter','SquarerootFilter'})
fprintf('\nEstimated Parameter Covariance Matrix\n')
table(EstParamCovSKF,EstParamCovSR,'VariableNames',...
{'SimpleKalmanFilter','SquarerootFilter'})

 Parameter Estimates

ans =

SimpleKalmanFilter    SquarerootFilter
__________________    ________________

0.51057               0.51057
0.23436               0.23436
-0.17904              -0.17904

Estimated Parameter Covariance Matrix

ans =

SimpleKalmanFilter                      SquarerootFilter
___________________________________    ___________________________________

0.036669    -0.013302    -0.014012     0.036669    -0.013302    -0.014012
-0.013302    0.0070187    0.0072533    -0.013302    0.0070187    0.0072533
-0.014012    0.0072533    0.0089019    -0.014012    0.0072533    0.0089019



In this case, the results are the same.

If you use the default, covariance filter method, and you run into numerical problems during estimation, filtering, or smoothing, try using the squareroot method.

## Algorithms

• For explicitly-defined state-space models, the software applies all predictors to each response series. However, each response series has its own set of regression coefficients.

• The software estimates regression coefficients along with all other state-space model parameters. The software is flexible enough to allow applying constraints to the regression coefficients using the constrained optimization options for fminunc.

• The software passes the name-value pair arguments Options, Aineq, bineq, Aeq, beq, lb, and ub directly to the optimizer fmincon or fminunc.

• If you do not specify optimization constraints, then the software uses fminunc for unconstrained numerical estimation. If you specify any pair of optimization constraints, then the software uses fmincon for constrained numerical estimation. For either type of optimization, optimization options you set using the name-value pair argument Options must be consistent with the options of the optimization algorithm.

• If you set 'Univariate',true, then, during the filtering algorithm, the software sequentially updates rather then updating all at once. This might accelerate parameter estimation, especially for a low-dimensional, time-invariant model.

## References

[1] Durbin J., and S. J. Koopman. Time Series Analysis by State Space Methods. 2nd ed. Oxford: Oxford University Press, 2012.