%% State Variable Cumulative IRFs of Estimated Model
% Simulate data from a known model, fit the data to a state-space model, and then estimate the cumulative IRFs of the state variables.
% Assume that the data generating process (DGP) is the AR(1) model
% x_t = 1 + 0.9x_{t-2} + u_t,
% where u_t is a series of independent and identically distributed Gaussian variables with mean 0 and variance 1.
% Simulate 500 observations from the model.

rng(1); % For reproducibility
DGP = arima('Constant',1,'AR',{0 0.9},'Variance',1);
y = simulate(DGP,500);

% Explicitly create a state-space model template for estimation that represents the model
% \begin{array}{l}
% x_t=c+\phi x_{t-2}+\eta u_t\\
% y_t= x_{t}.
% \end{array}

A = [0 NaN NaN; 0 1 0; 1 0 0];
B = [NaN; 0; 0];
C = [1 0 0];
D = 0;
Mdl = ssm(A,B,C,D,'StateType',[0 1 0]);

% Fit the model template to the data. Specify a set of positive, random standard  Gaussian starting values for the three model parameters.

EstMdl = estimate(Mdl,y,abs(randn(3,1)));

% EstMdl is a fully specified dssm model object.
% Estimate the cumulative IRFs of the state and measurement variables.

[ResponseY,ResponseX] = irf(EstMdl,'Cumulative',true);

% ResponseY is a 20-by-1 vector representing the measurement variable IRF. ResponseX is a 20-by-1-by-3 array representing the IRF of the state variables.
% Display the IRF of x_t, which is the first state variable in the system x_{1,t}.

irfx = ResponseX(:,:,1)

% Verify that, because y_t =x_t, ResponseY = ResponseX(:,:,1).

ver1 = sum(abs(ResponseY - ResponseX(:,:,1)))

% Verify that, because x_{1,t-1} =x_{3,t}, ResponseX(1:(end-2),1,1) = ResponseX(2:(end-1),:,3).

ver2 = sum(abs(ResponseX(1:(end-2),:,1) - ResponseX(2:(end-1),:,3)))

% Copyright 2020 The MathWorks, Inc.