findClosestCentroids.m 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. for i = 1:length(X)
  12. m = inf;
  13. for j = 1:K
  14. z = sum((X(i,:) - centroids(j,:)) .^2);
  15. if z < m
  16. m = z;
  17. idx(i) = j;
  18. end
  19. end
  20. end
  21. % ====================== YOUR CODE HERE ======================
  22. % Instructions: Go over every example, find its closest centroid, and store
  23. % the index inside idx at the appropriate location.
  24. % Concretely, idx(i) should contain the index of theq centroid
  25. % closest to example i. Hence, it should be a value in the
  26. % range 1..K
  27. %
  28. % Note: You can use a for-loop over the examples to compute this.
  29. %
  30. % =============================================================
  31. end