Pick rows from array (ndims not known in advance)

I want to pick out some rows (in the vector vv, see below) from an array x. The ndims(x) is determined at run time.

So far, I use the approach illustrated below. Is there a better way?

x1 = [11 12 13;
      21 22 23;
      31 32 33]
x  = cat(x1,x1.+100,dims=3)    #my array, happens to be a 3D array this time

vv = [1,3]       #rows to pick out

vc    = Any[Colon() for i=1:ndims(x)]
vc[1] = vv           #the rows to pick out
y     = x[vc...]      #the result

Two ways:

julia> yv = selectdim(x, 1, vv)
2×3×2 view(::Array{Int64, 3}, [1, 3], :, :) with eltype Int64:
[:, :, 1] =
 11  12  13
 31  32  33

[:, :, 2] =
 111  112  113
 131  132  133

julia> using EllipsisNotation

julia> yv == x[vv, ..]
true
2 Likes

There is a Base function selectdim which I think does precisely that.

Thanks. This works well.

I (wrongly) believed that selectdim(A, d::Integer, i) required i to be a single index.

The documentation says
Return a view of all the data of A where the index for dimension d equals i.

I guess that could be interpreted either way. In case I (or someone else here) come up with a better formulation, I would be happy to make a PR.

Maybe something as simple as adding selectdim(A, 2, 3:4) as another example, below the selectdim(A, 2, 3) it has now?

Thanks for the suggestion, It’s now done: https://github.com/JuliaLang/julia/pull/40456