You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

findClosestCentroids.m 1.3 kB

8 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142
  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. for i = 1 : size(X,1)
  21. [temp,idx(i)] = min(sum((X(i,:) .- centroids) .^ 2, 2));
  22. end
  23. % for i = 1 : size(X,1)
  24. % minN = sum((X(i,:) - centroids(1,:)) .^ 2);
  25. % idx(i) = 1;
  26. % for k = 2 : K
  27. % tempMinN = sum((X(i,:) - centroids(k,:)) .^ 2);
  28. % if tempMinN < minN
  29. % minN = tempMinN;
  30. % idx(i) = k;
  31. % end
  32. % end
  33. % end
  34. % =============================================================
  35. end

机器学习

Contributors (1)