本文介绍了如何在cvxpy中编写几个约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在cvxpy下的优化问题中添加许多约束.在matlab中,我可以通过添加一个主题,然后使用for循环生成约束来做到这一点.我如何在cvxpy中完成相同的工作,因为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?
推荐答案
在Python中,constraints
是一个列表.您可以像这样使用for循环附加/扩展(和 CVXPY函数让它变得更容易).
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
这篇关于如何在cvxpy中编写几个约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!