function centroids = computeCentroids(X, idx, K)
%COMPUTECENTROIDS returs 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.
%

% 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(i, :)
%               should contain the mean of the data points assigned to
%               centroid i.
%
% Note: You can use a for-loop over the centroids to compute this.
%

%m is rows, n is columns
%Ck_count = zeros(K);
%Ck_sum   = zeros(K,n);

%loop through the assigned centroids...
%for i=1:size(idx,2)

	%get the value at the index...
	%Ck_sum(idx(i),:) = Ck_sum(idx(i),:) .+ X(i,:)
	%Ck_count(idx(i)) = Ck_count(idx(i)) + 1; 
	
%end

%centroids = Ck_sum ./ Ck_count

%for i = 1:K 
	%if(Ck_count(i) != 0) 
		%centroids(i,:) = Ck_sum(i,:) ./ Ck_count(i)
	%end 
%end

% SCRATCH THAT - let's try find()....

for i=1:K
	%magically find all the indicies for each K and map them to x...
	xtemp=X(find(idx(:)==i),1:n); 
	if(size(xtemp,1) != 0) 
		centroids(i,1:n)=sum(xtemp)./size(xtemp,1); 
	end 
end





% =============================================================


end

