How to include the iteration number of a loop in variable names?

I have a loop iterating on r and want to define the variable x^r in every iteration.

I know one possibility is defining an anonymous variable, but it is not what I need.

for r in 1:4
      x = @variable(m, [r:r] )

I need the iteration number to be included in the variable name, so in the end of the iteration I’ll have: x^1 , x^2 , x^3 and x^4.

x = map(1:4) do r
      @variable(m, [r:r] )

Then you have a vector x with x[1] to x[4].

Are you looking for something like:

model = Model()
x = VariableRef[]
for r in 1:4
    x_r = @variable(model, base_name = "x[$r]")
    push!(x, x_r)

Docs: Variables · JuMP

1 Like

Thank for the your help.
I define this variable

δ = VariableRef[]
        for t in 1:T
            for ω in 1:Ω
                for l in 1:L[t,ω]
                    for r in 1:R
                        δ_r = @variable(m,  base_name = "δ[$t,$ω,$l,$r]")
                        push!(δ, δ_r)

and then this constraint

        l1_r1 = @constraint(m, [t in 1:T, ω in 1:Ω, r in 1:1], β[t,ω] ≥ 
                                     sum( δ[t,ω,l,r] for l in 1:L[t,ω] )  

and get this error

BoundsError: attempt to access 9-element Vector{VariableRef} at index [1, 1, 2, 1]

Which I suppose means y[1,1,2,1] is not available.
When I print y I see y[1,1,2,1]is there

VariableRef[δ[1,1,1,1], δ[1,1,2,1], δ[1,1,3,1], δ[1,1,4,1], δ[1,2,1,1], δ[1,2,2,1], δ[1,2,3,1], δ[1,2,4,1], δ[1,2,5,1]]

Can somebody please help what I am missing?

δ is a vector with 9 elements. You can only index it with δ[1] through δ[9].

I think you want instead:

@variable(m, δ[t=1:T, ω=1:Ω, 1:L[t,ω], 1:R])