Escachator
Escachator

Reputation: 1881

Calculating an array in LINQ C#

I would like to calculate the correlation matrix using linq, with a single phrase. How can I do that (if it is possible)?

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

I am also using:

using stats = MathNet.Numerics.Statistics.ArrayStatistics

and this is the code that I want to make 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       
    }
}

thanks!

Upvotes: 4

Views: 306

Answers (2)

Jerry Federspiel
Jerry Federspiel

Reputation: 1524

If you let yourself 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 (per 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();    

That's not to say you should do this. The loop version is both more readable and more performant.

Upvotes: 6

Alexei Levenkov
Alexei Levenkov

Reputation: 100547

Per OP request Enumerable.Aggregate version with 2d array as result:

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
        });

Side note: this is essentially exercise in using LINQ and not code that you should be using in real code.

  • code have to capture position into anonymous object causing a lot of unnecessary allocations
  • I think this version is significantly harder to read compared to regular for version

Upvotes: 2

Related Questions