如何在R中生成一个生成这些矩阵的循环?

时间:2018-04-19 16:46:07

标签: r loops optimization linear-programming gurobi

我正在尝试用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)

1 个答案:

答案 0 :(得分:3)

如图所示使用kronecker产品:

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