% Continuous process dynamics

a = -2;
b = -1.3;
V = 5;

A = [a 0 0; 1 0 0; 0 -V 0];
B = [b; 0; 0];
C = [0 0 1];
Gp = ss(A,B,C,0);

% Sampled process

h = 0.2;
Hp = c2d(Gp,h);
[Phi,Gamma] = ssdata(Hp);

% State feedback design

wc = 1;                           % speed of state feedback
pc = wc*roots([1 2 2 1]);         % control poles in continuous time
pcd = exp(pc*h);                  % control poles in discrete time

L = place(Phi,Gamma,pcd);

% Extended observer design to obtain integral action

wo = 2;                           % speed of observer
po = wo*roots([1 2 2 1]);         % observer poles in continuous time
pod = exp(po*h);                  % observer poles in discrete time

K = place(Phi',C',pod)';

% naive reference handling

Hcl = ss(Phi-Gamma*L,Gamma,C,0,h);
Lc = 1/dcgain(Hcl);

% reference generator

wm = 2;                          % speed of model
pm = wm*roots([1 3 3 1]);        % model poles in continuous time
pmd = exp(pm*h);                 % model poles in discrete time

Lm = place(Phi,Gamma,pmd);

Hm = ss(Phi-Gamma*Lm,Gamma,C,0,h);
Lcm = 1/dcgain(Hm);

% form the controller and check stability margins

refgen = ss(Phi-Gamma*Lm,Gamma*Lcm,[-Lm; eye(3)],[Lcm; zeros(3,1)],h);
observer = ss(Phi-K*C,[Gamma K],eye(3),zeros(3,2),h);
ctrl = ss(Phi-Gamma*L-K*C,K,L,0,h);
proc = ss(Phi,Gamma,C,0,h);
margin(proc*ctrl)

