function [l2, q, c, meanx] = mypca(x, type);
% function [l, q, c, meanx] = mypca(data, type);
% Principal Components Analysis
% type = 1 (default) -- uses covariance matrix
% type = 2 -- uses correlation matrix

n=size(x,2);
meanx=mean(x,1);
if nargin==1 type = 1; end
	x=x-repmat(meanx,size(x,1),1); 
if type==2
	for(i=1:n) 
		x(:,i)=x(:,i)/std(x(:,i));
	end
end	
r=x'*x;
[q0,l]=eig(r);
lambda0=diag(l);
[lambda,I]=sort(-lambda0); lambda=-lambda;
q=q0(:,I');
c=q'*x';
lsum=sum(lambda(:));
l2=lambda/lsum;

