How do I reset a variable value in a loop?

Let’s say I have a model like this:

using JuMP
using CPLEX

model = Model(CPLEX.Optimizer)

for k = 1:3

@variables(model, begin
    sigma
    x[1:3]>=0
        end)

@constraints(model,begin
        sigma == sum(x[i] for i=1:3) + k
        x[1]+x[2]<=100
        x[2]+x[3]<=50
        end)

@objective(model,Max,sigma)

optimize!(model)

end

I get next error:

An object of name sigma is already attached to this model. If this is intended, consider using the anonymous construction syntax, e.g., x = @variable(model, [1:N], …) where the name of the object does not appear inside the macro.

I am not sure what you really want to do, but I assume you like to solve the model three times for different values of parameter k. If so, you could simply put

model = Model(CPLEX.Optimizer)

inside the for-loop.

If you declare the model outside, clearly, in the second iteration of the for-loop the variables and constraints already exist in your model which causes the error message.

2 Likes

Thank you.