How to add repeated elements to a vector without looping?

3 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Bruno Luong
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)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Productos


Versión

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by