% This is a macro used to create the plots for discrete-time controllers

% Example 13.5


% Clear memory
clear all

% Define the input file names
exname = 'extdisc_ex5';    % the name of this macro
sysname = [exname, 'sys'];

% Define some system parameters
maxits = 100+1;

% define the desired reference
r = ones(maxits+3, 1);

% Simulate the scaler case
kappa = 0.8;
state = zeros(maxits, 3);
state(1,:) = [0, 0, 0];
xk1 = zeros(3,1);
k = 0:maxits;
k = k(:);
for i=1:maxits

  % get the current states
  xk = state(i, :)';

  % define the error variables
  ki = k(i);
  err = xk(1) - r(i);

  % define the control input
  uk = (r(i+3) - xk(1)*xk(1) + 2*xk(3) + kappa*err)/2;

  % advance the state
  xk1(1) = xk(2);
  xk1(2) = xk(3);
  xk1(3) = xk(1)*xk(1) - 2*xk(3) + 2*uk;
  state(i+1, :) = xk1';
end
x_sc = state;


% Simulate the scaler case
kappa = 0.8;
state = zeros(maxits, 3);
state(1,:) = [0, 0, 0];
xk1 = zeros(3,1);
t = poly([0.8, 0.8, 0.8]);
c1 = t(4); c2 = t(3); c3 = t(2);
for i=1:maxits

  % get the current states
  xk = state(i, :)';

  % define the error variables
  ki = k(i);
  err1 = xk(1) - r(i);
  err2 = xk(2) - r(i+1);
  err3 = xk(3) - r(i+2);

  % define the control input
  uk = (r(i+3) - xk(1)*xk(1) + 2*xk(3) - c1*err1 - c2*err2 - c3*err3)/2;

  % advance the state
  xk1(1) = xk(2);
  xk1(2) = xk(3);
  xk1(3) = xk(1)*xk(1) - 2*xk(3) + 2*uk;
  state(i+1, :) = xk1';
end
x_v = state;
A = [0 1 0; 0 0 1; -c1 -c2 -c3];
fprintf('eigenvalues of A for vector case ...\n');
eig(A)


figure(1); clf; hold off
h1 = stairs(k, x_sc(:,1), '--'); hold on
h2 = stairs(k, x_v(:,1));
xlabel('k');
axis([0, 100, 0, 1.2])
h3 = plot([0; 100], [1; 1], ':');
set([h1, h2, h3], 'LineWidth', 1.5);

% print out the results
eval(sprintf('print -deps %s_a\n', exname));
