%
%  driver for an state variable implementation of a plant
%
  clear variables
%
  Ts = 0.1;
  Tf = 3.0;
  t = [0:Ts:Tf];
  N = length(t);
%
%  determine the input (reference) signal
%
  r = ones(1,length(t));
  r = sin(4*pi*t);
% 
% prepare the reference signal and the corresponding time for Simulink
%
  rt = [t' r'];
%
% determine the state model
%
  a1 = 0.1; a2 = 0.2;
  b0 = 0.3; b1 = 0.4; b2 = 0.5;
  G = [0 1; -a2 -a1];
  H = [0; 1];
  C = [(b2-a2*b0) (b1-a1*b0)];
  D = b0;
  %[num_G, den_G]  = ss2tf(G,H,C,D)
  [n,m]=size(H);
%
%  determine the desired closed loop pole locations
%
  dp = [0.1 0.2];
%
%  determine the state feedback gain
%
  K = acker(G,H,dp)
%
%  simulate the step response in Matlab
%
  x = zeros(n,N);
  y = zeros(1,N);
  for k=2:N;
      x(:,k) = (G-H*K)*x(:,k-1)+H*r(k-1);
      y(k-1) = (C-D*K)*x(:,k-1)+D*r(k-1);
  end;
%
%  run the simulation
%
  sim('closedloop_state_model');
%
%  Now plot the results
%
figure;
plot(t,y,'o',ts,ys,'+'); grid; 
legend('Simulink ','Matlab');
xlabel('Time'); ylabel('y value');
 