% Listing 22.3 for the function of Example 22.2 of the book on
% "Principles of System Identification: Theory and Practice"

% Arun K. Tangirala
% December 06, 2015
% Freely distributed under no warranty

function V_ts = trimsq(theta,Z,mod_ord,T)
% Function to compute trimmed squares for OE models

% Read nb and nf
nb = mod_ord(1); nf = mod_ord(2); nk = mod_ord(3);

% Construct the model
Bpol = [zeros(1,nk) theta(1:nb)']; Fpol = [1 theta(nb+1:end)'];
mod_oe = idpoly(1,Bpol,1,1,Fpol,'Ts',1);

% Compute one-step ahead prediction errors
pred_err = pe(mod_oe,Z,1);

% Return the objective function
sort_errsq = sort((pred_err.y).^2);
V_ts = sum(sort_errsq(1:T));