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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With