physics.dev

Array indexing tips in Julia

https://discourse.julialang.org/t/discussion-on-why-i-no-longer-recommend-julia-by-yuri-vishnevsky/81151/88

These are a collection of useful methods of iterating through arrays in Julia. Much of this is already in the manual or other documentation online, but this is sort of a cheatsheet for my own purposes. Hopefully this helps you.

One of the confusing aspects for me when I was starting in Julia how it handles arbitrary array interation. Coming from Fortran-land I was pleasantly surprised to see

do j = 1, N
    do i = 1, M
        A(i,j) = A(i,j) + 1
    end do
end do

Using eachindex

CartesianIndices

for I in CartesianIndices(A)
    i,j = Tuple(I)
    @show i, j
end

OffsetArrays

using OffsetArrays

B = OffsetArray(reshape(1:9, 3, 3), -3, -2)
3×3 OffsetArray(reshape(::UnitRange{Int64}, 3, 3), -2:0, -1:1) with eltype Int64 with indices -2:0×-1:1:
 1  4  7
 2  5  8
 3  6  9

Loop along the diagonal of the OffsetArray

for (i, j) in zip(axes(B)...)
    @show i, j
end
(i, j) = (-2, -1)
(i, j) = (-1, 0)
(i, j) = (0, 1)