1
0
Fork 0

Find closest centroids

master
neingeist 10 years ago
parent 229023b69c
commit f8c0087ff3

@ -1,7 +1,7 @@
function idx = findClosestCentroids(X, centroids)
%FINDCLOSESTCENTROIDS computes the centroid memberships for every example
% idx = FINDCLOSESTCENTROIDS (X, centroids) returns the closest centroids
% in idx for a dataset X where each row is a single example. idx = m x 1
% in idx for a dataset X where each row is a single example. idx = m x 1
% vector of centroid assignments (i.e. each entry in range [1..K])
%
@ -15,17 +15,26 @@ idx = zeros(size(X,1), 1);
% Instructions: Go over every example, find its closest centroid, and store
% the index inside idx at the appropriate location.
% Concretely, idx(i) should contain the index of the centroid
% closest to example i. Hence, it should be a value in the
% closest to example i. Hence, it should be a value in the
% range 1..K
%
% Note: You can use a for-loop over the examples to compute this.
%
for i = 1:size(X,1)
idx(i) = 0; % unassigned yet
best_distance = Inf;
for k = 1:K
distance = norm(X(i,:) - centroids(k,:))^2;
if distance < best_distance
idx(i) = k;
best_distance = distance;
end
end
end
% =============================================================