我正在尝试使用R
包来解决lpsolve
中的线性规划问题。
问题在于:
以下是R中可重复示例的示例:
library("lpSolve")
a <- matrix(c(1,2,5,
1/2,1,3,
1/5,1/3,1),nrow=3,byrow=T)
#
f.obj <- c(1,0,0,0)
f.con <- matrix (c(
1,1,-a[1,2],0, #Contraint 1 for a12
1,-1,a[1,2],0, #Contraint 2 for a12
1,1,0,-a[1,3], #Contraint 1 for a13
1,-1,0,a[1,3], #Contraint 2 for a13
1,0,1,-a[2,3], #Contraint 1 for a23
1,0,-1,a[2,3], #Contraint 2 for a23
0,1,1,1, #Contraint 3
0,1,0,0, #Constraint 4
0,0,1,0, #Constraint 4
0,0,0,1 #Constraint 4
), nrow=10, byrow=TRUE)
f.dir <- c(rep("<=",6), "=",rep(">",3))
f.rhs <- c(rep(1,6),1,rep(0,3))
g <- lp ("max", f.obj, f.con, f.dir, f.rhs)
g$solution
如果我有7 X 7
或n x n
矩阵a
,我可以手动解决这个小问题。我如何指定约束1
和2
,特别是我在努力定义与[i,j]相关的约束?
a = matrix(
c(1,4,9,6,6,5,5,
1/4,1,7,5,5,3,4,
1/9,1/7,1,1/5,1/5,1/7,1/5,
1/6,1/5,5,1,1,1/3,1/3,
1/6,1/5,5,1,1,1/3,1/3,
1/5,1/3,7,3,3,1,2,
1/5,1/4,5,3,3,1/2,1
),nrow = 7,byrow =T)
上述矩阵的解决方案是0.986 0.501 0.160 0.043 0.060 0.060 0.1 0.075
我们非常感谢任何帮助。
答案 0 :(得分:3)
已更新以合并修订后的约束4并进行了一些次要的代码改进。
假设问题中的约束矩阵是正确的,则使用combn
迭代所有i&lt; j设置适当的元素。请注意,x[1]
是i
的值,x[2]
是j
中f
的值。 make_cons
按照问题中显示的顺序返回约束矩阵,但如果可以使用此类订单,则rbind
中的make_cons
行可以简化为rbind(cons1, cons2, cons3, cons4)
。
make_cons <- function(a) {
n <- nrow(a)
f <- function(x) replace(numeric(n), x, c(1, -a[x[1], x[2]]))
cons1 <- cbind(1, t(combn(1:n, 2, f)))
cons2 <- cbind(1, -cons1[, -1])
cons3 <- c(0, rep(1, n))
cons4 <- cbind(0, diag(n))
rbind(t(matrix(rbind(t(cons1), t(cons2)), ncol(cons1))), cons3, cons4)
}
# test
# a and f.con from question
a <- matrix(c(1, 0.5, 0.2, 2, 1, 0.333333333333333, 5, 3, 1), 3)
f.con <- matrix(c(1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, -1, 1, -1, 0, 0,
1, 1, 0, 0, -2, 2, 0, 0, 1, -1, 1, 0, 1, 0, 0, 0, -5, 5, -3,
3, 1, 0, 0, 1), 10)
all.equal(f.con, make_cons(a), check.attributes = FALSE)
## [1] TRUE
答案 1 :(得分:1)
这是一种使用for循环的可能性。
正如我在共事中所提到的,我认为你的条件(4)是错误的。这是我的建议。 我的想法是首先建立一个约束矩阵(4),然后是约束(3) 然后在循环中添加约束(2)和(1)。请注意,在开始时,我不认为对应于\ mu的列。我最后会添加这一栏。
n<- nrow(a)
f.cons<- diag(n)
f.cons<- rbind(f.cons, rep(1,n))
这建立了对应于约束(4)(前n行)和约束(3)的矩阵。现在我使用循环和命令 rbind 添加行到此矩阵。
for(i in 1:(n-1)){
for(j in (i+1): n){
x<- rep(0, n)
x[i]<- 1 #x corresponds to (1)
x[j]<- -a[i,j]
y<- -x #y corresponds to (2)
f.cons<- rbind(f.cons, rbind(x, y))
}
}
到目前为止,我忽略了第一列,它对应于\ mu。 我用这两个简单的行添加它:
f.cons<- cbind(rep(1, nrow(f.cons)), f.cons)
f.cons[1:(n+1), 1]=0
请注意,在我的矩阵f.cond中,前n + 1行对应于约束(3)和(4)!