% Principal component projection for reducing the dimensions of the feature sets
  
function [proj_data, e_vec_s, num]=pcp(trn_dat, eig_num)

% N is the size of sample data; M is the number of feature;
% trn_dat is the original data set, last column is its class
% eig_num is the selected transformation feature, ex: [1 2 3] or [3 4 5], almost using 1st 2nd or 3rd ... 
% proj_data is the transformed projection data
% e_vec_s is transformation matrix
 
%if nargin < 1,
 % load n_sample;
load liver.dat 
sampledata=liver;
  sam_size=size(sampledata,1);
  trn_dat=sampledata;
%end
%if nargin < 2,
% all feature no. 
%trn_dat=[ 1 3 5 7
%3 4 6 9
%7 4 2 1];  



feature_n = size(trn_dat,2)-1;
  eig_num = [1,2,6]
end

t0=clock;
feature_mat=trn_dat(:,1:size(trn_dat,2)-1);
trn_mean = mean(feature_mat);
% N is the size of sample data; M is the number of feature;

% Covariance matrix computation may overflow.
% A'*A*v=e*v-> A*A'*A*v=e*A*v-> So A*v are the eigenvectors of C=A*A';
% With the analysis the calculation are greatly reduced (M << N);

delmat=feature_mat-ones(size(feature_mat,1),1)*trn_mean;

[e_vec, e_val] = eig(delmat'*delmat)
e_val_v=diag(e_val);
[e_val_s, i] = sort(-e_val_v);
e_val_s=-e_val_s;
all_ev=sum(e_val_v);
evsum=0;
num=1;
t0 = clock;
per=0;
while per < 0.9,
  evsum=evsum+e_val_s(num);
  per=evsum/all_ev;
  num=num+1;
end

e_vec_s=e_vec(:,i);
% A*v are the eigenvectors of C=A*A';
u=delmat*e_vec_s(:,eig_num);

proj_data=[u trn_dat(:,size(trn_dat,2))];

elapsed_time = etime(clock, t0);
fprintf('Principle component transform computation Time : %g seconds\n ', elapsed_time);
