% ejemplo 5.5, Aström_Adaptive Control, pag. 196
% "Stability depends on the signals amplitudes" 
%   G(s)=1/(s^2+s+1)
% elaboro E.Quintero.M 23jul'98
%-------------------------------------------------
clear
% parametros
time=0; tf=100; gamma=0.1; ucx=1;
uc=ucx; twave=20; u=0; k=1; k0=1; th=0;
dt=0.05;    % integration step size
y1=0; y2=0; ym1=0; ym2=0; 
while(time<(tf-dt))
%--------------------------------------------------------    
      if(abs(time-twave)<dt/2)
         if(uc==ucx) uc=-ucx; else uc=ucx; end
         twave=twave+20;
      end
      u=th*uc;
      dy1=y2;
      dy2=-y1-y2+k*u;
      if(time==0) xx=[time uc y1 ym1 th]; end
%--------------------------------------------------------
      dym1=ym2;
      dym2=-ym1-ym2+k0*uc;
      e=y1-ym1;
      dth=-gamma*ym1*e;                 % MIT rule
%     dth=-gamma*ym1*e/(0.001+ym1*ym1); % normalized MIT rule

      y1=y1+dy1*dt;
      y2=y2+dy2*dt;
      ym1=ym1+dym1*dt;
      ym2=ym2+dym2*dt;
      th=th+dth*dt;

      time=time+dt;
      xx=[xx; time uc y1 ym1 th];
end
format short e
time,gamma,th
subplot(2,1,1),plot(xx(:,1),xx(:,3),xx(:,1),xx(:,4))
subplot(2,1,2),plot(xx(:,1),xx(:,5))
grid