function [sys,x0,str,ts] = rls(t,x,u,flag,tv,n)
% tv - sampling time
% n - length of the input vector (n = num. of parameters + 1 )
% u = [y; z]  

  switch flag,
  case 0,
    [sys,x0,str,ts]=mdlInitializeSizes(tv,n-1);
  case 2,
    sys=mdlUpdate(t,x,u,n-1);
  case 3,
    sys=mdlOutputs(t,x,u,n-1);
  case 9,
    sys=mdlTerminate(t,x,u);
  otherwise
    error(['Unhandled flag = ',num2str(flag)]);
end

function [sys,x0,str,ts]=mdlInitializeSizes(tv,n)
  sizes = simsizes;

  sizes.NumContStates  = 0;
  sizes.NumDiscStates  = n*(n+1);
  sizes.NumOutputs     = n;
  sizes.NumInputs      = n+1;
  sizes.DirFeedthrough = 0;
  sizes.NumSampleTimes = 1;  
  
  sys = simsizes(sizes);

  theta=(1:n)'*0.01;
  p=eye(n,n)*1e6;
  x0  = [theta;p(:)];

  str = [];

  ts  = [tv 0];

function sys=mdlUpdate(t,x,u,n)
  p =zeros(n,n);
  theta=zeros(n,1);
   
  theta(:)=x(1:n);
  p(:)=x(n+1:n+n*n);

  y=u(1);
  z=u(2:n+1);
  % begin
  e=y-z'*theta;
  gamma=1/(1+z'*p*z);
  l=gamma*p*z;
  p=p-gamma*p*z*z'*p;
  theta=theta+l*e;
  % end
  sys = [theta(:);p(:)];

function sys=mdlOutputs(t,x,u,n)
  sys=x(1:n);

function sys=mdlTerminate(t,x,u)
  sys = [];
