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));
2 个评论
采纳的回答
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 个评论
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!