How do I stop accumarray adding rows for non-existent values of the index column?
Afficher commentaires plus anciens
I want to sum the values in one column of an array based on values in another (index) column. What I get is a row for all values up to the maximum in the index column. For example,
a = [2 1.1; 2 1.2; 4 1.3; 4 1.4]
b = accumarray(a(:,1),a(:,2))
doesn't give what I expect: b =
2.3000 % i.e. sum of values for which the index is 2
2.7000 % i.e. sum of values for which the index is 4
but
b =
0
2.3000
0
2.7000
How do I suppress the rows where the index value doesn't exist? This is a trivial example, but in what I'm trying to do the index values are in the range 195001 to 202012 so I get a large number of zeros. All help gratefully received...
Réponse acceptée
Plus de réponses (1)
a = [2 1.1; 2 1.2; 4 1.3; 4 1.4];
[~, ~, group] = unique(a(:, 1));
b = accumarray(group, a(:,2))
Catégories
En savoir plus sur Matrices and Arrays dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!