1
0
Fork 0
This repository has been archived on 2019-12-21. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
coursera-ml-007-exercises/ex7/computeCentroids.m

42 lines
1.3 KiB
Mathematica
Raw Normal View History

2014-11-17 21:58:10 +01:00
function centroids = computeCentroids(X, idx, K)
2014-11-17 23:02:10 +01:00
%COMPUTECENTROIDS returs the new centroids by computing the means of the
2014-11-17 21:58:10 +01:00
%data points assigned to each centroid.
2014-11-17 23:02:10 +01:00
% centroids = COMPUTECENTROIDS(X, idx, K) returns the new centroids by
2014-11-17 21:58:10 +01:00
% 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
2014-11-17 23:02:10 +01:00
% belong to it. Concretely, the row vector centroids(k, :)
2014-11-17 21:58:10 +01:00
% should contain the mean of the data points assigned to
2014-11-17 23:02:10 +01:00
% centroid k.
2014-11-17 21:58:10 +01:00
%
% Note: You can use a for-loop over the centroids to compute this.
%
2014-11-17 23:02:10 +01:00
for k = 1:K
2014-11-17 23:13:57 +01:00
X_in_k = X(idx == k, :);
if size(X_in_k, 1) > 0
centroids(k, :) = sum(X_in_k)/size(X_in_k, 1);
2014-11-17 23:02:10 +01:00
end
end
2014-11-17 21:58:10 +01:00
% =============================================================
end