Let's say I have two (large) vectors a=[0 0 0 0 0]
and b=[1 2 3 4 5]
of the same size and one index vector ind=[1 5 2 1]
with values in {1,...,length(a)}. I would like to compute
for k = 1:length(ind)
a(ind(k)) = a(ind(k)) + b(ind(k));
end
% a = [2 2 0 0 5]
That is, I want to add those entries of b
declared in ind
to a
including multiplicity.
a(ind)=a(ind)+b(ind);
% a = [1 2 0 0 5]
is much faster, of course, but ignores indices which appear multiple times.
How can I speed up the above code?