Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating an array in LINQ C#

Tags:

arrays

c#

linq

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!

like image 276
Escachator Avatar asked Feb 10 '23 15:02

Escachator


1 Answers

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.

like image 180
Jerry Federspiel Avatar answered Feb 15 '23 09:02

Jerry Federspiel