Julia: Is there a way to return an iterator of each value of an index?

Viewed 238

Consider m = [1 2 3; 4 5 6; 7 8 9]

for idx in eachindex(m)
  println(idx)
end

I was expecting it to print (1, 1) (2, 1), (3, 1) .... (1, 3), (2, 3), (3, 3) but it prints 1, 2, ..., 9.

What's the most elegant way to loop through all the indices of a multidimensional array?

2 Answers

What about

julia> for i in CartesianIndices(m)
           println(Tuple(i))
       end
(1, 1)
(2, 1)
(3, 1)
(1, 2)
(2, 2)
(3, 2)
(1, 3)
(2, 3)
(3, 3)

(You can access the tuple of subindices of i::CartseianIndex with Tuple(i).)

This is not necessarily elegant but it works:

for i in eachindex(view(m, 1:size(m)[1], 1:size(m)[2]))
       println(i)
end

CartesianIndex(1, 1)
CartesianIndex(2, 1)
CartesianIndex(3, 1)
CartesianIndex(1, 2)
CartesianIndex(2, 2)
CartesianIndex(3, 2)
CartesianIndex(1, 3)
CartesianIndex(2, 3)
CartesianIndex(3, 3)

The reason is that an Array uses fast linear indices (a range 1:length(m)), but not all arrays do, and in particular views don't. Those arrays use Cartesian indices.

Related