Constraints with for loop and if statements

Hi, I am new to Julia and by extension JuMP. I am trying to rewrite a model for an optimization problem from Matlab to Julia using JuMP. Now following the documentation on the JuMP webpage, I have some doubts about writing the constraints in Julia. In Matlab, one of my constraint looks like this:

uc_miqp.Constraints.isOn = optimconstr(nHours, nUnits)
for kk = 1:nHours
    for jj = 1:nUnits
        uc_miqp.Constraints.isOn(kk, jj) = isOn(kk, jj) <= 1
    end
end

And following the documentation, I have rewritten it as follows:

@constraint(uc_miqp, [kk = 1:nHours, jj = 1:nUnits], isOn[kk, jj] <= 1)

Now I think what I have is correct, but what if I wanted to have it resemble the code in Matlab. Would it look like this:

for kk = 1:nHours
    for jj = 1:nUnits
        @constraint(uc_miqp, isOn[kk, jj] <= 1)
    end
end

Furthermore, I have some constraints with for loops and if else statements. What would be the correct or recommended way to implement something like this? This following is what I have implemented in Julia for for loops containing if else statements. For example if the Matlab code is :slight_smile:

uc_miqp.Constraints.isOn = optimconstr(nHours, nUnits)
for kk = 1:nHours
    for jj = 1:nUnits
        if kk <= 5
            uc_miqp.Constraints.isOn(kk, jj) = isOn(kk, jj) <= 1
        else
            uc_miqp.Constraints.isOn(kk, jj) = isOn(kk, jj) >= 1
        end
    end
end

I have implemented this is in Julia using the following 2 constraints:

@constraint(uc_miqp, [kk = 1:nHours, jj = 1:nUnits; kk <= 5], isOn[kk, jj] <= 1)
@constraint(uc_miqp, [kk = 1:nHours, jj = 1:nUnits; kk > 5], isOn[kk, jj] >= 1)

Would this be the best way to implement this?
The constraints may not make logical sense, it only used as an example.

You can rewrite this to be exactly the same if you want:

for kk = 1:nHours
    for jj = 1:nUnits
        if kk <= 5
            @constraint(uc_miqp, isOn[kk, jj] <= 0)
        else
            @constraint(uc_miqp, isOn[kk, jj] >= 0)
        end
    end
end

Incidentally, you should use j and k as your loop variables in julia. The convention of ii, jj, kk is very ugly, and only born in matlab out of fear of interfering with the imaginary number constants i/j, which is a problem julia doesn’t suffer from.


For that matter, you can also do:

@constraint(uc_miqp, isOn[1:5,  :] .<= 0)
@constraint(uc_miqp, isOn[6:end, :] .>= 0)
2 Likes