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.

computeCentroids.m 1.4 kB

8 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041
  1. function centroids = computeCentroids(X, idx, K)
  2. %COMPUTECENTROIDS returns the new centroids by computing the means of the
  3. %data points assigned to each centroid.
  4. % centroids = COMPUTECENTROIDS(X, idx, K) returns the new centroids by
  5. % computing the means of the data points assigned to each centroid. It is
  6. % given a dataset X where each row is a single data point, a vector
  7. % idx of centroid assignments (i.e. each entry in range [1..K]) for each
  8. % example, and K, the number of centroids. You should return a matrix
  9. % centroids, where each row of centroids is the mean of the data points
  10. % assigned to it.
  11. %
  12. % Useful variables
  13. [m n] = size(X);
  14. % You need to return the following variables correctly.
  15. centroids = zeros(K, n);
  16. % ====================== YOUR CODE HERE ======================
  17. % Instructions: Go over every centroid and compute mean of all points that
  18. % belong to it. Concretely, the row vector centroids(i, :)
  19. % should contain the mean of the data points assigned to
  20. % centroid i.
  21. %
  22. % Note: You can use a for-loop over the centroids to compute this.
  23. %
  24. centroidsSum = zeros(K,1);
  25. for i = 1 : m
  26. centroids(idx(i), :) = centroids(idx(i), :) .+ X(i, :);
  27. centroidsSum(idx(i)) = centroidsSum(idx(i)) + 1;
  28. end
  29. for i = 1 : K
  30. centroids(i,:) = centroids(i,:) ./ centroidsSum(i) ;
  31. end
  32. % =============================================================
  33. end

机器学习

Contributors (1)