function [matched_individual,bestmatchdistance]=eigenfaces_classify(test,training,n);
%classifies using n principal components, closest match
[w, h, nExpressions, nIndividuals]=size(training);
X=reshape(training,[w*h,nIndividuals*nExpressions]);
avg=mean(X,2);
Xd=bsxfun(@minus,X,avg);
[U,S,V]=svd(Xd,0);
Xt=reshape(test,w*h,numel(test)/(w*h));
Xtd=bsxfun(@minus,Xt,avg);
scores=U(:,1:n)'*Xtd;
trainingscores=U(:,1:n)'*Xd;
%normalize scores and samples
%scores=bsxfun(@rdivide,scores,sqrt(sum(abs(scores).^2)));
%trainingscores=bsxfun(@rdivide,trainingscores,sqrt(sum(abs(trainingscores).^2)));
%cosine similarity
%C=scores'*trainingscores;
%[bestmatchdistance bestmatchindex]=max(C,[],2);
%matched_individual=ceil(bestmatchindex/nExpressions);

%Euclidean distance
distanceMatrix=nan(size(scores,2),size(trainingscores,2));
for i=1:size(scores,2)
    for j=1:size(trainingscores,2)
        distanceMatrix(i,j)=norm(scores(:,i)-trainingscores(:,j));
    end
end
[bestmatchdistance bestmatchindex]=min(distanceMatrix,[],2);
matched_individual=ceil(bestmatchindex/nExpressions);
if numel(test)==w*h
   subplot(1,2,1);
   imagesc(test);
   colormap(gray);
   subplot(1,2,2);
   imagesc(reshape(X(:,bestmatchindex),[w,h]));
   colormap(gray);
   disp('best match distance=');
   disp(bestmatchdistance);
end