% Simulation of the decentralized controller

% Example 14.3

% Clear memory
clear all

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


% The simulation time (and step size for plotting)
t0 = 0;
tf = 1;
nits = 100;   % used for plotting not simulation step size
t = t0:(tf-t0)/nits:tf;

% This is what to vary for each case-study
ns = 1;
study = struct('param', 'name', 'value', 0, 'fign', 0, 'lnsty', '-');
cs(ns) = study;

% define the case-studies
cs(1).param = 'static';
cs(1).value = 0;
cs(1).fign = 1;
cs(1).lnsty = '-';

% Clear the figures
figure(1); clf

% Loop over the case studies
h = [];
for j=1:ns
  tnext = 0;   % used to dispay the current time

  % define default system/controller parameters
  kappa = 1;
  c = 0.2;
  mu = 1;
  eta = 1;
  x0 = [1; -2];

  % used to easily pass simulation data
  SysData = struct('sys', 'sfb');
  SysData = setfield(SysData, 'x0', x0);
  SysData = setfield(SysData, 'kappa', kappa);
  SysData = setfield(SysData, 'c', c);
  SysData = setfield(SysData, 'mu', mu);
  SysData = setfield(SysData, 'eta', eta);

  % Reset values according to the current case-study
  eval(sprintf('SysData.%s = cs(%d).value;', cs(j).param, j));

  % Define the system initial conditions
  x0 = [SysData.x0];

  % Run the simulation
  opts = '';
  fprintf('Running case-study #%d\n', j);
  [t, x] = ode45(sysname, t, x0, opts, SysData, 'deriv');

  % Define the system outputs
  y = zeros(length(t), 2);  % needs to be the size of the output vector
  for i=1:length(t);
    tmp = feval(sysname, t(i), x(i,:), '', SysData, 'output');
    tmp = tmp(:);  % make sure it fits
    y(i, :) = tmp';
  end

  % Plot the results
  figure(cs(j).fign); hold on;
  h = plot(t, y(:,1), cs(j).lnsty);
  h = [h; plot(t, y(:,2), ':')];
  set(h, 'LineWidth', 1.5);

end

% without adaptation
figure(1);
axis([0, tf, -2, 2]);
xlabel('t');
eval(sprintf('print -deps %s_a\n', exname));  % print out the results
