Logical indexing and sums
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
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))
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices 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!