2

I'm using MathNet Numerics matrices and trying to find out covariance of a matrix.

How can we find covariance of matrix?

We have method to find covariance between two IEnumerable under Statistics namespace.

http://numerics.mathdotnet.com/api/MathNet.Numerics.Statistics/Statistics.htm

But I don't know how to use it to find for a matrix.

For ex: In matlab/octave

enter image description here

Same way in C#. How can we implement??

malkam
  • 2,337
  • 1
  • 14
  • 17
  • possible duplicate of [How to compute a covariance matrix](http://stackoverflow.com/questions/4410943/how-to-compute-a-covariance-matrix) – Taher Rahgooy Aug 27 '15 at 18:35

2 Answers2

6

I don't think there is any method in Math.NET mimicking the cov function from Matlab/Octave, but you can easily write your own:

public static Matrix<double> GetCovarianceMatrix(Matrix<double> matrix)
{
    var columnAverages = matrix.ColumnSums() / matrix.RowCount;
    var centeredColumns = matrix.EnumerateColumns().Zip(columnAverages, (col, avg) => col - avg);
    var centered = DenseMatrix.OfColumnVectors(centeredColumns);
    var normalizationFactor = matrix.RowCount == 1 ? 1 : matrix.RowCount - 1;
    return centered.TransposeThisAndMultiply(centered) / normalizationFactor;
}
tearvisus
  • 2,013
  • 2
  • 15
  • 32
1

You could use the Tools.Covariance() method in the Accord.Statistics nuget package. http://accord-framework.net/docs/html/M_Accord_Statistics_Tools_Covariance.htm
To do something like this:

using Accord.Statistics;
public void CalculateMatrixCovariance()
{
    var matrix = new double[,] {
        {3,5},
        {9,10}};

    var covMatrix = matrix.Covariance();

    Console.WriteLine(covMatrix[0,0] + " " + covMatrix[0, 1]);
    Console.WriteLine(covMatrix[1,0] + " " + covMatrix[1, 1]);
}
ristaloff
  • 130
  • 1
  • 6