106
function [sys, x0, str, ts] = rlsestsMISO(t,x,u,flag,nstates,lambda,dt)
global newerr;
global ykanterior;
global phianterior;
%RLSESTS S-function to perform system identification.
%
% This M-file is designed to be used in a Simulink S-function block.
% It performs parameter estimation using the Recursive Least Squares
% Parameter Estimation Algorithm with Exponential Data Weighting
%
% The input arguments are
%
% nstates: the number of states in the states vector
% lambda: the exponential data weighting factor
% dt: how often to sample points (secs)
%
% The RLS estimator is defined by the following equations:
%
% 1 P(k-2) * phi(k-1) * [y(k) - phi(k-1)'theta(k-1)]
% theta[k] = theta[k-1] + ------ * -------------------------------------------------
% lambda lambda + phi(k-1)' * P(k-2) * phi(k-1)
%
% 1 P(k-2) * phi(k-1) * phi(k-1)' * P(k-2)
% P(k-1) = ------ * ----------------------------------------
% lambda lambda + phi(k-1)' * P(k-2) * phi(k-1)
%
% where:
%
% theta: the parameter estimates
% phi: the state vector
% P: the covariance matrix
% lambda: the exponential data weighting factor
%
% See also SFUNTMPL., "Adaptive Filtering, Prediction, and Control",
% G. C. Goodwin & K. S. Sin.
% Copyright (c) 2001 by Otacílio da Mota Almeida.
% Changed by Eber de Castro Diniz for MISO case
if abs(flag) == 2 % flag = 2 --> real time hit
% sample hit, return the next discrete states, which are the
% next parameter estimates
theta = x(1:nstates+1); % parameter estimates(this is the anterior
theta
P = zeros(nstates+1,nstates+1); % get covariance matrix
P(:) = x(nstates+2:(nstates+1+(nstates+1)*(nstates+1)));
yk = u(nstates - 1); % system output
phi = [u(1:nstates-2)' newerr]'; % state vector
est_err = yk - phi' * theta; % estimation error
den = 1 + phi' * P * phi; % lambda + phi' * P * phi
theta_new = theta + P * phi * (est_err / den);% new parameter estimates
Pnew = (P - P * phi * phi' * P / den) / 1; % new covariance
newerr(3)=newerr(2);
newerr(2)=newerr(1);
newerr(1) = yk - phi' * theta_new;
ykanterior = yk;
phianterior = phi;
sys = [theta_new', Pnew(:)']'; % return them
elseif flag == 4 % flag = 4 --> Return next sample hit