Search code examples
pythoncvxpy

Incremental Summation of Expressions in CVXPY


I need to incrementally build a CVXPY expression, e.g. a sum.
At the moment I'm using:

sum_expr = None

for ...
   var = cp.Variable(...)
   if sum_expr:
      sum_expr += var
   else:
      sum_expr = var

# use sum_expr 

Is there a cleaner, more concise way to do this?

Is there some default NOP/Null/Void/Nil value I can use to initialize sum_expr so that I can avoid the if statement and just use the +=?


Solution

  • Short answer is to use the neutral element for the specific operation, e.g. cp.Constant(0) for summation and cp.Constant(1) for products.

    There is no built-in "Null" expression, but adding a single neutral element to the parse tree does not really affect performance.

    Longer thread with answer is here.