% (c)
b = [1];
a = [1 -2];
sys = tf(b, a);
% plotting the root locus
subplot(121), rlocus(-sys); % for K<=0
subplot(122), rlocus(sys);  % for K>=0
% verifying the values that are stable
r = rlocus(sys, [-2 0 2 4 6]);
actual_signs = sign(r);
wanted_signs = [-1 -1 0 1 1];
if actual_signs ~= wanted_signs
  error('unexpected root locus');
end

% (d)
% deg 4 3  2      1    0
b =  [1 20 150    500  625    ];
a =  [1 0  154.25 87.5 5782.85];
sys = tf(b, a);
% plotting the root locus
subplot(121), rlocus(-sys); % for K<=0
subplot(122), rlocus(sys);  % for K>=0

% (e)
[r,k]=rlocus(sys);
indices = find(real(r)<0 & -5<imag(r) & imag(r)<5)
[i,j] = ind2sub(size(r), indices);
j
% i look for the first j that appears for all values of i
% then I do a binary search between r(j-1) and r(j) to see
% where the prop starts to hold
% from |K|=17.05 to infinity for K>=0
% (fine, this was before I discovered I could just click on the
% plot)

[r,k]=rlocus(-sys);
indices = find(real(r)<0 & -5<imag(r) & imag(r)<5)
[i,j] = ind2sub(size(r), indices);
j
% from |K|=6.943 to infinity for K<=0

% (f)
hb = [1 3 27.25];
ha = [1 0 -4];
H = tf(hb, ha);
mb = ha;
ma = [2 2*sqrt(2) 23];
M = tf(mb, ma);
% plotting the root locus
subplot(121), rlocus(-H); % for K<=0
subplot(122), rlocus(H);  % for K>=0

% (g)
[r,k] = rlocus(-H);
% |K|>1 for K<=0
[r,k] = rlocus(H);
% from |K|=0.147 to infinity for K>=0

% (h)
% K=1 gives poles with real part -0.75
bk = hb;
ak = ha+hb;
Qk = tf(bk, ak);

% (i)
t = [0:0.1:5];
sq = step(Qk, t);
% (j)
% the compensated system is M(s)H(s)
%C = M*H;
%[bc, ac] = tfdata(C);
bc = hb;
ac = ma;
C = tf(bc, ac);
sc = step(C, t);
% (k)
figure;
plot(t, sq);
hold on;
plot(t, sc, 'r');
legend('Q(s)', 'Hc(s) = M(s)H(s)');
% (m)
be = [1 3 27.25];
ae = [1 -0.01 -4.02];
% (n)
He = tf(be, ae);
bke = be;
ake = ae+be;
Qke2 = tf(bke, ake);
Qke = He/(1+He);
sqe = step(Qke, t);
figure;
plot(t, sq, 'b');
hold on;
plot(t, sqe, 'r');
legend('Q(s)', 'Qe(s)');
% (o)
Ce = M*He;
[bce, ace] = tfdata(Ce, 'v');
sce = step(Ce, t);
figure;
plot(t, sc, 'b');
hold on;
plot(t, sce, 'r');
legend('Hc(s)', 'Hce(s)');
