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 don't need to repeatedly recalculate the sums in the inner loop, instead, you can build up the matrix by subdiagonal using the fact that a cell equals the cell above it plus the cell on the diagonal to the right. This should reduce the order of the algorithm from O(n^3) to O(n^2).
Here's a quick and dirty implementation:
X <- diag(x)
for(i in 1:9) {
for(j in 1:(10-i)){
X[j+i,j] <- X[j,j+i] <- X[j+i,j+i] + X[j+i-1,j]
}
}
EDIT:
As others have pointed out, you can get a little more speed and simplicity by using cumsum and vectorizing the inner loop:
n <- length(x)
X <- diag(x)
for(i in 1:n) {
X[i:n,i] <- X[i,i:n] <- cumsum(x[i:n])
}