% ejemplo 5.7, aström, pag. 206
% "first-order MRAS based on stability theory"
% continuous system mras 
% MRAS for first-order system with reference model
%   Gm(s)=bm/(s+am)
% and a controller having two parameters th1 y th2
% elaboro E.Quintero.M 9jul'98
%-------------------------------------------------
clear
% parametros
time=0; tf=100; tprint=0.2;
a=1; b=0.5; am=2; bm=2; gamma=1;
dt=0.005;    % integration step size
uc=1; twave=10; th1=0; th2=0;
y=0; ym=0; u=0; 
while(time<(tf-dt))
%--------------------------------------------------------
      if(abs(time-twave)<dt/2)
         if(uc==1) uc=-1; else uc=1; end
         twave=twave+10;
      end
      dy=-a*y+b*u;
      if(time==0) xx=[time uc y ym u th1 th2]; end
%--------------------------------------------------------
      dym=-am*ym+bm*uc;
      e=y-ym;
      dth1=-gamma*e*uc;
      dth2=gamma*e*y;
      u=th1*uc-th2*y;

      y=y+dy*dt;
      ym=ym+dym*dt;
      th1=th1+dth1*dt;
      th2=th2+dth2*dt;

      time=time+dt;
      if(time>=tprint)
         xx=[xx; time uc y ym u th1 th2];
         tprint=tprint+0.2;
      end
end
format short e
time,gamma,th1,th2
figure
subplot(2,1,1),plot(xx(:,1),xx(:,3),xx(:,1),xx(:,4))
subplot(2,1,2),plot(xx(:,1),xx(:,5))
figure
subplot(2,1,1),plot(xx(:,1),xx(:,6),[0 tf],[bm/b bm/b],'g--')
subplot(2,1,2),plot(xx(:,1),xx(:,7),[0 tf],[(am-a)/b (am-a)/b],'g--')
figure
subplot(1,1,1),plot(xx(:,6),xx(:,7),[1 4.5],[-1 2.5],'g--')