%% Compute Only Final State Distribution From Kalman Filter
% Suppose that a latent process is an AR(1). The state equation is
% 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. 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 = 0.5;
B = 1;
C = 1;
D = 0.75;

% Specify the state-space model using the coefficient matrices.

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

% Mdl is an ssm model. Verify that the model is correctly specified using the display in the Command Window. The software infers that the state process is stationary. Subsequently, the software sets the initial state mean and covariance to the mean and variance of the stationary distribution of an AR(1) model.
% Filter the observations through the state-space model, in real time, to obtain the state distribution for period 100.

[rtfX100,rtfXVar100] = update(Mdl,y)

% update applies the Kalman filter to all observations in y, and returns only the state estimate of period 100.
% Compare the result to the results of filter.

[fX,~,output] = filter(Mdl,y);
size(fX)
fX100 = fX(100)
fXVar100 = output(end).FilteredStatesCov
tol = 1e-10;
discrepencyMeans = fX100 - rtfX100;
discrepencyVars = fXVar100 - rtfXVar100;
areMeansEqual = norm(discrepencyMeans) < tol
areVarsEqual = norm(discrepencyVars) < tol

% Like update, the filter function filters the observations through the model, but it returns all intermediate state estimates. Because update returns only the final state estimate, it is more suited to real time calculations than filter.
% Copyright 2021 The MathWorks, Inc.