public static double[,] WeightedScatter(double[][] matrix, double[] weights,
double[] means, double factor, int dimension)
{
int rows = matrix.Length;
if (rows == 0)
return new double[0, 0];
int cols = matrix[0].Length;
double[,] cov;
if (dimension == 0)
{
if (means.Length != cols)
{
throw new DimensionMismatchException("means",
"Length of the mean vector should equal the number of columns.");
}
if (rows != weights.Length)
{
throw new DimensionMismatchException("weights",
"The number of rows and weights must match.");
}
cov = new double[cols, cols];
for (int i = 0; i < cols; i++)
{
for (int j = i; j < cols; j++)
{
double s = 0.0;
for (int k = 0; k < rows; k++)
s += weights[k] * (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]);
cov[i, j] = s * factor;
cov[j, i] = s * factor;
}
}
}
else if (dimension == 1)
{
if (means.Length != rows)
{
throw new DimensionMismatchException("means",
"Length of the mean vector should equal the number of rows.");
}
if (cols != weights.Length)
{
throw new DimensionMismatchException("weights",
"The number of columns and weights must match.");
}
cov = new double[rows, rows];
for (int i = 0; i < rows; i++)
{
for (int j = i; j < rows; j++)
{
double s = 0.0;
for (int k = 0; k < cols; k++)
s += weights[k] * (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]);
cov[i, j] = s * factor;
cov[j, i] = s * factor;
}
}
}
else
{
throw new ArgumentException("Invalid dimension.", "dimension");
}
return cov;
}