Skip to content

Instantly share code, notes, and snippets.

@theptrk
Last active April 20, 2020 05:31
Show Gist options
  • Save theptrk/d6a31b23f387fc07d666ee95cfd0345c to your computer and use it in GitHub Desktop.
Save theptrk/d6a31b23f387fc07d666ee95cfd0345c to your computer and use it in GitHub Desktop.
function idx = findClosestCentroids(X, centroids)
% Set K
K = size(centroids, 1);
% Set empty indices vector
idx = zeros(size(X,1), 1);
% for every example in X...
for i = 1:size(X, 1)
% get the row
row = X(i, :);
% initialize a minimum distance value as infinite so every distance is smaller
min_dist = Inf;
% for every centriod...
for j = 1:size(centroids, 1)
% get the centriod row
centriod_row = centroids(j, :);
% calculate distance and if smaller,
% 1. update the idx vector with the centriod index
% 2. update the min distance to the distance
distance = sum((row - centriod_row).^2);
if distance < min_dist
idx(i) = j;
min_dist = distance;
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment