1
0
Fork 0
You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

50 lines
1.4 KiB
Matlab

10 years ago
function centroids = computeCentroids(X, idx, K)
%COMPUTECENTROIDS returs the new centroids by computing the means of the
10 years ago
%data points assigned to each centroid.
% centroids = COMPUTECENTROIDS(X, idx, K) returns the new centroids by
10 years ago
% 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(k, :)
10 years ago
% should contain the mean of the data points assigned to
% centroid k.
10 years ago
%
% Note: You can use a for-loop over the centroids to compute this.
%
for k = 1:K
count = 0;
% XXX vectorize
for i = 1:m
if idx(i) == k
centroids(k, :) += X(i, :);
count += 1;
end
end
if count > 0
centroids(k, :) /= count;
end
end
10 years ago
% =============================================================
end