Skip to content

Instantly share code, notes, and snippets.

@theptrk
Created April 20, 2020 06:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theptrk/c4eabb1c25db7c20d11f810987eb4b76 to your computer and use it in GitHub Desktop.
Save theptrk/c4eabb1c25db7c20d11f810987eb4b76 to your computer and use it in GitHub Desktop.
function centroids = computeCentroids(X, idx, K)
% Initialize to store new centroid values
centroids = zeros(K, n);
% iterate over number of centroids
for i = 1:K
% create a boolean vector that match the current index, then use this to index into X
has_this_centroid = X(idx == i, :);
% sum up the examples that are assigned this centroid
sum_of_assigned = sum(has_this_centroid);
% get the number of assigned for easier averaging
num_of_assigned = size(has_this_centroid, 1);
% calulate and store new centroid
centroids(i, :) = (1/num_of_assigned) * sum_of_assigned;
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment