1
votes

I have a piece of code that works outside a loop, but fails inside a loop.

See:

julia> margin = 1
1

julia> rat = [-0.3 ; -0.8]
2-element Array{Float64,1}:
 -0.3
 -0.8

julia> beta = 0
0

julia> for q=1:2
           if rat[q] - margin > beta
               beta = rat[q] - margin
           end
       end
ERROR: UndefVarError: beta not defined
Stacktrace:
 [1] top-level scope at ./REPL[803]:2 [inlined]
 [2] top-level scope at ./none:0

julia> q=1
1

julia> if rat[q] - margin > beta
           beta = rat[q] - margin
       end

julia> q=2
2

julia> if rat[q] - margin > beta
           beta = rat[q] - margin
       end

Can someone explain this error ("ERROR: UndefVarError: beta not defined")?

(I have Julia v"1.1.1", on Mac OSX)

2

2 Answers

1
votes

Adding global before the variable works for me:

for q=1:2
  if (rat[q] - margin) > beta
    global beta = rat[q] - margin
  end
end
2
votes

Julia has a very particular way of dealing with global scope. The rules of variable scope can be read here: https://docs.julialang.org/en/v1/manual/variables-and-scoping/#Global-Scope-1 . New scope rules were introduced in Julia-1.0, and they have been highly controversial in the community, particularly because of the unintuitive behaviour of for loops in global scope. For the extremely interested, there's a discussion of pros and cons here: