Effacer les filtres
Effacer les filtres

Logical indexing and sums

1 vue (au cours des 30 derniers jours)
Fabs
Fabs le 28 Mai 2014
Commenté : Fabs le 28 Mai 2014
Hi,
first of: I know I can do what I want in a loop. However, I'm performing something similar to my problem thousands of times on much bigger matrices, so if there is a solution with logical indexing and without any loop, that would be preferred.
OK, let's assume I have a matrix
a=[23 45; 65 13];
and I want the values of a to written to new positions defined in
b=[2 4;1 2]; % matrix with new positions for values in a
Obviously b is referencing one position (2) twice and
c=nan(size(a));
c(b) = a % matrix with values from a at positions from b
results in
c = [65 13; NaN 45]; % location two is written twice and only the second value shows up
Is there a way to get matrix c to be
c = [65 36; NaN 45]; % location 2 is sum of 13+23
?
Thanks y'all, I appreciate your help, F

Réponse acceptée

Kelly Kearney
Kelly Kearney le 28 Mai 2014
Meet accumarray, my favorite powerful-and-useful-but-terribly-named function (and lately, seemingly the answer to every question I respond to):
c = reshape(accumarray(b(:), a(:), [numel(a) 1], @sum, NaN), size(a))
  1 commentaire
Fabs
Fabs le 28 Mai 2014
That's what I call a quick response! Thank you very much!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical 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!

Translated by