vbx897
vbx897

Reputation: 23

CVXPY vector constraints

I am looking to implement constraints on my optimization variable :

X=variable(2)

How can I specify constraints on X components, like "X[i] <= 1" for example, which I tried but don't seem to work" ? I did not find anything in the cvxpy documentation on this specific case, although it seems pretty basic...

I tried this simple example :

import cvxpy

X=variable(2)

constraints = [x[0] <= 5,
               x[1] <= 5]

obj=Maximize(x[0]+x[1])

Pb=Problem(obj, constraints)

but cvxpy does not find any solution

Thanks !

Upvotes: 1

Views: 3684

Answers (2)

Goncalo Cardoso
Goncalo Cardoso

Reputation: 29

the exact problem you described yields the expected solution:

import cvxpy as cvx
x = cvx.Variable(2)
constraints = [x[0] <= 5, x[1] <= 5]
obj = cvx.Maximize(x[0] + x[1])
prob = cvx.Problem(obj, constraints)
prob.solve()
10.0
x.value
array([5., 5.])

Upvotes: -1

Jacques Kvam
Jacques Kvam

Reputation: 3056

The documentation shows an example of this on the main page. You specify the constraints when you create the Problem. Here's a simple example:

import cvxpy
x = cvxpy.Variable(5)
constraints = [x[3] >= 3, x >= 0]
problem = cvxpy.Problem(cvxpy.Minimize(cvxpy.sum_squares(x)), constraints)
problem.solve()
x.value

Which outputs:

array([-0., -0., -0.,  3., -0.])

Upvotes: 3

Related Questions