Filter löschen
Filter löschen

Logical indexing and sums

1 Ansicht (letzte 30 Tage)
Fabs
Fabs am 28 Mai 2014
Kommentiert: Fabs am 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

Akzeptierte Antwort

Kelly Kearney
Kelly Kearney am 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 Kommentar
Fabs
Fabs am 28 Mai 2014
That's what I call a quick response! Thank you very much!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by