1

我使用以下代码:

  library(foreach)
  library(doParallel)
  N<-5
  cl<-makeCluster(8)
  registerDoParallel(cl)

  #loop
  s8 <- foreach(i=1:N, .combine='rbind') %:%
    foreach(j=1:N, .combine='c') %dopar% {

        dis <-as.numeric (i+j)  } ## In reality there something more complicated

  stopCluster(cl) 

我得到以下结果:

> s8
         [,1] [,2] [,3] [,4] [,5]
result.1    2    3    4    5    6
result.2    3    4    5    6    7
result.3    4    5    6    7    8
result.4    5    6    7    8    9
result.5    6    7    8    9   10 

我想得到如下的上对角矩阵:

> s8
         [,1] [,2] [,3] [,4] [,5]
result.1    2    3    4    5    6
result.2    0    4    5    6    7
result.3    0    0    6    7    8
result.4    0    0    0    8    9
result.5    0    0    0    0   10

如果我将内部循环的迭代器更改为

foreach(j=i:N, .combine='c') %dopar% {

我没有得到所需的结果。

4

1 回答 1

1

也许这个(虽然我可能只会并行化外循环):

library(foreach)
library(doParallel)
N<-5
cl<-makeCluster(4)
registerDoParallel(cl)

#loop
#result is a list of vectors
s8 <- foreach(i=1:N) %:%
  foreach(j=i:N, .combine='c') %dopar% {

    as.numeric (i+j)  } ## In reality there something more complicated

stopCluster(cl) 

后处理以获得相同的长度:

s8 <- t(vapply(s8, function(x) {
  x <- rev(x)
  length(x) <- N
  rev(x)
}, FUN.VALUE = numeric(N)))

s8[lower.tri(s8)] <- 0

#     [,1] [,2] [,3] [,4] [,5]
#[1,]    2    3    4    5    6
#[2,]    0    4    5    6    7
#[3,]    0    0    6    7    8
#[4,]    0    0    0    8    9
#[5,]    0    0    0    0   10
于 2016-04-25T15:16:48.447 回答