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

1 Ansicht (letzte 30 Tage)
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 Kommentare
Devansh Patel
Devansh Patel am 26 Jun. 2019
[a,~,c] = unique(A(:,2));
out = [a, accumarray(c,A(:,1))];
I Guess I figured it!
Adam Danz
Adam Danz am 26 Jun. 2019
Bearbeitet: Adam Danz am 26 Jun. 2019
Nice job! Also, splitapply() was designed for this problem; see answer below.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Adam Danz
Adam Danz am 26 Jun. 2019
Bearbeitet: Adam Danz am 26 Jun. 2019
% 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

Weitere Antworten (0)

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Produkte


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by