Unconsistent range object behavior

New to Julia migrating my code from Octave I encountered a very strange error. Same piece of code works fine when sequential

julia> include(“test.jl”)
a[y,x][8 9 6 6 4; 4 7 2 5 3; 5 6 9 2 1; 5 3 4 3 3; 7 8 6 2 3]
2:6 3:7
r 4.859504132231405 c 3.628099173553719
2:6 3:7
r 4.859504132231405 c 3.628099173553719

but strange enough doesn’t work anymore in a loop, the range object is not recognized.

julia> include(“test.jl”)
a[y,x][4 5 3 1 9; 8 9 9 4 8; 1 7 1 5 3; 7 3 7 3 4; 1 4 1 6 7]
ERROR: LoadError: UndefVarError: x not defined
Stacktrace:
[1] top-level scope at /home/manu/code/julia/test.jl:15 [inlined]
[2] top-level scope at ./none:0
[3] include at ./boot.jl:317 [inlined]
[4] include_relative(::Module, ::String) at ./loading.jl:1041
[5] include(::Module, ::String) at ./sysimg.jl:29
[6] include(::String) at ./client.jl:388
[7] top-level scope at none:0
in expression starting at /home/manu/code/julia/test.jl:14

See below the code.
Uncomment the for loop and you get an error
`
function cog(x,y,J)
I=J[y,x]
sI = sum(I)
c = sum(x.*vec(sum(I,dims=1)))/sI
r = sum(y.*vec(sum(I,dims=2)))/sI
return r,c
end

a=rand(1:9,12,8)
r,c,d=5,4,2
x,y=c-d:c+d,r-d:r+d
println(“a[y,x]”,a[y,x])

#for i=1:2
println(x," ",y)
r,c=cog(x,y,a)
println("r “,r,” c “,c)
c=round(Int,c)
r=round(Int,r)
x,y=c-d:c+d,r-d:r+d
println(x,” ",y)
r,c=cog(x,y,a)
println("r “,r,” c ",c)
#end`

Loops in Julia create their own local scope. If you want to access a global variable you have to either declare it global in your loop or wrap your code in a function. There’s loads of threads on this on here if you search for the error.

Thanks for you rapid answer. This variable scope in loops is surprisingly new for me… I should RTFM :slight_smile:
Pb solved

1 Like

Also, please quote your code in posts: PSA: how to quote code with backticks

1 Like