Broadcasting on the middle dimension of a 3D array

Viewed 144

In Python I can have an numpy array a with dimensions (2, 3, 2) and b with (3) and do

c = a[:, :, :] + b[None, :, None]

I did not manage to figure out how to do this with Julia broadcast, because I do not know how to select the middle dimension.

c = broadcast(+, a, b)

What is the proper way to do this?

1 Answers
a .+ b'

For example

julia> a = rand(2,3,2)
2×3×2 Array{Float64, 3}:
[:, :, 1] =
 0.690245  0.358837   0.240053
 0.206133  0.0406269  0.985161

[:, :, 2] =
 0.207407  0.602692  0.483698
 0.625693  0.236401  0.306893

julia> b = rand(3)
3-element Vector{Float64}:
 0.1824121021951648
 0.33153839873473867
 0.024984235771881913

julia> a .+ b'
2×3×2 Array{Float64, 3}:
[:, :, 1] =
 0.872657  0.690375  0.265037
 0.388545  0.372165  1.01015

[:, :, 2] =
 0.38982   0.93423  0.508682
 0.808105  0.56794  0.331878

To elaborate, vectors in Julia are row vectors by default; transpose to a column vector to broadcast over the second dimension.

Related