function arx_nll = neglogl_arx(Z,params)

% Function file for Example 15.3 of the book
% "Principles of System Identification: Theory and Practice"

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

% RETURNS LOG-LIKELIHOOD FOR MLE OF ARX 
% TO BE USED IN CONJUNCTION WITH arxest_mle.m

% Parse the parameters
yvec = Z(:,1); uvec = Z(:,2); N = length(yvec);
a1 = params(1); b1 = params(2); sigma_e = params(3);

% Predictions and prediction errors
Phi = [-yvec(1:end-1) uvec(1:end-1)];
yhat = Phi*[a1 ; b1];
err_vec = yvec(2:end) - yhat;
% Compute negative log-likelihood and return it
term1 = -(N/2)*log(sigma_e^2);
term2 = -(1/2)*yvec(1)^2*(1 - a1^2)/sigma_e^2;
term3 = -(1/2)*sum(err_vec.^2)/sigma_e^2;
arx_nll =  -(term1 + term2 + term3);