% main_clop_data.m
% Matlab script to generate closed loop data set (Y,U)
% A 2nd order SISO system is controlled by a PI controller.
% The reference is perturbed by a Binary Signal.
% The data set may be used in connection with the exercises...

A=[1.5 1;-0.7 0]; B=[2;-1.3]; K=[0.5;0.3];
D=[1 0];

Kp=0.2; Ti=7;

N=1000;
randn('seed',0); rand('seed',0)   % Setting seeds in prbs1 function.
R=prbs1(N,75,175);                % The reference signal

randn('seed',0)
en=randn(N,1)*0.05;                % Innovations noise used.

x=[0;0]; z=0;                     % Initial states

for k=1:N
    y=D*x+en(k);                  % Measurement
    
    e=R(k)-y;                     % The PI controller
    u=Kp*e+z;
    z=z+Kp*e/Ti;
    
    Y(k,1)=y;                     % Soring data
    U(k,1)=u;
    
    x=A*x + B*u +K*en(k);         % Feed control, u_k, to the process
end

subplot(211), plot(U), title('The control, u_k'), grid
subplot(212), plot([R Y]) , title('The reference, r_k, and measurement output, y_k')
grid
