Save objective values in an optimization loop

Hello, here is my code

using JuMP, Plots, Gurobi

m=Model(with_optimizer(Gurobi.Optimizer))

@variable(m, x>=0)

@variable(m, y>=0)

k=0

obj_val=true

while k<=1

    φ(x,y)=3*x+k*y

    @objective(m, Max, φ(x,y))

    @constraint(m, 2*x-4>=0)

    @constraint(m, y-0.5*x>=0)

    

    optimize!(m)

    global k=k+0.2

    global obj_val = [objective_value(m)]

end

I want to save the objective value of each iteration, but i don’t know how to do it.

1 Like

Use a vector obj_val = Float64[] to store the values, and use push! to add elements to the vector:

using JuMP, Plots, Gurobi

function run_code()
    model = Model(with_optimizer(Gurobi.Optimizer))
    @variable(model, x >= 0)
    @variable(model, y >= 0)
    @constraint(model, 2x - 4 >= 0)
    @constraint(model, y - 0.5*x >= 0)
    k = 0
    obj_val = Float64[]
    while k <= 1
        @objective(model, Max, 3x + k * y)
        optimize!(model)
        k = k + 0.2
        push!(obj_val, objective_value(model))
    end
    return obj_val
end
run_code()

You should also read Performance Tips · The Julia Language.
If you wrap your code in a function, it will run faster, and you don’t have the global k issues.

1 Like

very nice solution… i wasn’t aware neither of that procedure nor the push! command