I want to solve a minimization problem with two constraints in R.
Problem: min x^T H x st
(1) e^T*x = 1,
(2) 0 < x_i <= 1 , i=1,..,20.
H
is a 20x20 Matrix and e
is vector of ones with length 20
How can I do this? I looked at optimize
, optim
and optimix
, but somehow I don't know how to start.
I started to create my objective function:
f<- function(x) {t(x)%*%H%*%x}
and constraint (1)
g<- function(x) {t(e)*x=1}
But I don't know how to formulate constraint (2).
I also don't know which optimization function is suitable for this problem. I am thankful for any advice.
In the end I want to receive a vector x with 20 values.
check the quadprog
package. It has a function solve.QP
to solve the following quadratic programming:
min(-d^T b + 1/2 b^TD b) with the constraints A^T b >= b_0.
In your case D=H*2, d = 0.
Here is how you can construct the matrix A and vector b0 for your problem:
Amat <- t(rbind(rep(1, n), diag(1, 20), -diag(1, 20))
b0 <- c(1, rep(0, 20), rep(-1, 20))
Then you can run
library(quadprog)
solve.QP(Dmat = 2*H, dvec = 0, Amat = Amat, bvec = b0, meq = 1)
Note that meq = 1
indicates that first inequality should be an equality.
If you only want the optimal x
values then try this:
solve.QP(Dmat = 2*H, dvec = 0, Amat = Amat, bvec = b0, meq = 1)$solution
Hope this helps.
Here is how to do with the CVXR
package.
Note that (1) is the same as sum(x_i) = 1
, and (2) can be simplified to x_i > 0
because sum(x_i) = 1
and x_i > 0
=> x_i <= 1
.
H <- rWishart(1, df = 30, diag(20))[,,1] # a 20x20 symmetric positive matrix
library(CVXR)
# the variable
x <- Variable(20)
# objective
objective <- Minimize(quad_form(x, H))
# define problem
constraint1 <- sum(x) == 1
constraint2 <- x > 0
problem <- Problem(objective, constraints = list(constraint1, constraint2))
# solve problem
result <- solve(problem)
# results
result$getValue(x) # optimal x
result$value # value of objective at optimal x
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.