*
* %ModelCompanion(model)
* returns the companion matrix for a model (could be a VAR,
* but doesn't have to be). This is the matrix A for the
* AR(1) representation
*
* X(t)=AX(t-1)+u(t)
*
* where X is the vector of dependent variables augmented to include
* lags through maxlag-1 of all dependent variables. This doesn't
* create a full state-space representation for X, as variables in
* the model which aren't lags of the dependent variables are omitted.
*
* Revision Schedule:
*  09/05 Written by Tom Doan, Estima. Requires v6.10 due to use of
*    %PSUBMAT function.
*
function %ModelCompanion model
type model model
type rect %ModelCompanion
*
local vect[int] depvars
local integer i j k n maxlag
local equation eqn
local rect[int] table
local vect beta
*
compute n=%modelsize(model)
compute depvars = %modeldepvars(model)
*
* Figure out the maximum lag of any dependent variable
* in any equation.
*
compute maxlag=0
do i=1,n
   compute eqn=%modeleqn(model,i)
   compute table=%eqntable(eqn)
   do j=1,%eqnsize(eqn)
      if table(2,j)<=maxlag
         next
      do k=1,%rows(depvars)
         if table(1,j)==depvars(k) {
            compute maxlag=table(2,j)
            break
         }
      end do k
   end do j
end do i
*
compute %ModelCompanion=%zeros(n*maxlag,n*maxlag)
if maxlag>1
   compute %psubmat(%ModelCompanion,n+1,1,%identity(n*(maxlag-1)))
*
do i=1,n
   compute eqn=%modeleqn(model,i)
   compute table=%eqntable(eqn)
   compute beta =%eqncoeffs(eqn)
   do j=1,%eqnsize(eqn)
      do k=1,n
         if table(1,j)==depvars(k) {
            compute %ModelCompanion(i,(table(2,j)-1)*n+k)=beta(j)
            break
         }
      end do k
   end do j
end do i
end


