How to add repeated elements to a vector without looping?
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Alexander Winter
el 27 de Jul. de 2020
Comentada: Alexander Winter
el 27 de Jul. de 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 comentario
Stephen23
el 27 de Jul. de 2020
Your first attempt is described here:
This blog describes the three ways to perform accumulation like you want (loop, sparse array, and accumarray):
Respuesta aceptada
Bruno Luong
el 27 de Jul. de 2020
Editada: Bruno Luong
el 27 de Jul. de 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
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!