function [compMu, compSigma, compN] = ...
  computeCompositeStats(mu, sigma, n)
% n, mu and sigma are vectors describing the statistics of a set of
% sets. The length of n is the number of sets on which we are 
% combining statistics. 
% 
% n(i) = number of samples set i
% mu(i) = mean of samples in set i
% sigma = std deviation of samples in set i
% 
% Vivek Nadkarni
% July 13, 2004
% Trimble

% Compute total number of points in all sets
compN = sum(n);

% Clear out NaNs
idx = isnan(mu);
mu(idx) = 0;

idx = isnan(sigma);
sigma(idx) = 0;


% Compute composite mean
compMu = sum(mu.*n)/compN; 
compMuVec = compMu*(n>0);

% Compute composite Variance
% P1, P2 and P3 stand for part 1, part 2 and part 3, which
% is just breaking down the three sets of information. 
compVarP1 = (n-1).*(sigma.^2);
compVarP2 = n.*(compMuVec.^2-mu.^2);
compVarP3 = - 2*n.*mu.*(compMuVec-mu);
compVar = compVarP1+compVarP2+compVarP3; 
compVar = sum(compVar)/(compN-1);

% Compute composite standard deviation
compSigma = sqrt(compVar); 

return; 