# Defining an if condition in a constraint

Hello everyone!
I want to define an if condition in a constraint. I will have different constraints if the variable is positive or negative (Pb >0.0 or Pb <0.0), and you can see this part of the code;

``````for i in 1:5, t in 1:24
if Pb[i,t] <= Zeromat
@constraint(m, e[i,t] - e[i,t.-1] + 0.85 *Pb[i,t.-1] == 0.0);
else
@constraint(m, e[i,t] - e[i,t.-1] - 1.11 *Pb[i,t.-1] == 0.0);
end
end
end
``````

but I am facing this error

``````MethodError: no method matching isless(::VariableRef, ::Matrix{Float64})
``````

SideNote1: Zeromat is an array of zeros [5,24]. I also tried it with simple zero (0.0 ) but then I will face the following error,

``````Cannot evaluate `<=` between a variable and a number.
``````

SideNote2: I am using Gurobi.jl.

I’m not an experienced JuMP user, but I think you are looking for `@NLconstraint`.

Here is an example:

1 Like

Thank you, I tried to change the constraint into a non linear one, but I am still facing the same error I have no idea if this will work but it puts everything inside the macro

``````@constraint(m, e[i,t] - e[i,t.-1] + (Pb[i,t] <= Zeromat ? 0.85 : -1.11) * Pb[i,t.-1] == 0.0);
``````
1 Like

You need to set up a binary variable (integer variable constrained by 0 <= Z[I,t] <= 1) that takes a different value depending on the sign of Pb[I,t]. (C.f. Big M method - Wikipedia )

Then you can simply write your constraint as

``````e[i,t] - e[i,t.-1] + (0.85 + (-1.11-0.85)*Z[i,t]) * Pb[i,t.-1] == 0.0
``````

Edit: I just realised it is a bit trickier still. The product between the binary and the continuous variable needs to be re-written using another artificial variable and a few constraints if you want a mixed-integer linear formulation.

4 Likes

Will not, linear programming does not allow for conditionals inside constraints, unless you use tricks like @Per have shown.

2 Likes

Gurobi will automatically handle the bilinear term, so this approach should work fine.

1 Like

Thanks, it works fine now!