% Listing 14.2 of the book for Example 14.2
% "Principles of System Identification: Theory and Practice"

% Arun K. Tangirala
% September 04, 2015
% Freely distributed under no warranty

%% Generate data

% Process
Gp = idpoly(1,[0 0 0.3 1 0.5 0.2],1,1,1,'Noisevariance',1,'Ts',1);

% Generate input
uk = idinput(510,'prbs',[0 0.4],[-1 1]);
N = length(uk);

% Simulate the process
xk = sim(Gp,uk);
Gp.Noisevariance = var(xk)/10;
yk = sim(Gp,uk,'Noise');

% Plot the input-output data
zk = iddata(yk,uk,1);

%% Estimate 11 IR coefficients of a FIR model

% Construct output vector
M = 11;
Y = yk(M:end);

% Construct regressors
Phimat = [];
for k1 = 0:M-1,
    Phimat  = [Phimat uk(M-k1:end-k1)];
end

% OLS estimates of IR models
ir_est = pinv(Phimat)*Y;

%% Residual analysis

% Predictions
Yhat = Phimat*ir_est;

% ACF of residuals and CCF between residuals and inputs
[acfval,lags] = xcov(Y-Yhat,20,'coeff');
[ccfval,lags] = xcov(Y-Yhat,uk(M:end),20,'coeff');