Sum of first column based on second column and storing results in a matrix

조회 수: 1 (최근 30일)
I have two columns in a matrix.
1st Column : duration
2nd column : Reference Number
I want to add all durations rows for each reference number and store it in a matrix where there is a single duration(sum) along with its unique reference number.
My table looks like below. For example I need a unique summed value of duration for each 3130 reference number. I tried to do it individually using below code but very time consuming. Can anyone please help me to loop it and store result in a matrix? Any guidance on this will be appreciated. Thanks.
idx = A(:,2)==3130;
s = sum(A(idx,1));
matlab.PNG
  댓글 수: 2
Devansh Patel
Devansh Patel 2019년 6월 26일
[a,~,c] = unique(A(:,2));
out = [a, accumarray(c,A(:,1))];
I Guess I figured it!
Adam Danz
Adam Danz 2019년 6월 26일
편집: Adam Danz 2019년 6월 26일
Nice job! Also, splitapply() was designed for this problem; see answer below.

댓글을 달려면 로그인하십시오.

채택된 답변

Adam Danz
Adam Danz 2019년 6월 26일
편집: Adam Danz 2019년 6월 26일
% Create fake data for the demo
A = [rand(30,1),randi(3,30,1)+1000];
% Calculate group sum and store in table
[groupID, groups] = findgroups(A(:,2));
groupsum = splitapply(@sum,A(:,1),groupID);
T = table(groups,groupsum)
Result (will vary due to random draw).
T =
3×2 table
groups groupsum
______ ________
1001 2.122
1002 6.1048
1003 6.8219

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

태그

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by