%% Convert Structural VAR Model to VEC Model Using Lag Operator Polynomials
% Consider converting the following structural VAR(2) model to a structural VEC(1) model.
% \left[ {\begin{array}{*{20}{c}}
% {0.54}&{ - 2.26}\\
% {1.83}&{0.86}
% \end{array}} \right]{y_t} = \left[ {\begin{array}{*{20}{c}}
% {0.32}&{ - 0.43}\\
% { - 1.31}&{0.34}
% \end{array}} \right]{y_{t - 1}} + \left[ {\begin{array}{*{20}{c}}
% {0.07}&{0.07}\\
% { - 0.01}&{ - 0.02}
% \end{array}} \right]{y_{t - 2}} + {\varepsilon _t}.
% Specify the autoregressive coefficient matrices A_0, A_1, and A_2.

A0 = [0.54 -2.26;
      1.83  0.86];
A1 = [0.32 -0.43
     -1.31  0.34];
A2 = [0.07  0.07
     -0.01 -0.02];

%
% Pack the matrices into separate cells of a 3 dimensional cell vector. Put A0 into the first cell, A1 into the second cell, and A2 into the third cell. Negate the coefficients corresponding to all nonzero lag terms.

VARCoeff = {A0; -A1; -A2};

%
% Create a lag operator polynomial that encompasses the autoregressive terms in the VAR(2) model.

VAR = LagOp(VARCoeff)

% VAR is a LagOp lag operator polynomial.  VAR specifies the VAR(2) model in lag operator notation, as in this equation
% (A_0 - A_1L - A_2L^2)y_t = \varepsilon_t.
% L is the lag operator. If you expand the quantity and solve for y_t, then the result is the VAR(2) model in difference-equation notation.
%
% Compute the coefficient matrices of \Delta y_{t} and \Delta y_{t}, and the error-correction coefficient matrix of the equivalent VEC(1) model.

[VEC,C] = var2vec(VAR)

% VAR.Coefficients{0} is A_0, the coefficient matrix of y_t. Subsequent elements in VAR.Coefficients correspond to subsequent lags in VAR.Lags.
% VEC is the VEC(1) equivalent of the VAR(2) model. Because the VAR(2) model is structural, the equivalent VEC(1) model is as well. That is, VEC.Coefficients{0} is the coefficient of \Delta y_{t}, and subsequent elements correspond to subsequent lags in VEC.Lags.
%
% Display the VEC model coefficients in difference-equation notation.

B0 = VEC.Coefficients{0}
B1 = -VEC.Coefficients{1}
C

% The resulting VEC(1) model is
% \left[ {\begin{array}{*{20}{c}}
% {0.54}&{ - 2.26}\\
% {1.83}&{0.86}
% \end{array}} \right]\Delta {y_t} = \left[ {\begin{array}{*{20}{c}}
% {-0.07}&{-0.07}\\
% {0.01}&{0.02}
% \end{array}} \right]\Delta {y_{t - 1}} + \left[ {\begin{array}{*{20}{c}}
% { - 0.15}&{1.9}\\
% { - 3.15}&{ - 0.54}
% \end{array}} \right]{y_{t - 1}} + {\varepsilon _t}.
%
% Alternatively, reflect the lag operator polynomial VEC around lag 0 to obtain the difference-equation notation coefficients.

DiffEqnCoeffs = reflect(VEC);
B = toCellArray(DiffEqnCoeffs);
B{1} == B0
B{2} == B1

% Both methods produce the same coefficients.
% Copyright 2015 The MathWorks, Inc.