Summing Associated Values without Loop

1 vue (au cours des 30 derniers jours)
Jackson Jewett
Jackson Jewett le 29 Nov 2022
Commenté : Jackson Jewett le 29 Nov 2022
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]

Réponse acceptée

Stephen23
Stephen23 le 29 Nov 2022
Modifié(e) : Stephen23 le 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
  1 commentaire
Jackson Jewett
Jackson Jewett le 29 Nov 2022
Incredible, thank you!!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by