I have a matrix in which I want to reset some specific elements.
For example, imagine my matrix:
m <- matrix(1:100, ncol=10)
Then I have two vectors indicating which items to keep
m.from <- c(2, 5, 4, 4, 6, 3, 1, 4, 2, 5) m.to <- c(7, 9, 6, 8, 9, 5, 6, 8, 4, 8)
So, for example, I will store the 3: 6 elements in line 1 and set the elements 1: 2 and 7:10 to 0. For line 2, I will save 6: 8 and the rest zero, etc.
Now I could easily do:
for (line in 1:nrow(m)) { m[line, 1:m.from[line]] <- 0 m[line, m.to[line]:ncol(m)] <- 0 }
which gives the correct result.
In my specific case, however, I am working on a ~ 15000 x 3000 matrix, which makes using this type of loop painfully long.
How can I speed up this code? I use apply , but how do I access the correct m.from and m.to index?