Mix of index-based and slice based indexing across different dimensions

Given an k-dimensional array, e.g.

A = LinearIndices((2,2,2))
2×2×2 LinearIndices{3, Tuple{Base.OneTo{Int64}, Base.OneTo{Int64}, Base.OneTo{Int64}}}:
[:, :, 1] =
 1  3
 2  4

[:, :, 2] =
 5  7
 6  8

and a list of row-column indices, e.g. idxs=[(1,2), (1,1)], how do I efficiently select the corresponding rows and columns, while slicing in the remaining dimensions?

In the given example, the outcome should be

3 7
1 5

i.e. taking the elements (1,2,1), (1,2,2), (1,1,1), and (1,1,2).

We can ignore the exact shape of the output for now, as that can be fixed using reshape.

Edit: The command reduce(hcat, (x -> @view A[x..., :]).(idxs)) solves the problem in principle, but maybe there’s a way to get one single view, instead of a copy.

Make those idxs an array of CartesianIndex:

julia> idxs = CartesianIndex.([(1,2), (1,1)])
2-element Vector{CartesianIndex{2}}:
 CartesianIndex(1, 2)
 CartesianIndex(1, 1)

julia> A[idxs, :]
2×2 Matrix{Int64}:
 3  7
 1  5
3 Likes