public static double[] WeightedMean(double[][] matrix, double[] weights, int dimension = 0)
{
int rows = matrix.Length;
if (rows == 0)
return new double[0];
int cols = matrix[0].Length;
double[] mean;
if (dimension == 0)
{
mean = new double[cols];
if (rows != weights.Length)
{
throw new DimensionMismatchException("weights",
"The number of rows and weights must match.");
}
// for each row
for (int i = 0; i < rows; i++)
{
double[] row = matrix[i];
double w = weights[i];
// for each column
for (int j = 0; j < cols; j++)
mean[j] += row[j] * w;
}
}
else if (dimension == 1)
{
mean = new double[rows];
if (cols != weights.Length)
{
throw new DimensionMismatchException("weights",
"The number of columns and weights must match.");
}
// for each row
for (int j = 0; j < rows; j++)
{
double[] row = matrix[j];
double w = weights[j];
// for each column
for (int i = 0; i < cols; i++)
mean[j] += row[i] * w;
}
}
else
{
throw new ArgumentException("Invalid dimension.", "dimension");
}
double weightSum = weights.Sum();
if (weightSum != 0)
for (int i = 0; i < mean.Length; i++)
mean[i] /= weightSum;
return mean;
}