%% Estimate FGLS Coefficients of Models Containing ARMA Errors
% Create this regression model with ARMA(1,2) errors, where \varepsilon_t is Gaussian with mean 0 and variance 1.
% \begin{array}{*{20}{c}}
% {{y_t} = 1 + {x_t}\left[ {\begin{array}{*{20}{c}}
% 2\\
% 3
% \end{array}} \right] + {u_t}}\\
% {{u_t} = 0.6{u_{t - 1}} + {\varepsilon _t}} - 0.3\varepsilon_{t-1} +
% 0.1\varepsilon_{t-1}.
% \end{array}

beta = [2 3];
phi = 0.2;
theta = [-0.3 0.1];
Mdl = regARIMA('AR',phi,'MA',theta,'Intercept',1,'Beta',beta,'Variance',1);

% Mdl is a regARIMA model. You can access its properties using dot notation.
%
% Simulate 500 periods of 2-D standard Gaussian values for x_t, and then simulate responses using Mdl.

numObs = 500;
rng(1); % For reproducibility
X = randn(numObs,2);
y = simulate(Mdl,numObs,'X',X);

%
% fgls supports AR(p) innovation models. You can convert an ARMA model polynomial to an infinite-lag AR model polynomial using arma2ar. By default, arma2ar returns the coefficients for the first 10 terms. After the conversion, determine how many lags of the resulting AR model are practically significant by checking the length of the returned vector of coefficients. Choose the number of terms that exceed 0.00001.

format long
arParams = arma2ar(phi,theta)
arLags = sum(abs(arParams) > 0.00001);
format short

% Some of the parameters have small magnitude. You might want to reduce the number of lags to include in the innovations model for fgls.
%
% Estimate the coefficients and their standard errors using FGLS and the simulated data. Specify that the innovations comprise an AR(arLags) process.

[coeff,~,EstCoeffCov] = fgls(X,y,'innovMdl','AR','arLags',arLags)

% The estimated coefficients are close to their true values.
% Copyright 2015 The MathWorks, Inc.