clear all
close all
clc

%---------------
% MODEL MATCHING
%---------------
%%
s=tf('s');
G=1.432/ ((s+2.293)*(s+0.876)) %(0.498*s^2+1.578*s+1);


%% find suitable model
M = 1/(s/4.8+1)^2

%%
step(M);

%% evaluate controller
K = M/(G*(1-M));
pole(K)
zero(K)


%% command response
Gr = feedback(series(K,G),1);
figure;
step(Gr)

%% input disturbance
 Gd = G/(1+G*K);
 figure;
 step(Gd);













%% --------
% IMC
%--------

clear all

%% plant
s = tf('s');
G = -(s-1)*exp(-s)/(s^2+s+1)


%%  ideal KIMC
GMP = (s+1)/(s^2+s+1)
KIMC1 = 1/GMP
p1 = pole(KIMC1);
z1 = zero(KIMC1);

%% prefilter
T=0.05;
V = 1/(T*s+1);

%% real KIMC
KIMC2 = series(V,KIMC1);
K = KIMC2/(1-KIMC2*G);

%% reference input step response of closed loop
Gr = feedback(K*G,1);
figure;
step(Gr)


%% Bode Plots
figure;
bode(Gr);
hold on
bode(1-Gr)
hold off

%% Multiplicative uncertainty
DeltaM = 0.01*(s/0.001+1)/(s/0.01+1);

figure;
bode(V);
hold on
bode(1/DeltaM);
hold off




















%% ----------------
% Smith Predictor
%----------------
 clear all
 
%% Plant
s = tf('s');
G = exp(-93.3*s)*5.6/(40.2*s+1);
figure
step(G);
 
%% PI-controller
K = 0.0501*(1+1/(47.35*s));
Gr1 = feedback(series(K,G),1);
figure;
step(Gr1);

%% Increase K
K = 0.07*(1+1/(47.35*s));
Gr2 = feedback(series(K,G),1);
hold on
step(Gr2);
hold off

%% Smith Predictor - proportional controller
GR = 5.6/(40.2*s+1);
% steady state error determines gain
KR = 17.67;
%
K = KR/(1+KR*GR*(1-exp(-93.3*s)));
figure;
step(feedback(series(KR,GR), 1))

%% compare with PI controller
GrSP = feedback(series(K,G),1);
figure;
step(Gr1)
hold on
step(Gr2)
step(GrSP)
hold off