Summing Associated Values without Loop

조회 수: 1 (최근 30일)
Jackson Jewett
Jackson Jewett 2022년 11월 29일
댓글: Jackson Jewett 2022년 11월 29일
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]

채택된 답변

Stephen23
Stephen23 2022년 11월 29일
편집: Stephen23 2022년 11월 29일
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by