% Problem 8.6
disp('Problem 8.6')
disp('Uncompensated system:')
K=3;
n=[0 0 0 1 10];
d=conv([1 20 0],[1 2 10]);
printsys(n,d,'s')

% Steady state unit ramp error
Kv=K*n(length(n))/d(length(d)-1);

disp('Unit ramp steady state error:')
ess_r=1/Kv

subplot(221)
rlocus(n,d)
axis([-25 10 -20 20])
title('(a) Original system')

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

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

disp('(b) System with PI controller:')
n_c=conv(n,[1 0.05]);
d_c=conv(d,[1 0]);
printsys(n_c,d_c,'s')

% Steady state unit ramp error of compensated system
Kvc=K*n_c(length(n_c))/d_c(length(d_c)-1);
disp('Steady state unit ramp error of compensated system')
ess_rc=1/Kvc

subplot(222)
rlocus(n_c,d_c)
axis([-25 10 -20 20])
title('(b) System with PI controller')

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

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

% Step response
t=0:0.2:50;
[y,x]=lsim(ncl,dcl,t,t);
[yc,xc]=lsim(n_ccl,d_ccl,t,t);
subplot(212)
plot(t,t,':',t,y,'--',t,yc,'-')
axis([0 50 0 50])
xlabel('time [s]')
ylabel('y, yc')