【问题标题】:Fast matrix indexing from vectors从向量快速矩阵索引
【发布时间】:2013-11-06 11:22:42
【问题描述】:

我想做很多高维数组的矩阵索引,但是索引被分割了。我想出了几个解决方案:

### 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))] )

但最快的 rbind(c(X)) 花费的时间是直接索引的两倍。有没有更快的方法?有什么像 python 的 *args 可以在 '[' 上运行的吗?

【问题讨论】:

  • 您的索引向量是如何拆分的?您能否提供具有多个索引的样本。此操作应完全矢量化。您看到的缓慢是因为您正在使用 for 循环来执行您不应该使用 for 循环的事情。
  • 我希望你是对的,我不需要 for 循环,但我不相信。你能向量化这个吗? ### 用观测值填充分布 testa testi testi

标签: arrays r matrix-indexing


【解决方案1】:

有点麻烦,不过试试

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

【讨论】: