Bounds error while iterating over for loop

I am trying to run a for loop by iterating over aij where aij is of type Vector{CartesianIndex{2}} (alias for Array{CartesianIndex{2}, 1}).

The code is:

for (x, y) in zip(aij)
xout = find(U[x, :])
yout = find(U[y, :])
comm = intersect(xout, yout)
nc = size(comm, 1)
for i = 1:nc
for j = (i+1):nc
w = comm[i]
v = comm[j]
if NA[w, v] == 1
W[x, y] += 1
W[x, w] += 1
W[x, v] += 1
W[y, w] += 1
W[y, v] += 1
W[w, v] += 1
end
end
end
end

I get an error like:

BoundsError: attempt to access Tuple{CartesianIndex{2}} at index [2]

Stacktrace:
[1] indexed_iterate(t::Tuple{CartesianIndex{2}}, i::Int64, state::Int64)
@ Base .\tuple.jl:88
[2] top-level scope
@ .\In[12]:1
[3] eval
@ .\boot.jl:368 [inlined]
[4] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
@ Base .\loading.jl:1428

julia> a = CartesianIndex(3,4)
CartesianIndex(3, 4)

julia> a[2]
4

julia> b = (a,)
(CartesianIndex(3, 4),)

julia> b[2]
ERROR: BoundsError: attempt to access Tuple{CartesianIndex{2}} at index [2]
Stacktrace:
 [1] getindex(t::Tuple, i::Int64)

julia> typeof(a)
CartesianIndex{2}

Welcome! Please add a triple backtick fence around your code to make it legible (Please read: make it easier to help you).

Bounds error means you are indexing outside the size of a list.

2 Likes

You probably want

for (x, y) in Tuple.(aij)

here.

zip is for attaching elements of different collections together. That would be necessary in languages where the indices have to be kept in separate arrays by themselves.

Since Julia has CartesianIndex type to store the indices together in a single object, aij doesn’t need to be zipped. What you need is to instead turn it into a Tuple so it can be separated out into x and y here. The above is one way to do it, but the following:

for a in aij
  x, y = Tuple(a)

maybe a bit more effiient in case aij contains a lot of values.

(Using either of these instead of for (x, y) in zip(aij) would get rid of the bounds error issue as well.)