%% Diagnostic Plots for Recursive Regression Coefficient Estimates
% Plot the recursive regression coeffiicent estimates of the explanatory model of real gross national product (GNP) as outlined in Plot Recursive Residuals and Critical Lines.
% Load the Nelosson-Plosser data set.

load Data_NelsonPlosser

%
% Several series have missing data. Focus the sample to measurements from 1915 to 1970.

span = (1915 <= dates) & (dates <= 1970);

%
% Collect the model variables into a tabular array. Position the response as the last variable.

Mdl = DataTable(span,[4,5,10,1]);

%
% Conduct a forward and backward cusum test. Store the recursive regression coefficient estimates.

[~,~,~,~,B] = cusumtest(Mdl,'Direction',{'forward','backward'},'Plot','on');

% The forward test rejects the null hypothesis that the coefficients are stable. The backward test fails to reject the null hypothesis.
% B is a 4-by-53-by-2 numeric array containing the coefficient estimates.
% Rows correspond to coefficients starting with the intercept, and then following the order of the predictors in Mdl.
% Columns correspond to recursive regression iterations. The first column is a vector of NaN values because the model has an intercept.
% Column 2 includes observations 1 - 4 for the forward test, and observations 53 - 56 for the backward test. Column 3 includes observations 1 - 5 for the forward test, and observations 52 - 56 for the backward test, and so on.
% Pages correspond to tests: the first page is the forward test and the second page is the backward test.
%
% Plot the recursive regression coefficients for each test.

coeffName = [{'Intercept'} Mdl.Properties.VariableNames(1:end-1)];
for k = 1:size(B,3)
    figure;
    for j = 1:size(B,1)
        subplot(2,2,j);
        plot(B(j,:,k));
        title(sprintf('%s',coeffName{j}));
        xlabel('Iteration')
        ylabel('Coefficient Value')
        axis tight
    end
end

% The coefficients from the forward recursive regression seem to vary throughout the sample. However, the coefficients from the backward regression seem to settle midway through the backward recursive regressions.
% Copyright 2012 The MathWorks, Inc.