% Problem 9.11
clear
% (a) System model for T=0
num=[0 0 10];
den=conv([1 4],[1 10]);
% system with approximate time delay
num1=[0 0 0 10];  
den1=conv(den,[0.5 1]); 
w=logspace(-1,2);

% (a)
bode(num,den,w);
hold on
bode(num1,den1,w);
hold off
[mag,phase]=bode(num,den,w);
[mag1,phase1]=bode(num1,den1,w);
[Gm,Pm,Wcg,Wcp] = margin(num,den);
[Gm1,Pm1,Wcg1,Wcp1] = margin(num1,den1);

fprintf('\nSystem without delay:\n')
fprintf('     Gain margin  = %f dB\n',20*log10(Gm))
fprintf('     Phase margin = %f rad/s\n',Pm)
fprintf('\nLinearized system with delay T=0.5s:\n')
fprintf('     Gain margin  = %f dB\n',20*log10(Gm1))
fprintf('     Phase margin = %f rad/s\n',Pm1)
fprintf('\n\n PRESS A KEY!\n')
pause

% (b)
[cNum,cDen]=cloop(num,den,-1);     % System without delay
[cdNum,cdDen]=cloop(num1,den1,-1); % System with delay
t=0:0.05:5;
[y,x]=step(cNum,cDen,t);           %step response without delay
[yd,xd]=step(cdNum,cdDen,t);       %step response with delay
figure(2)
plot(t,y,'-',t,yd,'--')
grid
xlabel('time [s]')
ylabel('y(t), y(t-T)')
print -deps sol9_11b

% (c)
ess=0.02;
Kp=(1-ess)/ess;
K=Kp*den(length(den))/num(length(num));
fprintf('\nStatic gain K (which gives ess=0.02) = %f\n',K)
fprintf('\n\n PRESS A KEY!\n')
pause
