%% Compare Responses from filter and simulate
% Simulate responses using filter and simulate. Then compare the simulated responses.
% Both filter and simulate filter a series of errors to produce output responses y, innovations e, and unconditional disturbances u. The difference is that simulate generates errors from Mdl.Distribution, whereas filter accepts a random array of errors that you generate from any distribution.
% Specify the following regression model with ARMA(2,1) errors:
% \begin{array}{*{20}{l}}
% \begin{array}{c}
% {y_t} = {X_t}\left[ {\begin{array}{*{20}{c}}
% {0.1}\\
% { - 0.2}
% \end{array}} \right] + {u_t}\\
% {u_t} = 0.5{u_{t - 1}} - 0.8{u_{t - 2}} + {\varepsilon _t} - 0.5{\varepsilon _{t - 1}},
% \end{array}
% \end{array}
% where \varepsilon_t is Gaussian with variance 0.1.

Mdl = regARIMA('Intercept',0,'AR',{0.5 -0.8}, ...
    'MA',-0.5,'Beta',[0.1 -0.2],'Variance',0.1);

%
% Simulate data for the predictors and from Mdl using Monte Carlo simulation.

rng(1);           % For reproducibility
X = randn(100,2); % Simulate predictor data
[ySim,eSim,uSim] = simulate(Mdl,100,'X',X);

%
% Standardize the simulated innovations and filter them.

z1 = eSim./sqrt(Mdl.Variance);
[yFlt1,eFlt1,uFlt1] = filter(Mdl,z1,'X',X);

%
% Confirm that the simulated responses from simulate and filter are identical using a plot.

figure
h1 = plot(ySim);
hold on
h2 = plot(yFlt1,'.');
title '{\bf Filtered and Simulated Responses}';
legend([h1, h2],'Simulate','Filter','Location','Best')
hold off

%
% Alternatively, simulate responses by randomly generating your own errors and passing them into filter.

rng(1);
X = randn(100,2);
z2 = randn(100,1);
yFlt2 = filter(Mdl,z2,'X',X);
figure
h1 = plot(ySim);
hold on
h2 = plot(yFlt2,'.');
title '{\bf Filtered and Simulated Responses}';
legend([h1, h2],'Simulate','Filter','Location','Best')
hold off

% This plot is the same as the previous plot, confirming that both simulation methods are equivalent.
% filter multiplies the error, Z, by sqrt(Mdl.Variance) before filtering Z through the model. Therefore, if you want to specify your own distribution, set Mdl.Variance to 1, and then generate your own errors using, for example, random('unif',a,b) for the Uniform(a, b) distribution.
% Copyright 2015 The MathWorks, Inc.