
function [F, Q, H]=build_companionform(A,p,Q_start,H_start)

nstates=size(A,1);
if size(A,2)~=nstates*p
    error('Matrix size not conformable with lags');
end
F=zeros(nstates*p,nstates*p);
for lag_iter=1:p 
    F(1:nstates,(lag_iter-1)*nstates+1:lag_iter*nstates)=A(:,(lag_iter-1)*nstates+1:lag_iter*nstates);
end
F(nstates+1:nstates*p,1:nstates*(p-1))=eye(nstates*(p-1),nstates*(p-1));

if nargin>=3
    Q=zeros(nstates*p,nstates*p);
    Q(1:nstates,1:nstates)=Q_start;
end
if nargin>=4
    nobservables=size(H_start,1);
    H=zeros(size(H_start,1),nstates*p);
    H(1:nobservables,1:nstates)=H_start;
end
 if nargin>=5
    nobservables=size(H_start,1);
    H=zeros(size(H_start,1),nstates*p);
    H(1:nobservables,1:nstates)=H_start;   
  
    
end