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

data analysisMATLAB

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

Best Answer

% 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
Related Question