function [thm,yhat,p,phi,psi] = rpem(z,nn,adm,adg,th0,p0,phi,psi)
%RPEM Computes estimates recursively for a general model using the
% Recursive Prediction Error Method
%
% [THM,YHAT] = rpem(Z,NN,adm,adg)
%
% Z: The output-input data z=[y u] (Multiple input is allowed)
% NN : NN=[na nb nc nd nf nk], The orders and delay of a general
% input-output model (see HELP PEM)
% adm: Adaptation mechanism. adg: Adaptation gain
% adm='ff', adg=lam: Forgetting factor algorithm, with forg factor lam
% adm='kf', adg=R1: The Kalman filter algorithm with R1 as covariance
% matrix of the parameter changes per time step
% adm='ng', adg=gam: A normalized gradient algorithm, with gain gam
% adm='ug', adg=gam: An Unnormalized gradient algorithm with gain gam
% THM: The resulting estimates. Row k contains the estimates "in alpha-
% betic order" corresponding to data up to time k (row k in Z)
% YHAT: The predicted values of the outputs. Row k corresponds to time k.
% Initial value of parameters(TH0) and of "P-matrix" (P0) can be given by
% [THM,YHAT,P] = rpem(Z,NN,adm,adg,TH0,P0)
% Initial and last values of auxiliary data vectors phi and psi are
% obtained by [THM,YHAT,P,phi,psi]=rpem(Z,NN,adm,adg,TH0,P0,phi0,psi0).
%
% See also RARMAX, RARX, ROE, RBJ AND RPLR.
% L. Ljung 10-1-89
% Copyright (c) 1989-90 by the MathWorks, Inc.
% All Rights Reserved.
[nz,ns]=size(z);nu=ns-1;
if ns==1,error('Use RARMAX instead for a time series!'),end
nll=length(nn);
if length(nn)~=3+3*nu,error('An incorrect number of orders is specified. nn should be [na nb nc nd nf nk] with nb, nf and nk of length = # of inputs!'),end
na=nn(1);nb=nn(2:ns);nc=nn(ns+1);nd=nn(ns+2);
if any(nb==0),error('If (some) nb is zero, please remove that input first!'),end
nf=nn(ns+3:ns+2+nu);nk=nn(ns+3+nu:ns+2+2*nu);
if any(nk<1),error('Sorry, this routine requires nk>0; Shift input sequence if necessary!'),end