
function [Coeff,Res,Xrec] = f(X,Xmean,U,n)
%
% Syntax:  [Coeff,Res,Xrec] = project(X,Xmean,U,n);
%
% This function computes the n-index projection coefficients for
% X using the eigenvectors in U
%
% Xrec is the reconstruction using the first n eigenvectors
% Res is the residual (distance-from-feature-space) per pixel

% ----------------------------------------------------------------------


[N,M]=size(U);
[Nx,Mx]=size(X);

Xm = Xmean*ones(1,Mx);
P = X - Xm;

Un = U(:,n);
Coeff = Un'*P;

if nargout>=2
 Ex = diag(P'*P);
 Ec = diag(Coeff'*Coeff);
 Res =  Ex - Ec;
 Res = Res/Nx;	% make the residual error normalized (per pixel)
end

if nargout==3
 Xrec = Xm + Un*Coeff;
end;

