Logical indexing and sums
2 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Kelly Kearney
on 28 May 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))
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!