Error in NL expression UndefVarError: exp1 not defined

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