提前谢谢。
我有三个嵌套的for循环,其中最低的循环包含一个条件if语句求值。
代码成功运行,尽管使用一个foreach循环和两个嵌套的for循环非常缓慢。对于我的“真实”数据,我可以在大约16小时内运行~ 1000 x 2000 x 160迭代。我想把它放大到~ 10000 x 2000 x 160,这将花费太长的时间来运行(>100小时)。理想情况下,我希望将嵌套的for循环转换为apply循环,因为我知道它们运行得更快。我构建了如下示例代码:
library("foreach")
library("doMC")
registerDoMC()
R = 10
N = 5
M = 10
data_matrix <- matrix(data=runif(50,N,M),ncol=10)
cos_function<- function(x,y){
res<-runif(1,3,5)
res<-res + (3/x) + (4/y)
return(res)
}
results<-foreach(k=1:R,combine=rbind) %dopar% {
dummy<-matrix(0, N, M)
for (i in 1:N) {
for (j in 1:M) {
if (cos_function(i, j) <= data_matrix[i,j]) {
dummy[i,j] = 1
}
}
return(dummy)
}我想出了很多方法来加快这个过程:包括嵌套循环的并行化,切换到嵌套的应用函数,将嵌套的循环组合成一个应用循环。正如您可能知道的,我对R和并行化非常陌生,所以任何指导都是非常有用的。
发布于 2014-03-04 21:41:11
我知道你的数据只是玩具数据,这个答案并没有回答你原来的问题,但是你考虑过优化你的矩阵计算吗?
以下代码在90秒内(而不是16h)在我的笔记本上运行:
R <- 160
N <- 1000
M <- 2000
## construct your data_matrix and replicate it R-times to get the same size
## like the cosmatrix
data_matrix <- matrix(data=rep(runif(N*M, N, M), R), byrow=TRUE, ncol=M)
## construct whole cosmatrix (inclusive replications R)
cosmatrix <- matrix(data=runif(N*M*R, 3, 5), ncol=M)
## perform your cos_fun
cosmatrix <- t(t(cosmatrix+3/(1:N)) + 4/(1:M))
## comparison
cosmatrix <= data_matrix发布于 2014-03-04 21:40:57
我不太熟悉并行化,但也许修改下面的内容会更快
dat<- matrix(data=runif(50,N,M),ncol=10)
#defining a new version of cos which takes a matrix
new_cos<-function(m) (3/m$i) + (4/m$j)
#create a data.frame ij which holds i and j combinations as each row.
ij<-expand.grid(i=seq(N),j=seq(M))
#now use this for your res. This will return a vector, where res[1] is the result of i=1 and j=1,
#res[2] is the result of i=2, j=1.
res<-runif(M*N,3,5)+new_cos(ij)
##now this will compare as appropriate, since the comparisons will be done column-wise along dat
##multiply booleans by 1 to get your 1/0 matrix
1*(res<=dat)https://stackoverflow.com/questions/22182942
复制相似问题