1.1.1 Finding closest centroids
n=size(X,1);
temp = zeros(K, 1);
for i=1:n
for j=1:K
% temp(j)=(X(i,1)-centroids(j,1))^2+(X(i,2)-centroids(j,2))^2;
% //上边这句提交总没分,其实我是很迷惑的。。我觉得他跟下边这句没什么区别
temp(j)=sum((X(i,:) - centroids(j,:)).^2);
end
%找最小距离的下标
mintemp=min(temp);
[index,~]=find(temp==mintemp);
if length(index)==1 %注意这一块,很有可能样例点在两个簇中心的正中间,这是find函数就会返回不止一个值
idx(i)=index;
else
idx(i)=index(1);
end
end
1.1.2 Computing centroid means
for i=1:K
% 这个注释掉的又错了。。。是因为今天晚上写的原因吗???写啥啥错,样例是对的,竟然还是需要找bug
% findindex=find(idx==i);
% l=length(findindex);
% if l~=0
% centroids(i,1)=sum(X(findindex,1))/l;
% centroids(i,2)=sum(X(findindex,2))/l;
% end
centroids(i,:)=(X'*(idx==i))/sum(idx==i);
end
2.2 Implementing PCA
![](https://img-blog.csdnimg.cn/20200502115936414.png)
[U, S, V] = svd(Sigma)
%计算协方差矩阵
Sigma=1/m*X'*X;
%计算协方差矩阵的特征向量
[U,S,V]=svd(Sigma);
%
2.3.1 Projecting the data onto the principal components
U reduce = U(:, 1:K)
.
U=U(:,1:K);
Z=X*U;
2.3.2 Reconstructing an approximation of the data
X_rec=Z*U(:,1:K)';