3

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 Answers 2

4

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:

Sign up to request clarification or add additional context in comments.

1 Comment

Indeed, I was perplexed. Thank you.
2

Adding global before the variable works for me:

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

1 Comment

thank you. For cross-reference I was about to link to this answer: stackoverflow.com/a/51910135/190791

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.