r - Constrained quadratic optimization with the quadProg library -
i have vector a of length n. have n*n matrix c. want maximize following equation :
minimize (- (w_transpose * a) + p * w_transpose * c * w) where w vector of length n, constraints each w non-negative , sum of w 1.
i have seen package called quadprog. there need specify :
dmat = c, dvec = a, , bvec = w
but not sure how apply above mentioned constraints there.
i suppose provide amat identity matrix, keep w non-negative. not sure how keep w normalized (sum equal zero). normalize them later well, still wondering if can here itself.
you can solve.qp function quadprog. ?solve.qp, read solve.qp solves systems of form min_b {-d'b + 0.5 b'db | a'b >= b0}. solving problem of form min_w {-a'w + pw'cw | w >= 0, 1'w = 1}. thus, mapping between forms:
d = a(this calleddvecin argumentssolve.qp)d = 2pc(this calleddmatin argumentssolve.qp)- for first set of constraints, have
i'w >= 0. final constraint can reformulated1'w >= 1,-1'w >= -1. therefore matrix of constraints (amatin argumentssolve.qp) identity matrix 1 vector , -1 vector appended on right, , right-hand side b0 (bvecin argumentssolve.qp) 0 vector 1 , -1 appended.
you can put in r pretty easily:
library(quadprog) solve.my.qp <- function(a, p, c) { solve.qp(dmat=2*p*c, dvec=a, amat=cbind(diag(1, length(a)), rep(1, length(a)), rep(-1, length(a))), bvec=c(rep(0, length(a)), 1, -1))$solution } you can test on simple 2-dimensional problems:
# penalty solve.my.qp(c(0, 0), 1, diag(1, 2)) # [1] 0.5 0.5 # encourage inclusion of first variable solve.my.qp(c(0.1, 0), 1, diag(1, 2)) # [1] 0.525 0.475
Comments
Post a Comment