function [newMean,newVar,newWeight] = combineMoments(oldMean,chunkMean,oldVar,chunkVar,oldWeight,chunkWeight)
% Chan's algorithm for incremental update of mean and
% variance

%   Copyright 2023 The MathWorks, Inc.

newVar = oldVar;
[newMean,newWeight,nonzeroChunkWeight,delta] = incremental.utils.combineMean(oldMean,chunkMean,oldWeight,chunkWeight);
newVar(nonzeroChunkWeight,:) = (oldWeight(nonzeroChunkWeight).*oldVar(nonzeroChunkWeight,:) + chunkWeight(nonzeroChunkWeight).*chunkVar(nonzeroChunkWeight,:) ...
    + delta(nonzeroChunkWeight,:).*delta(nonzeroChunkWeight,:)./(1./oldWeight(nonzeroChunkWeight) + 1./chunkWeight(nonzeroChunkWeight)))./newWeight(nonzeroChunkWeight);
end