Summing Variables by Indices in Python
AnsweredLet's say I have a set of variables x indexed from 1 to 100. How can I constrain the sum of all x indexed i or higher?
0
-
This depends on how you define the \(x\) variables in Python. I'll provide two examples. In both examples, I'll assume the variables are indexed \(0\) to \(99\) instead of \(1\) to \(100\).
If you add the variables via Model.addVars(), you can sum over the desired indices using the quicksum() function, then add the constraint with Model.addConstr():
x = m.addVars(100, name="x")
m.addConstr(gp.quicksum(x[j] for j in range(i, 100)) <= 10)If you add the variables via Model.addMVar(), you can slice the MVar object to only include the desired indices, then call MVar.sum() on the result. The constraint is again added via Model.addConstr():
x = m.addMVar((100,), name="x")
m.addConstr(x[i:].sum() <= 10)0
Please sign in to leave a comment.
Comments
1 comment