% Problem 8.8
disp('Problem 8.8')
disp('(a) Uncompensated system:')
n=[0 0 0 1];
d=conv([1 1],conv([1 5],[1 10]));
printsys(n,d,'s')
subplot(221)
rlocus(n,d)
axis([-15 5 -15 15])
grid
title('Uncompensated system')
Kp=200*n(length(n))/d(length(d));
disp('Steady-state error:')
ess=1/(1+Kp)

disp('Closed-loop system for K=200:')
[ncl,dcl]=cloop(200*n,d,-1)
printsys(ncl,dcl,'s')

disp('Closed-loop poles:')
roots(dcl)

disp('System with a phase-lag compensator:')
nc=[1 0.1];
dc=[1 0.01];
n_c=conv(200*n,nc);
d_c=conv(d,dc);
len_n=length(n_c);
len_d=length(d_c);
Kp_c=n_c(len_n)/d_c(len_d);

while (Kp_c-99) < 0,
   dc(2)=0.9*dc(2);
   d_c=conv(d,dc);
   Kp_c=n_c(len_n)/d_c(len_d);
end

disp('Phase-Lag Compensator:')
printsys(nc,dc,'s')

disp('Steady-state error of the compensated system:')
ess_c=1/(1+Kp_c)
subplot(222)
rlocus(n_c,d_c)
axis([-15 5 -15 15])
grid

axis([-15 5 -15 15])
title('(b) Compensated system')

disp('Closed-loop compensated system for K=200:')
[n_ccl,d_ccl]=cloop(n_c,d_c,-1);
printsys(n_ccl,d_ccl,'s')

disp('Poles of closed-loop compensated system:')
roots(d_ccl)

subplot(212)
t=0:0.2:50;
[y,x]=step(ncl,dcl,t);
hold
[yc,xc]=step(n_ccl,d_ccl,t);
plot(t,y,'--',t,yc,'-')
grid
xlabel('time [s]')
ylabel('y,yc')