Cumbersome array reshaping for broadcasting, unlike numpy

+1 for adding adddims to Base. the accepted solution of indexing with [CartesianIndex()] is not very intuitive.

1 Like

I thought newaxis was super weird and unnatural when I learned it in NumPy. I would probably feel the same if there was a similar magical name in Julia. In contrast I find useful to learn that [CartesianIndex()] works for this: it drives home some aspects of indexing that are hard to grasp otherwise, and more widely useful than this newaxis special case.

So I would prefer to have [CartesianIndex()] documented as a an idomatic example. But I don’t have much need for it, I can imagine people who do want something “nicer”…

1 Like

Some time ago I prepared this PR to add a method to Base called insertdims

julia> a = [1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> b = insertdims(a, dims=(1,3))
1×2×2×1 Array{Int64, 4}:
[:, :, 1, 1] =
 1  3

[:, :, 2, 1] =
 2  4

julia> b[1,1,1,1] = 5; a
2×2 Matrix{Int64}:
 5  2
 3  4

julia> b = insertdims(a, dims=(1,1))
1×1×2×2 Array{Int64, 4}:
[:, :, 1, 1] =
 5

[:, :, 2, 1] =
 3

[:, :, 1, 2] =
 2

[:, :, 2, 2] =
 4

julia> b = insertdims(a, dims=(1,2))
1×2×1×2 Array{Int64, 4}:
[:, :, 1, 1] =
 5  3

[:, :, 1, 2] =
 2  4
2 Likes

and it’s merged now :slight_smile:

1 Like

We changed the semantics though.

Now dims indicates where the final singleton dimensions are going to be from perspective of the final result

 julia> x = [1 2 3; 4 5 6] 
 2×3 Matrix{Int64}: 
  1  2  3 
  4  5  6 
  
 julia> insertdims(x, dims=3) 
 2×3×1 Array{Int64, 3}: 
 [:, :, 1] = 
  1  2  3 
  4  5  6 
  
 julia> insertdims(x, dims=(1,2,5)) == reshape(x, 1, 1, 2, 3, 1) 
 true 
  
 julia> dropdims(insertdims(x, dims=(1,2,5)), dims=(1,2,5)) 
 2×3 Matrix{Int64}: 
  1  2  3 
  4  5  6 
9 Likes