Fastest way to broadcast reductions of SubArrays

I have an array arr whose subarrays correspond to the column-groups given in colinds.

Below is an example of division that does what I want without creating any subarrays or broadcasting. The desired result is given by arr ./ res:

arr = [1 2 3 4 5;6 7 8 9 10]
res = zeros(size(arr))
colinds = (1:2,3:5)
for i in colinds
   s = sum(arr[:,i],dims=2)'
   srep = repeat(s,length(i))'
   res[:,i] .= srep
end
@test all(arr ./ res .== [1 2 3 4 5;6 7 8 9 10] ./ [3 3 12 12 12;13 13 27 27 27])

I don’t think the code above is optimized.
How can I do this by broadcasting the column-wise sum (or other reduction) to each subarray ?

1 Like

Hi I tried the following, not more efficient but shorter:

arr = convert(Array{Float64,2}, arr)

for i in colind
       subarr = arr[:,i] ./ sum(arr[:,i],dims=2)
       for (k,v) in enumerate(i)
           arr[:,v]=subarr[:,k]
       end
end