# Fastest way to broadcast reductions of SubArrays

**URL:** <https://discourse.julialang.org/t/fastest-way-to-broadcast-reductions-of-subarrays/45913>\
**Category:** New to Julia\
**Tags:** question, broadcast, array\
**Created:** [September 1, 2020, 6:38pm UTC](https://discourse.julialang.org/t/fastest-way-to-broadcast-reductions-of-subarrays/45913 "2020-09-01T18:38:30Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![mkarikom](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mkarikom/32/7096_2.png) [@mkarikom](https://discourse.julialang.org/u/mkarikom)\
**Post date:** [September 1, 2020, 6:38pm UTC](https://discourse.julialang.org/t/fastest-way-to-broadcast-reductions-of-subarrays/45913/1 "2020-09-01T18:38:30Z")

</div>

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`:

```julia
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**?

---

<div class="post-metadata">

**Author:** ![evad](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/evad/32/15756_2.png) [@evad](https://discourse.julialang.org/u/evad)\
**Post date:** [September 3, 2020, 7:51am UTC](https://discourse.julialang.org/t/fastest-way-to-broadcast-reductions-of-subarrays/45913/2 "2020-09-03T07:51:19Z")

</div>

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

```julia
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

```
