function [A,B]=adaptinGPC(rlsdata)
%Adaptiver based on RLS method
%rlsdata is data from the GPC function

global H b fmark w A B ypast uopt yrls urls beta P K
%H,b and fmark is variables in the costfuntion
%w is the setpoint trajectory
%A and B is modelparamters
%ypast is the past mesured values
%uopt is the optimal control signal found by the GPC algorithm
%yrls and urls is vectors the past vector is made from
%beta is the parameter estimate in a column vector, P is the covar. matrix
%and K is the gain vector

%Save the past data
yrls=[ypast(1);yrls]; %update the past measurement vector
urls=[uopt;urls]; %update the past control signals vector
i=size(yrls,1); %count how many data the rls algorithm has

%Choose values for the degree of polynomnials and the deadtime
n=3;  %Degree of the A polynominal
m=5;  %Degree of the B polynominal
d=2;  %Deadtime

%Test if there is enough data to run RLS
if i>=m+d+1
   %Constants
   c=1000; %for initializing of the P matrix
   gama=0.9;%forgetting factor
   alfa=0.0224; %variance to the error, found from PRBS-data
  
   %Initializing of the system
   beta_init=zeros(n+m,1); %initialize the beta-vector
   I=eye(m+n);%identity matrix
   Pinit=c*I; %initialize the P matrix
   ksi=[yrls(2:n+1);urls(d+2:m+d+1)]; %vector with past data from measurement and ctrl signal
   
   %Compute model prediction
   if i==m+d+1
      ypred=ksi'*beta_init; %if the loop runs the first time, uses the initlized beta
   else
      ypred=ksi'*beta; %if the loop runs 2nd time or more, uses the beta from last run
   end
      
   %Update gain vector
   if i==d+m+1
      K=(Pinit*ksi)./(alfa*gama+ksi'*Pinit*ksi); 
   else
      K=(P*ksi)./(alfa*gama+ksi'*P*ksi);
   end
   
   %Update parameter estimates
   if i==d+m+1
      beta=beta_init+K*(yrls(1)-ypred);
      A=[1;-beta(1:n)]'; %update modelparameter A. The first coeff is always 1
      B=[zeros(d,1);-beta(n+1:m+n)]';%updata B. -beta comes from different definition of A and B in RLS and GPC
   else
      beta=beta+K*(yrls(1)-ypred);
      A=[1;-beta(1:n)]';
      B=[zeros(d,1);-beta(n+1:m+n)]';
   end
      
   %Compute covariance matrix for next iteration
   if i==d+m+1
      P=(1/gama)*(I-K*ksi')*Pinit;
   else
      P=(1/gama)*(I-K*ksi')*P;
   end
else %else if i>m+d+1
   %if not enough data, the PRBS model is used
   A=[1  -0.4548 0.0218 -0.5309]; %A given from the PRBS data
   B=[0 0 -0.0235 0.0552 0.0255 0.0414 -0.0058]; %B given from the PRBS data
end %end if i>m+d+1
