% piecewise.m - Response to piecewise constant inputs
% KJA, Aug 06

aminit;

% Use the coupled spring massi system, with normalized steady state gain
sys = springmass();
sys = sys / freqresp(sys, 0);
x0 = [2, -1];

% Set up the parameters for the plot
Tmax = 8;				% final time
Tsim = 15;				% max simulation time
Tinc = 1;				% step increment
Nper = 0.5;				% number of periods of sinusoid
Sstp = 10;				% simuation steps between periods

% Generate a piecewise constant approximation to a sinusoid
figure(1); clf; figure(2); clf; 
uvec = []; tvec = []; uprv = 0;
for t = 0:Tinc:Tmax-Tinc
  % Generate the input for this segment
  u = sin(t/(Tmax-Tinc)*2*pi*Nper);

  % Generate the input plot
  figure(1); subplot(221); hold on;
  plot([t t t+Tinc], [uprv u u], 'b-', 'Linewidth', AM_data_linewidth);
  if (t ~= 0 && t/Tinc < 3)
    plot([t+Tinc Tmax], [u u], 'r--', 'Linewidth', AM_ref_linewidth);
  end

  % And the output plot
  [ysim, tsim] = step(sys, 0:Tinc:Tsim-t);
  figure(2); subplot(221); hold on;
  h2 = plot(tsim+t, ysim*(u-uprv), 'r--', 'Linewidth', AM_ref_linewidth);

  % Now save the input for later complete simulation
  uprv = u;				% save value of u for next run
  uvec = [uvec, u*ones(1, Sstp)];
  tvec = [tvec, t:Tinc/Sstp:t+Tinc-Tinc/Sstp];
end;

% Add labels to the input plot
figure(1); hold on;
amaxis([0 8 0 1]); box on;
xlabel('Time (sec)');
ylabel('Input (u)');

% Arrow describing the different signals
arrow([1.3 0], [1.3 0.42], AM_normal_arrowsize); amtext(1.5, 0.2, 'u(t0)');
arrow([2.6 0], [2.6 0.78], AM_normal_arrowsize); amtext(2.8, 0.35, 'u(t1)');
arrow([3.4 0.44], [3.4 0.78], AM_normal_arrowsize); 
amtext(3.6, 0.6, 'u(t1) - u(t0)');

% Generate the output for the entire output
figure(2); hold on;
[uvec] = [uvec, 0*ones(1, Sstp*(Tsim-Tmax)+1)];
[tvec] = [tvec, Tmax:Tinc/Sstp:Tsim];
[ysim, tsim] = lsim(sys, uvec, tvec);
h1 = plot(tsim, ysim, 'b-', 'Linewidth', AM_data_linewidth);
amaxis([0 Tsim -0.6 1.1]); box on;
xlabel('Time (sec)');
ylabel('Output (y)');

lgh = legend(gca, [h1 h2], 'Complete', 'Steps', 'Location', 'southwest');
legend(lgh, 'boxoff');

% Now plot the results
figure(1); amprint('piecewise-input.eps');
figure(2); amprint('piecewise-output.eps');

