Sum elements in the first column according to repeated values in a second column
10 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Hi, I have a two columns matrix, where the elements of the second column are repeated (here below in my example, 55, 98 and 17 are repeated several times).
I would like to sum the elements of the first column, which have (in common) the same element of the second column. Here an example... any fast way to do it?
% Input
A = [ 4 55
3 55
7 55
1 55
9 98
1 98
2 98
8 98
0 98
1 98
6 17
3 17
0 17
4 17]
% desired output
B = [15 55
21 98
13 17];
where, for example, the value 15 in B(1,1) is given by 4 + 3 + 7 + 1 = 15
0 Commenti
Risposta accettata
Star Strider
il 2 Mar 2022
A = [ 4 55
3 55
7 55
1 55
9 98
1 98
2 98
8 98
0 98
1 98
6 17
3 17
0 17
4 17];
[A2u,~,ix] = unique(A(:,2));
A1sums = accumarray(ix,A(:,1),[],@sum);
Desired_Result = [A1sums A2u]
.
4 Commenti
Johan
il 4 Mar 2022
I figured a pretty obfuscated way to do that without for loop; note that it's slower than using accumarray :)
A = [ 4 55
3 55
7 55
1 55
9 98
1 98
2 98
8 98
0 98
1 98
6 17
3 17
0 17
4 17];
logicalmask = A(:,2) == unique(A(:,2))';
result = [sum(A(:,1).*logicalmask)',unique(A(:,2))]
Più risposte (1)
Vedere anche
Categorie
Scopri di più su Numeric Types in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!