Last active
April 20, 2020 05:31
-
-
Save theptrk/d6a31b23f387fc07d666ee95cfd0345c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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