% Listing 14.7 of the book
% "Principles of System Identification: Theory and Practice"

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

p = size(Phi,2);	% size of parameter vector
[Q,R,P] = qr(Phi);  % full factorization
zvec = Q'*Y;
Theta = inv(R(1:p,1:p))*zvec(1:p,:)
pred_err = zvec(p+1:end,:);	% residuals 
[Q,R,P] = qr(Phi,0); % economy factorization
Theta = inv(R)*Q'*Y	% only parameters can be obtained
[Ps,indP] = sort(P); % Arrange the theta vector
Theta = Theta(indP);