Convert between indexing formats

Julia’s eachindex function makes it really easy to iterate over multidimensional arrays. Sometimes, however, I need access to not just the sequential index as described in memory (an Int) but also the individual dimension indices that are common of typical (e.g. C-like) for loops (e.g. (ix, iy, iz)).

Is there an easy way to go back and forth between index formats given a particular array? For example, something like

A = rand(2,3)

for i in eachindex(A)
   index_tuple = convert_index(A,i) # would give me (1,1), (2,1), (1,2), ...
end

(I see in the help there’s a way to get a CartesianIndex using a view, but then I lose my original index)

Maybe:

CartesianIndices(A)[i]
1 Like

Aha! You’re right!

Turns out this is in the manual too: Multi-dimensional Arrays · The Julia Language

Thank you!

1 Like