Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/Coursera-Machine-Learning
Path: blob/master/Week 8/Programming Assignment - 7/ex7/findClosestCentroids.m
864 views
1
function idx = findClosestCentroids(X, centroids)
2
%FINDCLOSESTCENTROIDS computes the centroid memberships for every example
3
% idx = FINDCLOSESTCENTROIDS (X, centroids) returns the closest centroids
4
% in idx for a dataset X where each row is a single example. idx = m x 1
5
% vector of centroid assignments (i.e. each entry in range [1..K])
6
%
7
% Set K
8
K = size(centroids, 1);
9
10
% You need to return the following variables correctly.
11
idx = zeros(size(X,1), 1);
12
13
% ====================== YOUR CODE HERE ======================
14
% Instructions: Go over every example, find its closest centroid, and store
15
% the index inside idx at the appropriate location.
16
% Concretely, idx(i) should contain the index of the centroid
17
% closest to example i. Hence, it should be a value in the
18
% range 1..K
19
%
20
% Note: You can use a for-loop over the examples to compute this.
21
%
22
23
for i=1:size(X,1)
24
%[c idx(i)] = min((X(i) - centroids(1:K)).^2);
25
c = zeros(1,K);
26
for j=1:K
27
c(1,j) = sqrt(sum((X(i,:)-centroids(j,:)).^2));
28
end
29
[val,pos] = min(c);
30
idx(i,1) = pos;
31
endfor
32
% =============================================================
33
end
34