%
% Function to do the backward recursion of discrete Riccati equation:
%    S_k = A^T[S_{k+1} - S_{k+1}(B^TS_{k+1}B + R)^{-1}B^TS_{k+1}]A+C^TQC
% from N with S_N = C^TPC and P given to i.
% 
% Input variables:
%    A   - State-space A matrix.
%    B   - State-space input matrix.
%    C   - State-space output matrix.
%    P   - Weighting matrix.
%    Q   - State weighting matrix.
%    R   - Input weighting matrix.
%    i   - Initial time (final time for recursion).
%    N   - Final time (initial time for recursion).

%    Mu-tools must also be installed.

%
% Written by: Kjetil Havre,  6/2-1996.
%
function S = dricint0(A,B,C,P,Q,R,i,N)

   S  = C.'*P*C;            Sa  = S;
   IDA = N;
   
   for j=N-1:-1:i
      S  = A.'*(S - S*B*inv(B.'*S*B+R)*B.'*S)*A+C.'*Q*C;
      Sa  = [S;Sa];
      IDA = [j;IDA];
   end
   S  = vpck(Sa,IDA);
end
