Error in NL expression UndefVarError: exp1 not defined

Hi All,
is there a way to use NL expression from nested loops? outside nested loops
example code

using JuMP
model=Model()
@variable(model,x)

xy=1
for z in 1:10
	if z==1
		if xy>=1
			@NLexpression(model,exp1,x^3)
			@NLexpression(model,exp2,x^2)
		end
	elseif z==2	
		if xy>=1
			@NLexpression(model,exp3,x^3)
			@NLexpression(model,exp4,x^2)
		end
	elseif z==3	
		if xy>=1
			@NLexpression(model,exp5,x^3)
			@NLexpression(model,exp6,x^2)
		end
	end
end	
@NLobjective(model,Min,exp1+exp2+exp3+exp4+exp5+exp6)
optimize!
error received
ERROR: UndefVarError: exp1 not defined
any idea how to resolve it. it is big code and I cant
1 Like

This is not a JuMP problem, but a regular Julia problem.

It’s usually a sign that you should structure your code differently. (e.g., What happens if xy < 1 when z==1? What are exp1 and exp2 then? Why loop over z if you know what to do for various z? Why not just write explicitly?)

julia> x = 2
2

julia> xy=1
1

julia> for z in 1:10
               if z==1
                       if xy>=1
                               exp1 = x^3
                               exp2 = x^2
                       end
               elseif z==2        
                       if xy>=1
                               exp3 = x^3
                               exp4 = x^2
                       end
               elseif z==3        
                       if xy>=1
                               exp5 = x^3
                               exp6 = x^2
                       end
               end
       end

julia> exp1+exp2+exp3+exp4+exp5+exp6
ERROR: UndefVarError: exp1 not defined
Stacktrace:
 [1] top-level scope
   @ REPL[22]:100

One solution is to give variables a default value:

julia> x = 2
2

julia> xy=1
1

julia> exp1 = exp2 = exp3 = exp4 = exp5 = exp6 = 0
0

julia> for z in 1:10
           if z==1
               if xy>=1
                   exp1 = x^3
                   exp2 = x^2
               end
           elseif z==2        
               if xy>=1
                   exp3 = x^3
                   exp4 = x^2
               end
           elseif z==3        
               if xy>=1
                   exp5 = x^3
                   exp6 = x^2
               end
           end
       end

julia> exp1+exp2+exp3+exp4+exp5+exp6
36
2 Likes

Thanks it worked

1 Like