Skip to content
Advertisement

Python: porting to cvxopt quadratic programming from MATLAB’s quadprog

I am porting a MATLAB script to Python that uses the quadprog function. The best equivalent seems to be qp. I can work out the equivalent notation with the doc and a bit of time, but I’m lazy and it would be nice to just copy-paste some code instead of thinking about it. So:

  • Which of the parameters in the two functions are equivalent?
  • How do I incorporate the upper and lower bounds from quadprog into cvxopt.solvers.qp?

I’ve already read this related question but I’m even lazier than that.

Advertisement

Answer

This is a silly question you goose, but since there might be more lazy people around, take this line of MATLAB code (using numbered parameters for readability):

x = quadprog(C1, C2, C3, C4, C5, C6, C7, C8, ...)

The equivalent in Python will be:

import numpy
import cvxopt
n = C1.shape[1]   # This is for readability only    

P = C1
q = C2
G = numpy.vstack([C3, -numpy.eye(n), numpy.eye(n)])
h = numpy.hstack([C4, -C7, C8])
A = C5
b = C6

sol = cvxopt.solvers.qp(cvxopt.matrix(P), cvxopt.matrix(q), cvxopt.matrix(G), cvxopt.matrix(h), cvxopt.matrix(A), cvxopt.matrix(b))
x = sol['x']

Assuming that you’ve been working with numpy.arrays. If you’ve been using matrices, check this doc to find this formulation for G and h:

G = numpy.bmat('C3, -numpy.eye(n), numpy.eye(n)')
h = numpy.bmat('C4, -C7, C8')
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement