1

I have a nested for loop below (which does not do much but it is a simpler version of something that I would like to do). I would like to parallelize this computation.

x=seq(-4,4,length.out=1000)
y1 = pnorm(x)
y2 = pnorm(x, mean = 2)
y3 = pnorm(x, mean = 2.1)
y4 = pnorm(x, mean = 2.2)
y5 = pnorm(x, mean = 2.3)
y6 = pnorm(x, mean = 2.4)
y7 = pnorm(x, mean = 2.5)
y8 = pnorm(x, mean = 2.6)

A = matrix(c(y1,y2),nrow = 2, byrow =TRUE)
B = array(c(y3,y4,y5,y6,y7,y8), dim = c(1000,3,2))

tt = 1:1000
BB = 3
set.seed(1)
BBB = runif(BB)

res=matrix(0,nrow=2,ncol=2)
width = double(2)

for(i in 1:2){
  Ai=A[i,]
  Bi=B[,,i]

  C = approx(Ai, tt, BBB)$y

  D=double(BB)

  for(j in 1:3){
    D[j]=approx(tt, Bi[,j], C[j])$y
  }

  alphastar=quantile(D,c(0.1/2,1-0.1/2))

  res[i,]=approx(Ai, tt, alphastar)$y
  width[i] = diff(res[i,])

}

There are some similar questions Q1 and Q2, but they do not answer my question. In summary, my calculation has the following form

for(i in 1:2){
code involving only i subscript

for(j in 1:3){
code which uses output from above
}

code involving output from j loop
}

Is it possible to nest for loops in this way by using foreach? I would like this code to return res (a matrix) and width (a vector).

Edit: Q1 contains an interesting example:

x <- foreach(i=1:8, .combine='rbind') %:%
   foreach(j=1:2, .combine='c') %dopar% {
     l <- runif(1, i, 100)
     i + j + l  
   }

But, I do not want to run (in this example) l <- runif(1, i, 100) for each j. It only needs to be ran once, for each i. Running everything in both loops is going to waste a lot of time (maybe not in this example but it will in other examples). Is it possible to obtain something of the form

x <- foreach(i=1:8, .combine='rbind') %:%
  l <- runif(1, i, 100)
  foreach(j=1:2, .combine='c') %dopar% {
    i + j + l  
  }

The above code does not work. Is there any way of modifying the above to allow for the code that does not involve j to be computed in the first loop and not to waste time running it for each j?

JLee
  • 237
  • 1
  • 10

1 Answers1

0

Take a look on this .A similar question about Nested foreach() has answered with some examples.