-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomputeCentroids.m
64 lines (45 loc) · 1.64 KB
/
computeCentroids.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
function centroids = computeCentroids(X, idx, K)
%COMPUTECENTROIDS returs the new centroids by computing the means of the
%data points assigned to each centroid.
% centroids = COMPUTECENTROIDS(X, idx, K) returns the new centroids by
% computing the means of the data points assigned to each centroid. It is
% given a dataset X where each row is a single data point, a vector
% idx of centroid assignments (i.e. each entry in range [1..K]) for each
% example, and K, the number of centroids. You should return a matrix
% centroids, where each row of centroids is the mean of the data points
% assigned to it.
%
% Useful variables
[m n] = size(X);
% You need to return the following variables correctly.
centroids = zeros(K, n);
% ====================== YOUR CODE HERE ======================
% Instructions: Go over every centroid and compute mean of all points that
% belong to it. Concretely, the row vector centroids(i, :)
% should contain the mean of the data points assigned to
% centroid i.
%
% Note: You can use a for-loop over the centroids to compute this.
%
for i=1:K
sel=find(idx==i);
if sel>0
centroids(i,:)=mean(X(sel,:));
end
end
%--------another working solution----------------
%num_in_centroid = zeros(K);
%for i = 1:m
% k = idx(i);
%size(centroids(k,:))
%size(X(i,:))
% centroids(k,:) = centroids(k,:) + X(i,:);
% num_in_centroid(k) = num_in_centroid(k) + 1;
%end
%for k = 1:K
% if num_in_centroid(k) > 0
% centroids(k,:) = centroids(k,:) / num_in_centroid(k);
% end
%end
% =============================================================
end