findClosestCentroids.m 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. function idx = findClosestCentroids(X, centroids)
  2. %FINDCLOSESTCENTROIDS computes the centroid memberships for every example
  3. % idx = FINDCLOSESTCENTROIDS (X, centroids) returns the closest centroids
  4. % in idx for a dataset X where each row is a single example. idx = m x 1
  5. % vector of centroid assignments (i.e. each entry in range [1..K])
  6. %
  7. % Set K
  8. K = size(centroids, 1);
  9. % You need to return the following variables correctly.
  10. idx = zeros(size(X,1), 1);
  11. % ====================== YOUR CODE HERE ======================
  12. % Instructions: Go over every example, find its closest centroid, and store
  13. % the index inside idx at the appropriate location.
  14. % Concretely, idx(i) should contain the index of the centroid
  15. % closest to example i. Hence, it should be a value in the
  16. % range 1..K
  17. %
  18. % Note: You can use a for-loop over the examples to compute this.
  19. %
  20. m = rows(X);
  21. for i = 1:m % for each example
  22. min_xi = zeros(K,1);
  23. for j = 1:K
  24. cj = centroids(j,:); % extract the centroid at ith row
  25. % distance = sqrt(u1-v1)^2 + (u2-v2)^)
  26. % http://mathonline.wikidot.com/the-distance-between-two-vectors
  27. min_xi(j) = sum((X(i,:) - cj) .^ 2) ^(1/2);
  28. endfor
  29. %min_xi;
  30. [v, idx(i)] = min(min_xi);
  31. endfor
  32. % =============================================================
  33. end