From 39b09f144a3f197b86ad0ab38a06ba3fea04e116 Mon Sep 17 00:00:00 2001 From: neingeist Date: Mon, 17 Nov 2014 23:02:10 +0100 Subject: [PATCH] Compute centroid means (unvectorized) --- ex7/computeCentroids.m | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/ex7/computeCentroids.m b/ex7/computeCentroids.m index 606011e..2bd6095 100644 --- a/ex7/computeCentroids.m +++ b/ex7/computeCentroids.m @@ -1,7 +1,7 @@ function centroids = computeCentroids(X, idx, K) -%COMPUTECENTROIDS returs the new centroids by computing the means of the +%COMPUTECENTROIDS returs 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 +% centroids = COMPUTECENTROIDS(X, idx, K) returns the new centroids by % computing the means of the data points assigned to each centroid. It is % given a dataset X where each row is a single data point, a vector % idx of centroid assignments (i.e. each entry in range [1..K]) for each @@ -19,18 +19,27 @@ centroids = zeros(K, n); % ====================== YOUR CODE HERE ====================== % Instructions: Go over every centroid and compute mean of all points that -% belong to it. Concretely, the row vector centroids(i, :) +% belong to it. Concretely, the row vector centroids(k, :) % should contain the mean of the data points assigned to -% centroid i. +% centroid k. % % Note: You can use a for-loop over the centroids to compute this. % - - - - - +for k = 1:K + count = 0; + + % XXX vectorize + for i = 1:m + if idx(i) == k + centroids(k, :) += X(i, :); + count += 1; + end + end + if count > 0 + centroids(k, :) /= count; + end +end % =============================================================