public static void covarianceMatrix(Vec mean,DataSet dataSet,Matrix covariance,double sumOfWeights,double sumOfSquaredWeights){
  if (!covariance.isSquare())   throw new ArithmeticException("Storage for covariance matrix must be square");
 else   if (covariance.rows() != mean.length())   throw new ArithmeticException("Covariance Matrix size and mean size do not agree");
 else   if (dataSet.getSampleSize() == 0)   throw new ArithmeticException("No data points to compute covariance from");
 else   if (mean.length() != dataSet.getNumNumericalVars())   throw new ArithmeticException("Data vectors do not agree with mean and covariance matrix");
  Vec scratch=new DenseVector(mean.length());
  for (int i=0; i < dataSet.getSampleSize(); i++) {
    DataPoint dp=dataSet.getDataPoint(i);
    Vec x=dp.getNumericalValues();
    x.copyTo(scratch);
    scratch.mutableSubtract(mean);
    Matrix.OuterProductUpdate(covariance,scratch,scratch,dp.getWeight());
  }
  covariance.mutableMultiply(sumOfWeights / (Math.pow(sumOfWeights,2) - sumOfSquaredWeights));
}

public static void covarianceMatrix ( Vec mean , DataSet dataSet , Matrix covariance , double sumOfWeights , double sumOfSquaredWeights ) { if ( ! covariance . isSquare ( ) ) throw new ArithmeticException ( "Storage for covariance matrix must be square" ) ; else if ( covariance . rows ( ) != mean . length ( ) ) throw new ArithmeticException ( "Covariance Matrix size and mean size do not agree" ) ; else if ( dataSet . getSampleSize ( ) == 0 ) throw new ArithmeticException ( "No data points to compute covariance from" ) ; else if ( mean . length ( ) != dataSet . getNumNumericalVars ( ) ) throw new ArithmeticException ( "Data vectors do not agree with mean and covariance matrix" ) ; Vec scratch = new DenseVector ( mean . length ( ) ) ; for ( int i = 0 ; i < dataSet . getSampleSize ( ) ; i ++ ) { DataPoint dp = dataSet . getDataPoint ( i ) ; Vec x = dp . getNumericalValues ( ) ; x . copyTo ( scratch ) ; scratch . mutableSubtract ( mean ) ; Matrix . OuterProductUpdate ( covariance , scratch , scratch , dp . getWeight ( ) ) ; } covariance . mutableMultiply ( sumOfWeights / ( Math . pow ( sumOfWeights , 2 ) - sumOfSquaredWeights ) ) ; }
computes the weighted covariance matrix of the given data set . superfluous calculations are avoided by having the call provide information .
