function sumd = calcErrSum(data, cent, idx, numClust)
% Calculates the error of each cluster as sum of L2 distance of each point
% from the center.
%
% Author: saurabh.me@gmail.com (Saurabh Singh)
clustIds = unique(idx);
if isempty(cent)
  cent = calculateCenters(data, idx, clustIds);
end
sumd = zeros(1, length(clustIds));
for i = 1 : length(clustIds)
  d = data(idx==clustIds(i), :);
  cr = repmat(cent(i, :), size(d, 1), 1);
  dist = d - cr;
  dist = dist.*dist;
  sumdi = sum(dist, 2);
  sumd(i) = sum(sumdi);
end
end

function cents = calculateCenters(data, idx, clustIds)
cents = zeros(length(clustIds), size(data, 2));
for i = 1 : length(clustIds)
  d = data(idx == clustIds(i), :);
  cents(i, :) = mean(d);
end
end
