Azzera filtri
Azzera filtri

Summing Associated Values without Loop

3 visualizzazioni (ultimi 30 giorni)
I have an nx2 matrix. Some elements in the first column repeat. I am interested in the elements in the second column that correspond to respective unique values in the first column. For each given unique value in the first column, I would like to sum each of the corresponding values in the second column. Ultimately, I would like to generate a new matrix in which every unique element in the first column is represented once, with the sum of its corresponding elements in the second column. The matrices I am using are huge, so I would like to do this without loops, but I cannot find a method to do so. Does anyone have any advice? Thank you!!
As an example, if given A, I would like to produce A' without using a loop:
A = [ 1 2
5 7
1 -1
3 5
5 2
1 7]
A'= [1 8
5 9
3 5]

Risposta accettata

Stephen23
Stephen23 il 29 Nov 2022
Modificato: Stephen23 il 29 Nov 2022
A = [1,2;5,7;1,-1;3,5;5,2;1,7]
A = 6×2
1 2 5 7 1 -1 3 5 5 2 1 7
[U,~,X] = unique(A(:,1),'stable');
V = accumarray(X,A(:,2));
M = [U,V]
M = 3×2
1 8 5 9 3 5
Or another approach:
V = groupsummary(A(:,2),X,@sum);
M = [U,V]
M = 3×2
1 8 5 9 3 5

Più risposte (0)

Categorie

Scopri di più su Graphics Object Programming in Help Center e File Exchange

Prodotti


Release

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by