Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write several constraint in cvxpy?

I want to add many constraint in a optimization problem under cvxpy. In matlab I can do so by adding a line subject to and then use for loop to generate the constraints. How can I do the same work in cvxpy, as there is no 'subject to' concepts in cvxpy. any suggestion please?

like image 650
Creator Avatar asked Dec 23 '22 20:12

Creator


1 Answers

In Python constraints is a list. You can use for loop to append/extend it like this (and CVXPY functions make it easier).

import cvxpy as cvx

samples = 10
x = cvx.Variable(samples)
y = range(1, samples+1)
constraints = []

for i in xrange(samples):
    constraints += [
        y[i] * x[i] <= 1000,
        x[i] >= i
    ]

objective = cvx.Maximize(cvx.sum_entries(x))

prob = cvx.Problem(objective, constraints)
prob.solve()
print x.value
like image 103
dave-cz Avatar answered Jan 10 '23 01:01

dave-cz