用mapply替换嵌套的for循环

时间:2017-12-07 14:28:45

标签: r for-loop apply sparse-matrix nested-loops

我是R的初学者。我正在使用R studio的Cplex进行线性编程来解决模型问题。我的模型中的约束之一是X1(i,j,t)< = D(i,j,t)。我可以使用嵌套的for循环(16X16X6)来做到这一点。但我想让我的模型运行更大的模型,更像是2500X2500X60。我需要节省内存并以比嵌套for循环更快的速度运行它。我想过使用apply但我不知道如何使它工作。任何帮助将不胜感激!

location <-16
horizon <-6
Amat <- NULL
Xe_null <- array(0, dim = c(locations, locations, horizon))
Xl_null <- array(0, dim = c(locations, locations, horizon))
Xl      <- array(0, dim = c(locations, locations, horizon))
Xl <- Xl_null
for (t in 1:horizon) {
  for (j in 1:locations) {
    for (i in 1:locations) {
      Xl[i,j,t] <- 1
      Amat <- rbind(Amat, c(as.vector(Xe_null), as.vector(Xl)))
      Xl <- Xl_null 
 } } }
dim(Amat) # 1536 3072

这是另一个约束。

R       <- array(, dim=c(locations, horizon, horizon))
R_null  <- array(, dim=c(locations, horizon, horizon))
R <- R_null
Xe <- Xe_null
Xl <- Xl_null
#
for (t in 1:(horizon-1)) {
  for (tp in (t+1):horizon) {
    for (j in 1:locations)     {
      for (i in 1:locations)      {
        if ((tp-t) ==Travel_time[i,j]) 
        {
          Xe[i,j,t]=1
          Xl[i,j,t]=1
        } 
      }
      R[j,tp,t] = 1
      R[j,tp,t+1] = -1
      Amat <- rbind(Amat, c(as.vector(Xe), as.vector(Xl),as.vector(R)))
      }
  }
}

我尝试这样做:

Xl = function(ii,jj,tt){1}
t =c(1:horizon)
i =c(1:locations)
j =c(1:locations)
output_Xl = apply(expand.grid(i,j,t),1,function(x,y,h) Xl(x[1],x[2],x[3]))
Xl_new <- array(output_Xl, dim = c(locations, locations, horizon))
Amat <- rbind(Amat, c(as.vector(Xe_null), as.vector(Xl_new)))
dim(Amat) # 1 3072

2 个答案:

答案 0 :(得分:2)

您可以使用

获得相同的输出
T <- horizon*locations*locations
Bmat <- cbind(matrix(0, nrow=T, ncol=T), diag(1, nrow=T, ncol=T))
identical(Amat, Bmat)
# TRUE

答案 1 :(得分:2)

我认为你需要的是使矢量化函数提供相同的输出(参见Dim report As New <Name of your embedded crystal report> report.SetDataSource(ds.Tables("fruit_stock")) <your_crystal_report_viewer_in_your_form>.ReportSource = report )。下面的代码是你的速度的五百倍 在您遇到实际问题时,您可能需要使用?Vectorize代替<<-(请参阅<-

?"<<-"