function [X,whiteningMatrix]=pca(A,rdim);
% Summary: principle component analysis
% Synopsis: [X,whiteningMatrix]=pca(A,rdim)
% A is matrix, each row denotes a pattern
% rdim denotes the reduced dimension
% X is the projected result, each row contains rdim elements
% whiteningMatrix denotes the projection matrix

[n1 n2]=size(A);
A=A-ones(n1,1)*mean(A);
X=A';
%X = X-ones(size(X,1),1)*mean(X);
covarianceMatrix = X*X';
%covarianceMatrix = covarianceMatrix./size(X,2);    
[E, D] = eig(covarianceMatrix);
[dummy,order] = sort(diag(-D));
E = E(:,order(1:rdim));
d = diag(D); 
d = real(d.^(-0.5));
D = diag(d(order(1:rdim)));
X = D*E'*X;
%X=E'*X;
whiteningMatrix = D*E';
%whiteningMatrix = E';
dewhiteningMatrix = E*D^(-1);
X=X';
return