Fast matrix indexing from vectors

◇◆丶佛笑我妖孽 提交于 2019-12-25 05:01:06

问题


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 '['?


回答1:


A bit cumbersome, but try

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


来源:https://stackoverflow.com/questions/19810781/fast-matrix-indexing-from-vectors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!