Search code examples
while-loopjuliajulia-jump

"Not defined variable" in a 'while loop' in Julia


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?


Solution

  • 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