How to add repeated elements to a vector without looping?
3 views (last 30 days)
Show older comments
Alexander Winter
on 27 Jul 2020
Commented: Alexander Winter
on 27 Jul 2020
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
1 Comment
Stephen23
on 27 Jul 2020
Your first attempt is described here:
This blog describes the three ways to perform accumulation like you want (loop, sparse array, and accumarray):
Accepted Answer
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)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!