% Ex2_half:
% Model reduction by the half rule

clear all
k=2;T1=6; T2=4; T3=2; T4=1;
s=tf('s');
hp=k/((1+T1*s)*(1+T2*s)*(1+T3*s)*(1+T4*s));
% 1st order model+delay (inverse response) mod. approx.
T=T1+T2/2; tau_1a=T2/2+T3+T4; p=0;
hp_1a=k*(1-tau_1a*s)/(1+(T+p)*s);
% 2nd order model+delay (inverse response) mod. approx.
T1_2a=T1; T2_2a=T2+T3/2; tau_2a=T3/2+T4;
hp_2a=k*(1-tau_2a*s)/((1+T1_2a*s)*(1+T2_2a*s));

[Y,t]=step(hp);
[Y_1a]=step(hp_1a,t);
[Y_2a]=step(hp_2a,t);

figure(1)
plot(t,Y,'-',t,Y_1a,'-.',t,Y_2a,'--'), grid
legend('Model response','1st order approx','2nd order approx')
title('Model response and 1st and 2nd order approximations')
xlabel('Time')


% PI control
%T=9
Kp=T/(2*k*tau_1a);
Ti=T;

hc=Kp*(1+Ti*s)/(Ti*s)

h0=series(hc,hp)
h_ry=feedback(h0,1)

figure(2)
step(h_ry);