bakun
bakun

Reputation: 475

For loop with 2 iterators in Julia/JuMP

I need to implement the following pseudocode to JuMP/Julia:

forall{i in M, j in Ni[i]}:  x[i] <= y[j];

I imagine something like:

for i in M and j in Ni[i]
    @constraint(model, x[i] <= y[j])
end

How do I properly implement the 2 iterators in the for loop?

Upvotes: 3

Views: 965

Answers (2)

Oscar Dowson
Oscar Dowson

Reputation: 2574

You want

@constraint(model, [i = M, j = Ni[i]], x[i] <= y[j])

Here is the relevant documentation: https://www.juliaopt.org/JuMP.jl/stable/constraints/#Constraint-containers-1

Upvotes: 1

fredrikekre
fredrikekre

Reputation: 10984

I don't know if you want one iteration with both values, or the Cartesian product of the iterators, but here are example for both:

julia> M = 1:3; N = 4:6;

julia> for (m, n) in zip(M, N) # single iterator over both M and N
           @show m, n
       end
(m, n) = (1, 4)
(m, n) = (2, 5)
(m, n) = (3, 6)

julia> for m in M, n in N # Cartesian product
           @show m, n
       end
(m, n) = (1, 4)
(m, n) = (1, 5)
(m, n) = (1, 6)
(m, n) = (2, 4)
(m, n) = (2, 5)
(m, n) = (2, 6)
(m, n) = (3, 4)
(m, n) = (3, 5)
(m, n) = (3, 6)

Upvotes: 6

Related Questions