MATLAB: How to accumulate to a vector-indexed array

MATLABvectorization

I want to vectorize something in the following form:
for jk = 1:njk
k = K(jk);
L(k) = L(k) + R(jk);
end
where the range of the k values is less than that of the jk values, so some k values occur for multiple values of jk. The obvious "solution" would be
L(K(1:njk)) = L(K(1:njk)) + R(1:njk);
but this gives wrong results, either because (1) L(K(1:njk)) occurs on both the LH and RH sides, or because (2) vectored indexing cannot be used on the LH side (I'm not sure whether (1) or (2) is the reason). A possible approach might be if there is something equivalent to the "+=" operator in C, which would allow
L(K(1:njk)) += R(1:njk);
Also the vectors happen to be large (>10000 elements) so anything that involves creating an intermediate matrix ix not likely to be practical.
Is there a way to vectorize this?

Best Answer

I don't see anything wrong with the syntax you proposed...
L = rand(100,1);
R = rand(100,1);
K = randperm(100);
njk = 5;
% The loop method
L1 = L;
for jk = 1:njk
k = K(jk);
L1(k) = L1(k) + R(jk);
end
% The vectorized method
L2 = L;
L2(K(1:njk)) = L2(K(1:njk)) + R(1:njk);
% Yup, they're the same...
isequal(L1, L2)
Related Question