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/computeCentroids.m
863 views
1
function centroids = computeCentroids(X, idx, K)
2
%COMPUTECENTROIDS returns the new centroids by computing the means of the
3
%data points assigned to each centroid.
4
% centroids = COMPUTECENTROIDS(X, idx, K) returns the new centroids by
5
% computing the means of the data points assigned to each centroid. It is
6
% given a dataset X where each row is a single data point, a vector
7
% idx of centroid assignments (i.e. each entry in range [1..K]) for each
8
% example, and K, the number of centroids. You should return a matrix
9
% centroids, where each row of centroids is the mean of the data points
10
% assigned to it.
11
%
12
13
% Useful variables
14
[m n] = size(X);
15
16
% You need to return the following variables correctly.
17
centroids = zeros(K, n);
18
19
20
% ====================== YOUR CODE HERE ======================
21
% Instructions: Go over every centroid and compute mean of all points that
22
% belong to it. Concretely, the row vector centroids(i, :)
23
% should contain the mean of the data points assigned to
24
% centroid i.
25
%
26
% Note: You can use a for-loop over the centroids to compute this.
27
%
28
29
for k=1:K,
30
centroids(k,:) = (1/sum(idx==k)) * sum(X(idx==k,:));
31
%centroids(k,:) = mean(X(idx==k,:));
32
endfor
33
34
35
36
37
38
39
% =============================================================
40
41
42
end
43
44
45