Let's consider a simple linearly constrained quadratic program of the form you have mentioned:
min 0.5x^2 + 0.7y^2
s.t. x + y = 1
x >= 0
y >= 0
Solution with the quadprog
package
The quadprog
package accepts models of the following form:
min −d'b + 1/2b'Db
s.t. A'b >= b0
To get our problem into this form, we need to construct a matrix D
with (2*0.5 2*0.7)
as the main diagonal, as well as a matrix A
with our three constraints and a right hand side b0
:
dvec <- c(0, 0)
Dmat <- diag(c(1.0, 1.4))
Amat <- rbind(c(1, 1), c(1, 0), c(0, 1))
bvec <- c(1, 0, 0)
meq <- 1 # The first constraint is an equality constraint
Now we can feed this to solve.QP
:
library(quadprog)
solve.QP(Dmat, dvec, t(Amat), bvec, meq=meq)$solution
# [1] 0.5833333 0.4166667
Solution with the limSolve
package
The limSolve
package's lsei
function accepts models of the following form:
min ||Ax-b||^2
s.t. Ex = f
Gx >= h
To obtain our objective function we need to construct matrix A
with (sqrt(0.5) sqrt(0.7))
as the main diagonal, set b
to be the 0 vector, as well as matrices and vectors encoding the other information:
A <- diag(c(sqrt(0.5), sqrt(0.7)))
b <- c(0, 0)
E <- rbind(c(1, 1))
f <- 1
G <- diag(2)
h <- c(0, 0)
Now we can feed this information to lsei
:
library(limSolve)
lsei(A, b, E, f, G, h)$X
# [1] 0.5833333 0.4166667