How to add repeated elements to a vector without looping?

3 views (last 30 days)
I have the following code:
a = zeros(1, 4);
a([1 2 4 3 2 1 1]) = a([1 2 4 3 2 1 1]) + [1 1 1 1 1 1 1];
This gives a == [1 1 1 1]. What I would want is a similar operation that gives a = [3 2 1 1], basically add 1 to each element of the selection, everytime it is in the selection. This would be easy to do in a for loop:
a = zeros(1, 4);
selection = [1 2 4 3 2 1 1];
addVec = [1 1 1 1 1 1 1];
for i = 1:length(selection)
a(selection(i)) = a(selection(i)) + addVec(i);
end
But this is not efficient. I'm looking for a vectorized version of this.
Thank you

Accepted Answer

Bruno Luong
Bruno Luong on 27 Jul 2020
Edited: Bruno Luong on 27 Jul 2020
accumarray([1 2 4 3 2 1 1]', 1)'
Put [1 1 1 1 1 1 1]' as second argument if the values to accumulate are not uniform.
(important the quotes, especially the inner one)
ans =
3 2 1 1

More Answers (0)

Products


Release

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!