%% Extract Estimation Results from Estimated Model
% Estimate several models by passing the data to estimate. Vary the autoregressive and moving average degrees p and q, respectively. Estimation results contain the AIC, which you can extract and then compare among the models.
%
% Simulate response and predictor data for the regression model with ARMA errors:
% \begin{array}{l}{y_t} = 2 + {X_t}\left[ {\begin{array}{*{20}{c}}{ - 2}\\{1.5}\end{array}} \right] + {u_t}\\{u_t} = 0.75{u_{t - 1}} - 0.5{u_{t - 2}} + {\varepsilon _t} + 0.7{\varepsilon _{t - 1}},\end{array}
% where \varepsilon_t is Gaussian with mean 0 and variance 1.

Mdl0 = regARIMA('Intercept',2,'Beta',[-2; 1.5],...
    'AR',{0.75, -0.5},'MA',0.7,'Variance',1);

rng(2);            % For reproducibility
X = randn(1000,2); % Predictors
y = simulate(Mdl0,1000,'X',X);

%
% To determine the number of AR and MA lags, create and estimate multiple regression models with ARMA(p, q) errors. Vary p = 1,..,3 and q = 1,...,3 among the models. Suppress all estimation displays.  Extract the AIC from the estimation results structure.  The field AIC stores the AIC.

pMax = 3;
qMax = 3;
AIC = zeros(pMax,qMax); % Preallocation

for p = 1:pMax
    for q = 1:qMax
        Mdl = regARIMA(p,0,q);
        EstMdl = estimate(Mdl,y,'X',X,'Display','off');
        results = summarize(EstMdl);
        AIC(p,q) = results.AIC;
    end
end

%
% Compare the AIC values among the models.

minAIC = min(min(AIC))
[bestP,bestQ] = find(AIC == minAIC)

% The best fitting model is the regression model with AR(2,1) errors because its corresponding AIC is the lowest. This model also has the structure of the model used to  simulate the data.
% Copyright 2012 The MathWorks, Inc.