Array calculation in LINQ C #

I would like to calculate the correlation matrix using linq, with one phrase. How can I do this (if possible)?

Suppose I already have an array with sizes N called volatilites, and Returns is a jagged array with N arrays of the same size.

I also use:

using stats = MathNet.Numerics.Statistics.ArrayStatistics

and this is the code I want to do in LINQ:

double[,] correlation_matrix = new double[N,N];
for (int i=0; i<N;i++){
    for (int j = i + 1; j < N; j++){
        correlation_matrix [i,j]= stats.Covariance(Returns[i], Returns[j]) / (volatilities[i] * volatilities[j]); // stores it to check values       
    }
}

thank!

+4
source share
2 answers

If you allow yourself to have an array of arrays, you can do

var correlation_matrix = 
    Returns.Select((r_i, i) => 
        Returns.Where((r_j, j) => j > i).Select((r_j, j) =>
            stats.Covariance(r_i, r_j) / (volatilities[i] * volatilities[j])
        ).ToArray()
    ).ToArray();

If you want to use ranges (for your comment), you can do

var N = Returns.Length;
var correlation_matrix = 
    Enumerable.Range(0, N).Select(i => 
        Enumerable.Range(i + 1, N - i - 1).Select(j =>
            stats.Covariance(Returns[i], Returns[j]) / (volatilities[i] * volatilities[j])
        ).ToArray()
    ).ToArray();    

This does not mean that you should do it. The loop version is more readable and more efficient.

+6
source

In the OP request, the Enumerable.Aggregateversion with the 2d array is:

var correlation_matrix = 
   Enumerable.Range(0, N).Select(i => 
       Enumerable.Range(i + 1, N - i - 1).Select(j => 
         new {
            i, j, // capture location of the result
            Data = i + j } // compute whatever you need here
       )
   )
   .SelectMany(r => r) // flatten into single list
   .Aggregate(
       new double[N,N], 
       (result, item) => { 
           result[item.i, item.j] = item.Data; // use pos captured earlier
           return result; // to match signature required by Aggregate
        });

: LINQ, , .

  • , .
  • , for
+2

All Articles