I want to implement some conditions in my objective function. I know adding conditions to constraints is possible through addGenConstrIndicator() but I don't know how I can add conditions in the objective function. Here is a minimal example snippet for my problem. I have variable v with size = 3, prev_values are the previous values for this variable (consider a temporal scenario with the next variable values is dependent on the previous variable values). Now, I want to check if the current value is either equal to 0 or equal to its previous values, and use it in my objective function. How can I implement this in Gurobi (below is a sketch of what I intend to implement)?

model = gp.Model()
E = [2, 4, 7]
prev_values = [4, 5, 1]
v = model.addVar(3, lb=0, vtype=gp.GRB.INTEGER, )

def check(vn, vp):
    if vn == 0 or vn == vp:
        return 0
    return 1

model.setObjective(max([check(v[i], prev_values[i]) * E[i] for i in range(3)]) , gp.GRB.MINIMIZE)

1 Answer 1


If you are trying to maximize $\sum_i E_i f(v_i, p_i)$ where $v_i$ and $p_i$ are nonnegative integer variables and $f(v_i, p_i)$ is zero if either argument is zero and 1 if both arguments are strictly positive, you can do it by introduce a new binary variable $z_i$ to represent the value of $f(v_i, p_i).$ (I'm assuming here that $E_i$ is a nonnegative parameter.) Your object becomes $\max \sum_i E_i z_i,$ and you add the constraints $z_i \le v_i$ and $z_i \le p_i$ for all $i.$

  • $\begingroup$ thank you for answer, could you plz elaborate a bit more on how I can add this new binary variable to the Gurobipy? $\endgroup$ Commented Mar 9, 2023 at 20:13
  • $\begingroup$ No, I cannot, since I am not a Gurobi user (nor a Python user). $\endgroup$
    – prubin
    Commented Mar 9, 2023 at 20:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.