Search code examples
juliaoffset

Get the top left index of an OffsetArray


I have a following OffsetArray:

julia> off = OffsetArray(rand(5, 5), -3, -3)
5×5 OffsetArray(::Matrix{Float64}, -2:2, -2:2) with eltype Float64 with indices -2:2×-2:2:
 0.515173  0.861326   0.349478  0.970478  0.255713
 0.862617  0.47006    0.707166  0.938883  0.331716
 0.512007  0.0325946  0.553909  0.569638  0.510056
 0.941383  0.351381   0.35792   0.482246  0.439157
 0.887686  0.413278   0.527105  0.782516  0.976842

I would like to extract programmatically the index of the top left element, in this case that would be (-2, -2).

Right now I'm doing this

topleft = off |> axes |> CartesianIndices |> first |> ind -> ind.I

It looks like an overkill to me, but I couldn't find any other options.

Is there a more direct approach?


Solution

  • I would normally use firstindex:

    julia> firstindex(off, 1)
    -2
    

    where the second argument is a dimension you want to get the first index of.

    To get a (-2, -2) tuple you can write e.g.:

    julia> firstindex.(Ref(off), (1, 2))
    (-2, -2)