-
Notifications
You must be signed in to change notification settings - Fork 11
/
computeCentroids.m
27 lines (25 loc) · 1000 Bytes
/
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
function centroids = computeCentroids(X, idx, K)
%COMPUTECENTROIDS returns 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.
[m n] = size(X);
centroids = zeros(K, n);
frequency = zeros(K, 1);
for i = 1:m
frequency(idx(i))++;
centroids(idx(i), :) += X(i, :);
endfor
mask = centroids == 0;
frequency = maskZeroAsOne(frequency);
centroids = centroids ./ frequency;
function mat = maskZeroAsOne(mat)
mask = mat == 0;
mat += mask;
endfunction
end