computeCentroids.m 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. ns = zeros(K, 1);
  17. for i = 1:m
  18. centroids(idx(i),:) = centroids(idx(i),:) + X(i,:);
  19. ns(idx(i)) = ns(idx(i)) + 1;
  20. end
  21. centroids = centroids ./ ns;
  22. % ====================== YOUR CODE HERE ======================
  23. % Instructions: Go over every centroid and compute mean of all points that
  24. % belong to it. Concretely, the row vector centroids(i, :)
  25. % should contain the mean of the data points assigned to
  26. % centroid i.
  27. %
  28. % Note: You can use a for-loop over the centroids to compute this.
  29. %
  30. % =============================================================
  31. end