2
\$\begingroup\$

I have several large numeric vectors (close to 1e6 entries each) and I need to make some computations with their values:

iters=100
iters2=100
set.seed(91)
sampleSubset<-sample(1:1e6, iters)
mR12 <- mR1[sampleSubset]
mRy2 <- mRy[sampleSubset]
mDMDuc12 <- mDMDuc1[sampleSubset]
mDMDc2 <- mDMDc[sampleSubset]
mFR <- matrix(, nrow = 0, ncol = 1)
mFR <- foreach(i=1:iters, .combine=rbind, .packages="foreach") %do% {
          mp2 <- mp[sample(1e6, iters2)]
          mFR3 <- matrix(, nrow = 0, ncol = 1)
          foreach(j=1:iters2, .combine=c) %do% {
             if (mp2[j]>mR12[i]) {
               Frv = 1
             } else if ((mR12[i]<mRy2[i]) | (mR12[i]<0.005) |
                          (mRy2[i]<0.005) | (mDMDuc12[i]<1e4) |
                          (mDMDc2[i]<1e7) | (mDMDc2[i]<mDMDuc12[i])) {
               Frv = NA
             } else if (mp2[j]<=mRy2[i]) {
               Frv = 0
             }  else {
               #points A(Ry,0) and B(R1,DMDuc1)
               #linear: y = mx + b
               #m = -b/Ry
               #m = (mDMDuc1 - b)/R1
               #-b/Ry = (mDMDuc1 - b)/R1 -> -b*R1/Ry = (mDMDuc1 - b) -> b(1-R1/Ry) = mDMDuc1 -> b= mDMDuc1/(1-R1/Ry)
               b = mDMDuc1[i]/(1-mR12[i]/mRy2[i])
               m = -b/mRy2[i]
               DMDp = m*mp2[j] + b
               Frv = (DMDp - 0)/(mDMDc2[i] - 0)
             }
             mFR3 <- rbind(mFR3,matrix(Frv, ncol=1, nrow = 1))
             mFR3
           }
            mFR <- mFR3
            mFR
}
colnames(mFR) <- "mFR"
mFR <- mFR[rowSums(is.na(mFR)) != ncol(mFR),1]

But for large values of iters and iters2, close to 1e6 (as I want to get accurate results), this takes hours. I'd like to reduce the execution time.

Examples to run:

mR1<- matrix(rnorm(1e6), nrow = 1e6, ncol = 1)
mRy<- matrix(rnorm(1e6), nrow = 1e6, ncol = 1)
mDMDuc1 <- matrix(rnorm(1e6), nrow = 1e6, ncol = 1)
mDMDc <- matrix(rnorm(1e6), nrow = 1e6, ncol = 1)
mp<- matrix(rnorm(1e6), nrow = 1e6, ncol = 1)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.