% 3F2 Examples Paper 3 question 8.
% Need to set up -alpha =  the desired poles of the observer
% and  -beta =  the desired poles of the closed loop with state fb.
% and fact = extra gain factor.

A=[0 0 ; 0 -1];
B=[1; -2];
C=[1 1];
D=0;

bode(A,B,C,D)
title('Nominal open loop Bode diagram')
disp('hit a key to continue')
pause

% 
L=[alpha^2; -(1-alpha)^2];

K=[beta^2 0.5*(1-beta)^2];

M=beta^2;

st_fb_poles=eig(A-B*K)
obs_poles=eig(A-L*C)

Aa=A;
Ba=B;
Ca=fact*C;
Da=fact*D;


Ac=[Aa -Ba*K; L*Ca A-B*K-L*C];
Bc= [Ba*M zeros(2,1); B*M L];
Cc=[Ca zeros(1,2); zeros(1,2) -K];
Dc=[0 0 ; M 0];

disp('closed loop poles = ')
disp(eig(Ac))

t=0:.01:5;
v=0.01*randn([length(t),1]);

r=ones([length(t),1]);

figure(1)
y=lsim(Ac,Bc,Cc,Dc,[r v],t);
plot(t,y)
grid
title(['Step response, y and u,  for alpha = ',num2str(alpha),',    beta = ' ...
,num2str(beta),',  fact = ',num2str(fact) ])
legend('output y','input u');
disp('hit a key to continue')
pause;

%loop gain
figure(2)
[Al,Bl,Cl,Dl]=series(Aa,Ba,Ca,Da,A-B*K-L*C,L,K,0);
nyquist(Al,Bl,Cl,Dl)                   
axis([-2 2 -2 2])  
title(['Nyquist diagram for alpha = ',num2str(alpha),',    beta = ' ...
,num2str(beta),',  fact = ',num2str(fact)])

% disp('The step response can be replotted by typing')
% disp('>> plot(t,y)')

