1.1.1 Finding closest centroids
Your task is to complete the code in findClosestCentroids.m. This function takes the data matrix X and the locations of all centroids inside centroids and should output a one-dimensional array idx that holds the index (a value in {1,…,K}, where K is total number of centroids) of the closest centroid to every training example.
% Traverse all points of X
for i = 1:length(X)
min = Inf;
% Traverse all points of K, judge which cluster the point belong to
for j = 1:K
dist = norm(X(i,:) - centroids(j,:))^2;
if dist < min
min = dist;
idx(i) = j;
end
end
end
1.1.2 Computing centroid means
You should now complete the code in computeCentroids.m. You can implement this function using a loop over the centroids. You can also use a loop over the examples; but if you can use a vectorized implementation that does not use such a loop, your code may run faster.
for i = 1:K
count = 0;
for j = 1:m
if idx(j) == i
count = count + 1;
centroids(i,:) = centroids(i,:) + X(j,:);
end
end
centroids(