Indexing a const array with a JuMP variable

Please read Please read: make it easier to help you, and provide a minimal working example.

Note that the following will not work:

model = Model()
@variable(model, x)
data = [1, 2, 3]
@objective(model, data[x])    # Can't index with x.

Instead, you should do something like the following:

model = Model()
data = [1, 2, 3]
@variable(model, x[1:length(data)], Bin)
@constraint(model, sum(x) == 1)
@objective(model, sum(x[i] * data[i] for i in 1:length(data))

Here, the binary variables x choose each element out of data, and there is a constraint that you can only choose one element.

3 Likes