【问题标题】:How can I make a loop in R that produces these matrices?如何在 R 中创建一个生成这些矩阵的循环?
【发布时间】:2018-04-20 00:58:36
【问题描述】:

我正在尝试使用 R 中的 Gurobi 解决大规模分配问题。我需要一个循环来为我指定的任何 n 生成约束矩阵,因为对于非常大的问题我将无法手动输入它们。我粘贴了 n=2 和 n=3 的样本矩阵以及我为 n=2 提出的代码。我需要 n-i 部分继续为 1、2、3、4 等,但每个新行都需要累积。我知道我还有很长的路要走,而且我对 R 很陌生。任何帮助将不胜感激,谢谢。

n=2

1 1 0 0 
0 0 1 1 
1 0 1 0
0 1 0 1

n=3
1 1 1 0 0 0 0 0 0
0 0 0 1 1 1 0 0 0
0 0 0 0 0 0 1 1 1
1 0 0 1 0 0 1 0 0 
0 1 0 0 1 0 0 1 0
0 0 1 0 0 1 0 0 1



library("gurobi")

model <- list()

n=2

i=0
while (i <= n-2) {
  print(i)
  i = i+1
}
i

a=rep(1,n) 
b=rep(0,(n-i)*n)
c=rep(0,n) 
d=rep(1,n) 
e=rep(0,(n-i)*n)
f=rep(1:0, times=n)
g=rep(0:1, times=n)



model$A          <- matrix(c(a,b,c,d,e,f,g), nrow=4, ncol=4, byrow=T)
model$obj        <- c(1,2,3,4)
model$modelsense <- "min"
model$rhs        <- c(1,1,1,1)
model$sense      <- c('=', '=','=','=')
model$vtype      <- 'B'

params <- list(OutputFlag=0)

result <- gurobi(model, params)

print('Solution:')
print(result$objval)
print(result$x)

【问题讨论】:

    标签: r loops optimization linear-programming gurobi


    【解决方案1】:

    如图所示使用克罗内克产品:

    make_mat <- function(k) {
      d <- diag(k)
      ones <- t(rep(1, k))
      rbind( d %x% ones, ones %x% d )
    }
    lapply(2:3, make_mat)
    

    给予:

    [[1]]
         [,1] [,2] [,3] [,4]
    [1,]    1    1    0    0
    [2,]    0    0    1    1
    [3,]    1    0    1    0
    [4,]    0    1    0    1
    
    [[2]]
         [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
    [1,]    1    1    1    0    0    0    0    0    0
    [2,]    0    0    0    1    1    1    0    0    0
    [3,]    0    0    0    0    0    0    1    1    1
    [4,]    1    0    0    1    0    0    1    0    0
    [5,]    0    1    0    0    1    0    0    1    0
    [6,]    0    0    1    0    0    1    0    0    1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-16
      • 2021-02-08
      • 2017-11-22
      • 1970-01-01
      相关资源
      最近更新 更多