How to define JuMP variables using for loop in Julia?
I am new to Julia and I am trying to spot an optimization problem with JuMP . I have a lot of variables ( x1,x2,x3....
) that I am trying to define with a loop for
. I want to have code:
@variable(m, x1>=0)
@variable(m, x2>=0) ...
However, I wanted to use a loop for
, so I didn't have to define each variable manually.
Here's what I have so far:
m = Model()
for i = 1:2
@variable(m,string('x',i)>=0)
end
I know the part string('x',i)
is wrong, but I'm not sure how to do it with Julia.
source to share
Sounds like you want an array of variables x
.
In the JuMP docs, you can create an array using the array syntax in your definition.
@variable(m, x[1:2] >= 0)
@variable(m, y[1:M,1:N] >= 0)
source to share
You can add indices to your variables using @variable
. Everyone works in JuMP:
m = Model()
@variable(m, x[1:2] >= 0)
@variable(m, boringvariable[1:9,1:9,1:9])
@variable(m, 0 <= pixel_intensity[1:255,1:255] <= 1)
@variable(m, bit_pattern[0:8:63], Bin)
N = 5, M = 10
@variable(m, trucks_dispatched[i=1:N,j=1:M] >= 0, Int)
items = [:sock,:sandal,:boot]
max_stock = [:sock => 10, :sandal => 13, :boot => 5]
@variable(m, 0 <= stock_levels[item=items] <= max_stock[item])
source to share