# Add rows from one matrix to another by index

**URL:** <https://discourse.julialang.org/t/add-rows-from-one-matrix-to-another-by-index/29293>\
**Category:** New to Julia\
**Created:** [September 29, 2019, 1:37pm UTC](https://discourse.julialang.org/t/add-rows-from-one-matrix-to-another-by-index/29293 "2019-09-29T13:37:55Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Elmer\_Cusipuma](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/elmer_cusipuma/32/11958_2.png) [@Elmer\_Cusipuma](https://discourse.julialang.org/u/Elmer_Cusipuma)\
**Post date:** [September 29, 2019, 1:37pm UTC](https://discourse.julialang.org/t/add-rows-from-one-matrix-to-another-by-index/29293/1 "2019-09-29T13:37:55Z")

</div>

In short I want to index into a matrix and add to each row.

```julia
F = zeros(Int64,5)
idx = [2,5,2] # same row repeated several times
fi = [5,2,7]
F[idx] += fi

```

Desired:

```julia
julia> F
5-element Array{Int64,1}:
  0
 12
  0
  0
  2

```

actual:

```julia
 F
5-element Array{Int64,1}:
 0
 7
 0
 0
 2

```

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [September 29, 2019, 1:41pm UTC](https://discourse.julialang.org/t/add-rows-from-one-matrix-to-another-by-index/29293/2 "2019-09-29T13:41:40Z")

</div>

When there is repetition, I would just write a loop:

```julia
for (i, f) in zip(idx, fi)
    F[i] += f
end

```

(not that sorting by `idx` may improve performance)

---

<div class="post-metadata">

**Author:** ![simeonschaub](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/simeonschaub/32/216566_2.png) [@simeonschaub](https://discourse.julialang.org/u/simeonschaub)\
**Post date:** [September 29, 2019, 6:59pm UTC](https://discourse.julialang.org/t/add-rows-from-one-matrix-to-another-by-index/29293/3 "2019-09-29T18:59:57Z")

</div>

You could also use

```julia
view(F, idx) .+= fi

```

But the way @Tamas_Papp recommended might be more explicit and legible.

---

<div class="post-metadata">

**Author:** ![Seif\_Shebl](https://avatars.discourse-cdn.com/v4/letter/s/eada6e/32.png) [@Seif\_Shebl](https://discourse.julialang.org/u/Seif_Shebl)\
**Post date:** [September 29, 2019, 8:13pm UTC](https://discourse.julialang.org/t/add-rows-from-one-matrix-to-another-by-index/29293/4 "2019-09-29T20:13:45Z")

</div>

Just for fun, you can also try broadcasting:

```julia
((i,f) -> F[i]+=f).(idx,fi)

```

Performance-wise, a loop will always be faster, though.
