Given a vector x
of length k, I would like to obtain a k by k matrix X
where X[i,j]
is the sum of x[i] + ... + x[j]
. The
You can also try this:
x <- 1:10
matrix(apply(expand.grid(1:10, 1:10), 1, function(y) sum(x[y[2]:y[1]])), 10, 10)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 3 6 10 15 21 28 36 45 55
[2,] 3 2 5 9 14 20 27 35 44 54
[3,] 6 5 3 7 12 18 25 33 42 52
[4,] 10 9 7 4 9 15 22 30 39 49
[5,] 15 14 12 9 5 11 18 26 35 45
[6,] 21 20 18 15 11 6 13 21 30 40
[7,] 28 27 25 22 18 13 7 15 24 34
[8,] 36 35 33 30 26 21 15 8 17 27
[9,] 45 44 42 39 35 30 24 17 9 19
[10,] 55 54 52 49 45 40 34 27 19 10