/K-Means Clustering and PCA/Octave/computeCentroids.m

http://github.com/gafiatulin/ml-class · Objective C · 49 lines · 37 code · 12 blank · 0 comment · 6 complexity · d52fcedd3acce30ad488a197f1e0fa4d MD5 · raw file

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