% Kap 11.3
% Fasretarderande kompensering
% Motor G(s)=100/(s(s+10))
% M?l: Minska rampfel en faktor 10
% G_K=(s+0.8)/(s+0.08)

s=tf('s');
gp=100/(s*(s+10));
t=0:0.01:10;
ramp=t';
gcl=feedback(gp,1);
y=lsim(gcl,ramp,t);
e=ramp-y;
figure(1)
plot(t,e)
axis([-1 10 0 0.14])
hold on

figure(2)
bode(gp); grid on; hold on;
allmargin(gp)

%     GainMargin: Inf
%    GMFrequency: Inf
%    PhaseMargin: 51.8273
%    PMFrequency: 7.8615
%    DelayMargin: 0.1151
%    DMFrequency: 7.8615
%         Stable: 1

M=10;
marg=allmargin(gp);
wc=marg.PMFrequency
a=wc/M;

gk=(s+a)/(s+a/M)
bode(gk*gp,'r')

gcl2=feedback(gk*gp,1);
y2=lsim(gcl2,ramp,t);
e2=ramp-y2;
figure(1)
plot(t,e2,'r')
axis([-1 10 0 0.14])

% Also check what happens to control signal
gu = feedback(gk,gp);   % (think..)
u=lsim(gu,ramp,t);
figure(1)
plot(t,u,'k')



% Where are the closed loop poles?
% uncomment to see root locus

%closedloopwith1=zpk(gcl)
%closedloopwithgk=zpk(gcl2)

%figure(3)
%rlocus(gp);hold on
%R=rlocus(gp,1);
%plot(R,'b*')
%axis([-20 0 -12 12])
%rlocus(gp*gk);
%R2=rlocus(gp*gk,1);
%plot(R2,'r*')




