Keep dimensionality of slices

The slices are rows internally but they come out as columns.

julia> let x = [1 2 3 4
                5 6 7 8]    
           collect(first(eachslice(x; dims=1)))
       end
4-element Vector{Int64}:
 1
 2
 3
 4

How can I get each slice, retaining their (1,n) shape? (I’m interested in working on arbitrary-dimensional arrays, not just matrices.)

julia> x[1:1,:]
1×4 Matrix{Int64}:
 1  2  3  4
2 Likes

To be more precise, I’m looking for an expression that

  • works for any value of ndims generically. x[1:1, :] works great for matrices but not higher or lower dims
  • produces an iterable collection of these slices, not just the first one

Sounds like you want the selectdim function:

julia> x = reshape(1:24, (2,3,4))
2×3×4 reshape(::UnitRange{Int64}, 2, 3, 4) with eltype Int64:
[:, :, 1] =
 1  3  5
 2  4  6

[:, :, 2] =
 7   9  11
 8  10  12

[:, :, 3] =
 13  15  17
 14  16  18

[:, :, 4] =
 19  21  23
 20  22  24

julia> y = (selectdim(x, 2, i:i) for i in axes(x,2))
Base.Generator{Base.OneTo{Int64}, var"#3#4"}(var"#3#4"(), Base.OneTo(3))

julia> first(y)
2×1×4 view(reshape(::UnitRange{Int64}, 2, 3, 4), :, 1:1, :) with eltype Int64:
[:, :, 1] =
 1
 2

[:, :, 2] =
 7
 8

[:, :, 3] =
 13
 14

[:, :, 4] =
 19
 20

julia> last(y)
2×1×4 view(reshape(::UnitRange{Int64}, 2, 3, 4), :, 3:3, :) with eltype Int64:
[:, :, 1] =
 5
 6

[:, :, 2] =
 11
 12

[:, :, 3] =
 17
 18

[:, :, 4] =
 23
 24

with the obvious generalization:

julia> sliceiter(x, m) = (selectdim(x, m, i:i) for i in axes(x,m))
3 Likes