enfascination
enfascination

Reputation: 1036

Fast matrix indexing from vectors

I want to do a lot of matrix indexing of a high-D array, but the indices are split up. I came up with a few solutions:

### setup
test <- array(0, c(3,3,3,3))
test[1,2,3,2] <- 1
system.time(for (i in 1:1000000) test[1,2,3,2] )
### index split between two vectors
idx1 <- c(1,2);     idx2 <- c(3,2)
### things that work are slower
system.time(for (i in 1:1000000) test[rbind(c(idx1, idx2))] )
system.time(for (i in 1:1000000) test[matrix(c(idx1, idx2), nrow=1)] )
system.time(for (i in 1:1000000) test[t(c(idx1, idx2))] )

But the fastest, rbind(c(X)), takes twice as long as indexing directly. Is there any faster way? Is there anything like python's *args that I could run on '['?

Upvotes: 0

Views: 102

Answers (1)

Hong Ooi
Hong Ooi

Reputation: 57686

A bit cumbersome, but try

test[idx1[1], idx1[2], idx2[1], idx2[2]]

Upvotes: 1

Related Questions