Using accumarray to do sum with duplicate indicies

4 vues (au cours des 30 derniers jours)
Paul Chesler
Paul Chesler le 24 Sep 2017
Commenté : Paul Chesler le 24 Sep 2017
Hi folks, Let f and A be arrays with size(f) = [N,1] and size(A) = [M,1] with N > M. Let J be a list of indices for f with size(J) = size(A). I wish to compute the for loop
for k = 1:M,
f(J(k)) = f(J(k)) + A(k);
end
However, due to time constraints I need to do this computation without the for loop. If all the indices J were unique I would simply say f(J) = f(J) + A. However, I will need to consider the case where there are many duplicate indices in J. I suspect this can be accomplished with accumarray, but its not clear to me how to do this. Does anybody have any suggestions?
Thanks, Paul
  1 commentaire
the cyclist
the cyclist le 24 Sep 2017
It would be helpful to include a small example that is general enough for your use case, showing what the input and expected output are.

Connectez-vous pour commenter.

Réponse acceptée

Matt J
Matt J le 24 Sep 2017
Modifié(e) : Matt J le 24 Sep 2017
Yes, it is a direct application of accumarray,
f=f+accumarray(J,A,size(f));
  1 commentaire
Paul Chesler
Paul Chesler le 24 Sep 2017
Thank you Matt! That did it perfectly.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by