How to write several constraint in cvxpy?

这一生的挚爱 提交于 2019-12-11 06:55:54

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/42706519/how-to-write-several-constraint-in-cvxpy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!