Path: blob/master/Week 8/Programming Assignment - 7/ex7/computeCentroids.m
863 views
function centroids = computeCentroids(X, idx, K)1%COMPUTECENTROIDS returns the new centroids by computing the means of the2%data points assigned to each centroid.3% centroids = COMPUTECENTROIDS(X, idx, K) returns the new centroids by4% computing the means of the data points assigned to each centroid. It is5% given a dataset X where each row is a single data point, a vector6% idx of centroid assignments (i.e. each entry in range [1..K]) for each7% example, and K, the number of centroids. You should return a matrix8% centroids, where each row of centroids is the mean of the data points9% assigned to it.10%1112% Useful variables13[m n] = size(X);1415% You need to return the following variables correctly.16centroids = zeros(K, n);171819% ====================== YOUR CODE HERE ======================20% Instructions: Go over every centroid and compute mean of all points that21% belong to it. Concretely, the row vector centroids(i, :)22% should contain the mean of the data points assigned to23% centroid i.24%25% Note: You can use a for-loop over the centroids to compute this.26%2728for k=1:K,29centroids(k,:) = (1/sum(idx==k)) * sum(X(idx==k,:));30%centroids(k,:) = mean(X(idx==k,:));31endfor32333435363738% =============================================================394041end42434445