How to add repeated elements to a vector without looping?
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Alexander Winter
le 27 Juil 2020
Commenté : Alexander Winter
le 27 Juil 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 commentaire
Stephen23
le 27 Juil 2020
Your first attempt is described here:
This blog describes the three ways to perform accumulation like you want (loop, sparse array, and accumarray):
Réponse acceptée
Bruno Luong
le 27 Juil 2020
Modifié(e) : Bruno Luong
le 27 Juil 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
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!