%% Smooth States of Time-Invariant Diffuse State-Space Model
% Suppose that a latent process is a random walk. 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;
x0 = 1.5;
rng(1); % For reproducibility
u = randn(T,1);
x = cumsum([x0;u]);
x = x(2:end);

% Suppose further that the latent process is subject to additive measurement error. The observation equation is
% y_t = x_t + \varepsilon_t,
% where \varepsilon_t is Gaussian with mean 0 and standard deviation 0.75. Together, the latent process and observation equations compose a state-space model.
%
% Use the random latent state process (x) and the observation equation to generate observations.

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

%
% Specify the four coefficient matrices.

A = 1;
B = 1;
C = 1;
D = 0.75;

%
% Create the diffuse state-space model using the coefficient matrices. Specify that the initial state distribution is diffuse.

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

% Mdl is an dssm model. Verify that the model is correctly specified using the display in the Command Window.
%
% Smooth states for periods 1 through 100. Plot the true state values and the smoothed state estimates.

SmoothedX = smooth(Mdl,y);

figure
plot(1:T,x,'-k',1:T,SmoothedX,':r','LineWidth',2)
title({'State Values'})
xlabel('Period')
ylabel('State')
legend({'True state values','Smoothed state values'})

% The true values and smoothed estimates are approximately the same.
% Copyright 2015 The MathWorks, Inc.