%% Convert Diffuse to Standard State-Space Model
% If you estimate, filter, or smooth a diffuse state-space model containing at least one diffuse state, then the software uses the diffuse Kalman filter. To use the standard Kalman filter instead, convert the diffuse state-space model to a standard state-space model.  ssm attributes a large initial state variance (1e7) for diffuse states. A standard state-space model treatment results in an approximation to the results of the diffuse Kalman filter. However, estimate uses all of the data to fit the model, and filter and smooth return filtered and smoothed estimates for all periods, respectively.
% Explicitly create a one-dimensional diffuse state-space model. Specify that the first state equation is x_t = x_{t-1} + u_t, and that the observation model is y_t = x_t + \varepsilon_t.

A = 1;   
B = 1; 
C = 1; 
D = 1;
MdlDSSM = dssm(A,B,C,D)

% MdlDSSM is a dssm model object. Because the model does not contain any unknown parameters, dssm infers the initial state distribution and its parameters. In particular, the initial state variance is Inf because the nonstationary state has a diffuse distribution by default.
%
% Convert MdlDSSM to a standard state-space model.

Mdl = ssm(MdlDSSM)

% Mdl is an ssm model object. The structures of Mdl and MdlDSSM are equivalent, except that the initial state variance of the state in Mdl is 1e7.
%
% To see the difference between the two models, simulate 10 periods of data from a state-space model that is similar to Mdl, except it has known initial state mean of 5 and variance 2.

Mdl0 = ssm(A,B,C,D,'Mean0',5,'Cov0',2,'StateType',2);
T = 10;
rng(1); % For reproducibility
y = simulate(Mdl0,T);

%
% Obtain filtered and smoothed states from Mdl and MdlDSSM using the simulated data.

fY = filter(Mdl,y);
fDY = filter(MdlDSSM,y);
sY = smooth(Mdl,y);
sDY = smooth(MdlDSSM,y);

%
% Plot the filtered and smoothed states.

figure;
plot(1:T,y,'-o',1:T,fY,'-d',1:T,fDY,'-*');
legend('Simulated Data','Filtered States -- Mdl','Filtered States -- MdlDSSM');

figure;
plot(1:T,y,'-o',1:T,sY,'-d',1:T,sDY,'-*');
legend('Simulated Data','Smoothed States -- Mdl','Smoothed States -- MdlDSSM');

% Besides apparent transient behavior, the filtered and smoothed states between the standard and diffuse state-space models appear nearly equivalent. The slight difference occurs because filter and smooth set all diffuse state estimates in the diffuse state-space model to 0 while they implement the diffuse Kalman filter. Once the covariance matrices of the smoothed states attain full rank, filter and smooth switch to using the standard Kalman filter. In this case, the switching time occurs after the first period.
% Copyright 2015 The MathWorks, Inc.