Path: blob/master/Week 8/Programming Assignment - 7/ex7/findClosestCentroids.m
864 views
function idx = findClosestCentroids(X, centroids)1%FINDCLOSESTCENTROIDS computes the centroid memberships for every example2% idx = FINDCLOSESTCENTROIDS (X, centroids) returns the closest centroids3% in idx for a dataset X where each row is a single example. idx = m x 14% vector of centroid assignments (i.e. each entry in range [1..K])5%6% Set K7K = size(centroids, 1);89% You need to return the following variables correctly.10idx = zeros(size(X,1), 1);1112% ====================== YOUR CODE HERE ======================13% Instructions: Go over every example, find its closest centroid, and store14% the index inside idx at the appropriate location.15% Concretely, idx(i) should contain the index of the centroid16% closest to example i. Hence, it should be a value in the17% range 1..K18%19% Note: You can use a for-loop over the examples to compute this.20%2122for i=1:size(X,1)23%[c idx(i)] = min((X(i) - centroids(1:K)).^2);24c = zeros(1,K);25for j=1:K26c(1,j) = sqrt(sum((X(i,:)-centroids(j,:)).^2));27end28[val,pos] = min(c);29idx(i,1) = pos;30endfor31% =============================================================32end3334