%% Refine Parameters When Fitting Time-Invariant Diffuse State-Space Model
% Suppose that a latent process is a random walk. Consequently, the state equation is
% x_t = x_{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; 
rng(1); % For reproducibility 
u = randn(T,1);
x = cumsum([1.5;u]);
x = x(2:end);

% Suppose further that the latent process is subject to additive measurement error. Consequently, the observation equation is
% y_t = x_t + \varepsilon_t,
% where \varepsilon_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 = x + randn(T,1);

% Together, the latent process and observation equations compose a state-space model. Assume that the state is a stationary AR(1) process. Then the state-space model to estimate 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 coefficient matrices. Use NaN values for unknown parameters.

A = NaN;
B = NaN;
C = 1;
D = NaN;

%
% Create the diffuse state-space model by passing the coefficient matrices to dssm and specifying that the state type is diffuse.

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

% Mdl is a dssm model object. The software sets values for the initial state mean and variance to 0 and Inf. Verify that the model is specified correctly using the display in the Command Window.
%
% Find a good set of starting parameters to use for estimation.

params0 = [1 1 1]; % Initial values chosen arbitrarily
Output = refine(Mdl,y,params0);

% Output is a 1-by-5 structure array containing the recommended initial parameter values.
%
% Choose the initial parameter values corresponding to the largest loglikelihood

logL = cell2mat({Output.LogLikelihood})';
[~,maxLogLIndx] = max(logL)
refinedParams0 = Output(maxLogLIndx).Parameters
Description = Output(maxLogLIndx).Description

% The algorithm that yields the highest loglikelihood value is Quasi-Newton, which is the first struct in the structure array Output.
%
% Estimate Mdl using refinedParams0, which is the vector of refined initial parameter values.

EstMdl = estimate(Mdl,y,refinedParams0,'lb',[-Inf,0,0]);

% The AR model coefficient is within two standard errors of 1, which suggests that the state processes is a random walk.
% Copyright 2012 The MathWorks, Inc.