Commits

Ning Sun committed b0a7268

finished k-means exercises

  • Participants
  • Parent commits b8549f1

Comments (0)

Files changed (2)

mlclass-ex7/computeCentroids.m

 % Note: You can use a for-loop over the centroids to compute this.
 %
 
-
-
-
-
-
+for i=1:K
+  sums = zeros(1, n);
+  samples_in_cluster = 0;
+  for j=1:m
+    if (idx(j) == i)
+      sums+=X(j,:);
+      samples_in_cluster+=1;
+    endif
+  endfor
+  centroids(i,:) = sums./samples_in_cluster;
+endfor
 
 
 % =============================================================

mlclass-ex7/findClosestCentroids.m

 %
 
 
+for i=1:size(X,1)
+  min_idx = 0;
+  min_dist = -1;
+  for j=1:K
+    centroid = centroids(j,:);
+    dist = sum((X(i,:)-centroid).^2)
+    if ((min_dist==-1) || (dist<min_dist))
+      min_dist = dist;
+      min_idx = j;
+    endif
+  endfor
+  idx(i) = min_idx;
+endfor