Muh*_*amd -2 loops for-loop r rcpp
I have a nested loop as
X <- matrix(c(0.5,0,0,0.75), nrow = 2)
k = nrow(X)
ans1 <- 0
ans2 <- 0
for (aa in 1:k) {
for (bb in 1:k) {
for (cc in 1:k) {
for (dd in 1:k) {
ans1 = ans1 + (0.45 * X[aa,bb] * X[cc,dd])
for (xx in 1:k) {
for (yy in 1:k){
ans2 = ans2 + (1.7*X[aa,bb]*X[xx,yy]*X[cc,dd] + 0.2*X[aa,xx]*X[bb,yy]*X[cc,dd])
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
But the matrix X
which must be a square matrix can be of very high dimensions. Which would therefore slow the loop considerably. e.g. X = matrix(rnorm(10000),nrow = 100,byrow = T)
I am wondering if there is a shorter way to compress this. That would be readable and most importantly a slightly faster. I have tried expand.grid
but this doesn't help much.
For instance for ans1
library(tidyverse)
an1 <- expand.grid(rep(list(seq(length(X))),2)) %>% arrange_all()
an11 <- t(apply(an1, 1, function(x) as.vector(t(X))[x]))
Run Code Online (Sandbox Code Playgroud)
But as I mentioned, this doesn't improve the speed. Any suggestions? I am also thinking Rcpp might help but I am not sure and I have not tried that (not very good with the c++ syntax).
您根本不需要使用循环。由于您的ans1
和代码ans2
只是术语的总和,并且这些术语根本不相互作用,因此表达式简化为
ans1simple <- 0.45*sum(X)^2
ans2simple <- 1.9*sum(X)^3
Run Code Online (Sandbox Code Playgroud)
您可以对随机数据进行测试。X
如果您不相信,请更改 的种子或大小:
ans1simple <- 0.45*sum(X)^2
ans2simple <- 1.9*sum(X)^3
Run Code Online (Sandbox Code Playgroud)
由reprex 包(v1.0.0)于 2021 年 4 月 19 日创建
差异只是舍入误差。