矢量化高D阵列的填充

时间:2013-11-06 12:30:40

标签: arrays r populate matrix-indexing

我正在使用观察test_idxs填充分布testa

test_idxs <- matrix(sample(c(1,2,3), 300000, repl=T), ncol=3)
testa_for_looped <- array(0, c(3,3,3))
testa_vectorized <- array(0, c(3,3,3))
system.time( for (i in 1:nrow(test_idxs)) { testa_for_looped[rbind(test_idxs[i,])] <- testa_for_looped[rbind(test_idxs[i,])] + 1 } )  ## slower
system.time( testa_vectorized[test_idxs] <- testa_vectorized[test_idxs] + 1  ) ### faster
sum(testa_for_looped) ### right
sum(testa_vectorized) ### wrong

矢量化解决方案更快,但是这个解决方案已经破解,我提出的所有解决方案都比for循环慢。你会做什么?

0 个答案:

没有答案