5

I am new to Julia, and I am trying to define an optimization problem with JuMP. I have a lot of variables (x1,x2,x3....) that I am trying to define using a for loop. I want to have the code:

@variable(m, x1>=0)
@variable(m, x2>=0) ... 

However I wanted to use a for loop so I did not have to define every variable manually.
Here is what I have so far:

m = Model()
for i = 1:2
    @variable(m,string('x',i)>=0)
end 

I know the string('x',i) part is not right but I am not sure how to do this using Julia.

Frames Catherine White
  • 27,368
  • 21
  • 87
  • 137
Cam
  • 421
  • 2
  • 8
  • 18

3 Answers3

5

It looks like you want an array of x variables.

From the JuMP docs, you can make an array by using array syntax in your definition.

@variable(m, x[1:2] >= 0)
@variable(m, y[1:M,1:N] >= 0)
Andrew
  • 1,839
  • 14
  • 25
  • 1
    When I use `@defVar(m, x[1:2] >= 0)` I keep getting an error when I try to solve: `@setObjective(m, Max, 8x1+12x2) @addConstraint(m, 6x1+8x2<=72) status=solve(m)' gives error: `LoadError: Variable not owned by model present in constraints while loading In[22], in expression starting on line 5` any ideas?? @IainDunning @Andrew – Cam Aug 04 '15 at 15:25
  • 2
    Don't use `x1` and `x2`, use `x[1]` and `x[2]`, then it will work. – IainDunning Aug 04 '15 at 16:03
  • Feel free to drop by the julia-opt mailing list if you have questions later! – IainDunning Aug 04 '15 at 18:28
5

You can add indices to your variables using @variable. The following are all valid 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])
Frames Catherine White
  • 27,368
  • 21
  • 87
  • 137
IainDunning
  • 11,546
  • 28
  • 43
0

I'll just add that a 'for' loop in your constraints might look like this:

@constraint(m, [i in 1:2], x[i]>=0)

where [i in 1:2] is your for loop.

Adding to Iain's comment above, better to use x as a vector the to be defining individual variables for it - that way you only have the one decision variable.

This is particularly useful when you want to increase the dimensionality of it: ie x[i,j]

Chris Swan
  • 57
  • 8