From fd3d428d35746fca79e31200fc34aedd856b699b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E7=92=9F=E5=9E=9A?= Date: Fri, 22 Sep 2017 22:36:21 +0800 Subject: [PATCH] Update computeCentroids.m fix matrix bug --- .../Week 08/ex7/computeCentroids.m | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/Andrew Ng Stanford Coursera/Week 08/ex7/computeCentroids.m b/Andrew Ng Stanford Coursera/Week 08/ex7/computeCentroids.m index e330da1..e347ff7 100644 --- a/Andrew Ng Stanford Coursera/Week 08/ex7/computeCentroids.m +++ b/Andrew Ng Stanford Coursera/Week 08/ex7/computeCentroids.m @@ -1,5 +1,5 @@ function centroids = computeCentroids(X, idx, K) -%COMPUTECENTROIDS returs the new centroids by computing the means of the +%COMPUTECENTROIDS returns the new centroids by computing the means of the %data points assigned to each centroid. % centroids = COMPUTECENTROIDS(X, idx, K) returns the new centroids by % computing the means of the data points assigned to each centroid. It is @@ -26,16 +26,20 @@ % Note: You can use a for-loop over the centroids to compute this. % -counts = zeros(K,1); -for i = 1:m, - for j = 1:K, - if idx(i) == j, - centroids(j,:) = (centroids(j,:) + X(i,:)); - counts(j) = counts(j) + 1; +counts=zeros(K,1) +for i = 1:m + for j =1:K + if idx(i)==j + centroids(j,:)=centroids(j,:)+X(i,:) + counts(j)=counts(j)+1 + end end - end -end -centroids = centroids./counts; +end +for k=1:n + centroids(:,k)=centroids(:,k)./counts +end + + % =============================================================