In short I want to index into a matrix and add to each row.
F = zeros(Int64,5)
idx = [2,5,2] # same row repeated several times
fi = [5,2,7]
F[idx] += fi
Desired:
julia> F
5-element Array{Int64,1}:
0
12
0
0
2
actual:
F
5-element Array{Int64,1}:
0
7
0
0
2
When there is repetition, I would just write a loop:
for (i, f) in zip(idx, fi)
F[i] += f
end
(not that sorting by idx
may improve performance)
1 Like
You could also use
view(F, idx) .+= fi
But the way @Tamas_Papp recommended might be more explicit and legible.
2 Likes
Just for fun, you can also try broadcasting:
((i,f) -> F[i]+=f).(idx,fi)
Performance-wise, a loop will always be faster, though.
1 Like