Summing Associated Values without Loop

1 Ansicht (letzte 30 Tage)
Jackson Jewett
Jackson Jewett am 29 Nov. 2022
Kommentiert: Jackson Jewett am 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]

Akzeptierte Antwort

Stephen23
Stephen23 am 29 Nov. 2022
Bearbeitet: Stephen23 am 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

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by