r - 使用 lpsolve 在 R 中进行线性规划

标签 r loops matrix linear-programming lpsolve

我正在尝试使用 lpsolve 包解决 R 中的线性规划问题。

问题是这样的:

enter image description here

以下是 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 7n x n 矩阵 a 会怎么样? 。我如何指定约束 12,特别是我正在努力定义与 a[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任何帮助将不胜感激。

最佳答案

已更新以纳入修订后的约束 4,并进行了一些小的代码改进。

假设问题中的约束矩阵是正确的,则使用 combn 迭代所有 i < j 设置适当的元素。请注意,x[1]i 的值,x[2]j 的值fmake_cons 以与问题中所示相同的顺序返回约束矩阵,但 make_cons 中的 rbind 行可以简化为 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

关于r - 使用 lpsolve 在 R 中进行线性规划,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41019115/

相关文章:

php - 使用 php 不同地重命名每个选定的文件

使用循环的javascript对象操作

php - 使用 PHP 对 MySQL 输出进行分层排序

string - 确定满足汉明距离矩阵的字符串

Numpy 高级索引困惑

r - 给定位置和条件,用 R 改变向量中的值

在 Sweave 中渲染网格图形

java - 如何创建邻居的ArrayList来协调无向图中的节点?

r - 使用 stat_summary : summary range reaches zero 以对数刻度绘制数据

r - `setDT` 包中的 `data.table` 错误