3
votes

I am trying to do a sensitivity analysis in Julia using JuMP. Here is my code: using JuMP, Plots, Gurobi

m=Model(with_optimizer(Gurobi.Optimizer))


@variable(m, x>=0)
@variable(m, y>=0)
@variable(m, k>=0)

k = 0

while k<=1
    φ(x,y,k)=3*x+k*y

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

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

    pl=optimize!(m)
    k=k+0.2
end

The problem is that I get an error:

UndefVarError: k not defined

What am I missing?

2
alternatively, you can use the Clp solver instead of the Gurobi solverYorgos

2 Answers

5
votes
julia> k =0
0

julia> while k<10
           k=k+1
       end
ERROR: UndefVarError: k not defined
Stacktrace:
 [1] top-level scope at ./REPL[11]:2

In julia if we are operating with loops the variables we initialise outside our loop can not be directly accessed within a loop on default. To do that we have to set those variable on to global use as on default they are considered to be local

julia> while k<10
         global  k=k+1
       end

Now this works fine

1
votes

Disclaimer: This is an alternative solution, that it was suggested by a member of Julia Discorse

In a discussion at Julia Discourse, it is suggested to wrap the code in a function in order to increase speed and to avoid the global issue:

function run_code()
    model = Model(with_optimizer(Gurobi.Optimizer))
    @variable(model, x >= 0)
    @variable(model, y >= 0)
    @constraint(model, 2x - 4 >= 0)

    k = 0

    while k <= 1
        @objective(model, Max, 3x + k * y)
        optimize!(model)
        k = k + 0.2
    end
end
run_code()