Linear Programs using R

本秂侑毒 提交于 2019-12-14 02:29:06

问题


How can we solve a linear program using R? I want to solve the following example:

min -a -2b +4c

Constraints
a + b + s1 = 5
a + 3c -s2 = 10
2b - 3c = 20

a >= 0, b >= 0, c >= 0, s1 >= 0, s2 >= 0

The equations might not make total sense. I just need to know the syntax of writing these equations in R. I might write something like this for the above equations

require(lpSolve)

R.obj <- c(-1,-2,4)

R.con <- matrix(c(1,1,1,1,3,-1,2,-3),nrow=3,byrow=TRUE)

R.dir <- c("=","=","=")

R.rhs <- c(5,10,20)

lp("min",R.obj,R.con,R.dir,R.rhs)

Would this be correct? In the documentation, the matrix is always M*M, what if the matrix is M*N where N != M?


回答1:


Your constraint matrix has 3 rows and 5 columns, but you've only provided the 8 non-zero values when building your constraint matrix. Further, you have 5 variables, so R.obj needs 5 values:

require(lpSolve)
R.obj <- c(-1, -2, 4, 0, 0)
R.con <- matrix(c(1, 1, 0, 1, 0, 2, 0, 3, -3, 1, 0, 0, 0, -1, 0), nrow=3)
R.dir <- c("=", "=", "=")
R.rhs <- c(5, 10, 20)
lp("min", R.obj, R.con, R.dir, R.rhs)
# Error: no feasible solution found

A bit of math shows that this LP is indeed infeasible. This LP is equivalent to -a - b >= -5, a + 3c >= 10, b = 10 + 1.5c. You can substitute the last equation into the first to yield -a - 1.5c >= 5 and a + 3c >= 10, and adding yields c >= 10. By your third equation, b >= 25, which means the first equation can never hold due to the non-negativity of a and s1.



来源:https://stackoverflow.com/questions/22310767/linear-programs-using-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!