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.
source
share