%% Fit Time-Invariant Diffuse State-Space Model to Data
% Generate data from a known model, and then fit a diffuse state-space model to the data.
% Suppose that a latent process is this AR(1) process
% x_t = 0.5x_{t-1} + u_t,
% where u_t is Gaussian with mean 0 and standard deviation 1.
% Generate a random series of 100 observations from x_t, 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
% y_t = x_t + \varepsilon_t,
% where \varepsilon_t 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
% \begin{array}{c}x_t = \phi x_{t-1} + \sigma_1u_t \\ y_t = x_t +
% \sigma_2\varepsilon_t.\end{array}
%
% Specify the state-transition matrix. Use NaN values for unknown parameters.

A = NaN;

%
% Specify the state-disturbance-loading coefficient matrix.

B = NaN;

%
% Specify the measurement-sensitivity coefficient matrix.

C = 1;

%
% Specify the observation-innovation coefficient matrix

D = NaN;

%
% Create the state-space model using the coefficient matrices and specify that the state variable is diffuse. A diffuse state specification indicates complete ignorance on the values of the states.

StateType = 2;
Mdl = dssm(A,B,C,D,'StateType',StateType);

% Mdl is a dssm model. Verify that the model is correctly specified by viewing its display in the Command Window.
%
% Pass the observations to estimate to estimate the parameter. Set a starting value for the parameter to params0.  \sigma_1 and \sigma_2 must be positive, so set the lower bound constraints using the 'lb' name-value pair argument. Specify that the lower bound of \phi is -Inf.

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

% EstMdl is a dssm 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.
%
% Use dot notation to use or display the fitted state-transition matrix.

EstMdl.A

% Pass EstMdl to forecast to forecast observations, or to simulate to conduct a Monte Carlo study.
% Copyright 2012 The MathWorks, Inc.