Broadcasting getindex for a range

Given vv is a Vector{Vector} shouldn’t broadcasting to get a range getindex.(vv, UnitRange) work ?

Let’s say I have:

ar = [[1,2,3], [4,5,6], [7,8,9]]

getindex.(ar, 2:3)
ERROR: DimensionMismatch("arrays could not be broadcast to a common size; got a dimension with lengths 3 and 2")
Stacktrace:
 [1] _bcs1
   @ ./broadcast.jl:516 [inlined]
 [2] _bcs
   @ ./broadcast.jl:510 [inlined]
 [3] broadcast_shape
   @ ./broadcast.jl:504 [inlined]
 [4] combine_axes
   @ ./broadcast.jl:499 [inlined]
 [5] instantiate
   @ ./broadcast.jl:281 [inlined]
 [6] materialize(bc::Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{1}, Nothing, typeof(getindex), Tuple{Vector{Vector{Int64}}, UnitRange{Int64}}})
   @ Base.Broadcast ./broadcast.jl:860
 [7] top-level scope
   @ REPL[41]:1

#also tried
getindex.(ar, [2,3])
ERROR: DimensionMismatch("arrays could not be broadcast to a common size; got a dimension with lengths 3 and 2")
Stacktrace:
 [1] _bcs1
   @ ./broadcast.jl:516 [inlined]
 [2] _bcs
   @ ./broadcast.jl:510 [inlined]
 [3] broadcast_shape
   @ ./broadcast.jl:504 [inlined]
 [4] combine_axes
   @ ./broadcast.jl:499 [inlined]
 [5] instantiate
   @ ./broadcast.jl:281 [inlined]
 [6] materialize(bc::Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{1}, Nothing, typeof(getindex), Tuple{Vector{Vector{Int64}}, Vector{Int64}}})
   @ Base.Broadcast ./broadcast.jl:860
 [7] top-level scope
   @ REPL[47]:1

#although this works
ar .|> x -> getindex(x,2:3)
3-element Vector{Vector{Int64}}:
 [2, 3]
 [5, 6]
 [8, 9]

#and ofc this works but not what needed
getindex(ar, 2:3)
2-element Vector{Vector{Int64}}:
 [4, 5, 6]
 [7, 8, 9]

According to this Broadcast Array Indexing · Issue #19169 · JuliaLang/julia · GitHub I would assume that it used to be possible but now not (maybe bug) ?

tested on julia version 1.7.2

Broadcast is trying to match the shape of ar (length 3) with 2:3 (length 2). It might become more obvious how it’s working with the range 1:3 instead:

julia> ar = [[1,2,3], [4,5,6], [7,8,9]];

julia> getindex.(ar, 1:3)
3-element Vector{Int64}:
 1
 5
 9

In this case, you’re matching the elements of 1:3 with the three elements of ar. What you’re after, though, is to repeat the 2-element range 2:3 three times to match up with the shape of ar. To do this, make the range an element itself! You can really put it into any 1-element container:

julia> getindex.(ar, Ref(2:3))
3-element Vector{Vector{Int64}}:
 [2, 3]
 [5, 6]
 [8, 9]
3 Likes