function [out1 out2 out3 out4]=pca(X,n)%out1相关系数矩阵特征值,out2相关系数矩阵,out3各主成分,out4累计贡献率,X数据矩阵,n前n个主成分;
m=size(X);
a=sum(X)/m(1);
for i=1:m(1);
for j=i:m(2);
R(i,j)=sum((X(:,i)-a(i)).*(X(:,j)-a(j)))./(sum((X(:,i)-a(i)).^2)*sum((X(:,j)-a(j)).^2)).^0.5;
end
end
for i=1:m(2);
for j=1:i-1;
R(i,j)=R(j,i) ;
end
end
[x,d]=eig(R);
out1=sort(d(d~=0),'descend');
for i=1:m(2)
out2(:,i)=x(:,m(2)+1-i);
end
out3=zeros(m(1),m(2));
for i=1:m(2)
for j=1:m(2)
out3(:,i)=out3(:,i)+out2(j,i)*X(:,j);
end
end
b=out1./sum(out1);
out4=sum(b(1:n));
bar(b(1:n));
hold on;
for i=1:n
out5(i)=sum(b(1:i));
end
plot(1:n,out5);
legend('各成分贡献率','前n个主成分累计贡献率');
X1 =1.0e+004 *[0.2479 0.0028 0.0007 0.0058 0.0001 0.0005 6.3878 0.0096;
0.1639 0.0024 0.0008 0.0061 0.0002 0.0006 5.2425 0.0098;
0.5089 0.0033 0.0009 0.0062 0.0002 0.0006 4.1990 0.0098;
0.1644 0.0035 0.0006 0.0064 0.0001 0.0002 2.3356 0.0097;
0.1401 0.0037 0.0006 0.0059 0.0001 0.0002 3.2756 0.0098;
0.4669 0.0028 0.0007 0.0060 0.0001 0.0004 4.0451 0.0098;
0.1821 0.0030 0.0008 0.0066 0.0001 0.0006 3.6796 0.0098;
0.3253 0.0049 0.0022 0.0058 0.0002 0.0031 6.2152 0.0098;
0.4551 0.0027 0.0009 0.0050 0.0002 0.0006 8.2327 0.0099;
0.8583 0.0025 0.0009 0.0062 0.0002 0.0004 5.0259 0.0097;
0.6036 0.0024 0.0011 0.0057 0.0002 0.0006 4.8268 0.0097;
0.3038 0.0031 0.0007 0.0063 0.0001 0.0002 3.1203 0.0098;
0.3920 0.0030 0.0009 0.0058 0.0002 0.0005 5.1244 0.0097;
0.2003 0.0029 0.0006 0.0068 0.0001 0.0001 2.4780 0.0097;
0.8542 0.0031 0.0012 0.0063 0.0002 0.0007 4.8804 0.0098;
0.5138 0.0032 0.0008 0.0066 0.0002 0.0004 3.2340 0.0098;
0.4276 0.0033 0.0008 0.0063 0.0001 0.0004 4.3921 0.0099;
0.3692 0.0032 0.0009 0.0068 0.0001 0.0002 3.1675 0.0099;
0.9662 0.0027 0.0009 0.0058 0.0002 0.0005 5.9775 0.0097;
0.2050 0.0032 0.0008 0.0068 0.0001 0.0004 3.5494 0.0098;
0.0518 0.0031 0.0006 0.0066 0.0001 0.0003 5.2707 0.0094;
0.1589 0.0029 0.0006 0.0065 0.0001 0.0002 3.1252 0.0099;
0.4010 0.0032 0.0007 0.0064 0.0001 0.0004 3.1848 0.0098;
0.0994 0.0034 0.0007 0.0069 0.0001 0.0002 3.1751 0.0097;
0.1955 0.0050 0.0016 0.0055 0.000