Simpler code for aggregating data by sum
古いコメントを表示
Hello,
given matrix A: A=[4 0.5;4 0.25;1 0.125; 2 0.2;4 0.6;3 0.2; 1 2/3; 2 1; 2 1/16;4 0.5]
asked: Aggregate data in first column by sum
desired result:
1.0000 0.7917
2.0000 1.2625
3.0000 0.2000
4.0000 1.8500
I composed a code, but it work half, it can not make the data unique. So it fails at : G=unique(List)
Can somebody tell me why it fails at that point? And is there a more straight forward code for this whole proces? Maybe inbuilt functions? Can I get some feedback pls?
This is my code:
List=[];
% Make list unique
for i=1:size(A,1)
F=A(A(:,1)==A(i,1),:); %subsetting all rows
ElementList=[A(i,1) sum(F(:,2))]; %adding the sum of the subset to a row
List=[List; ElementList] % saving row plus its aggregated sum to a list
end
G=unique(List) %making the list unique
kind regards,
3 件のコメント
rakbar
2019 年 1 月 10 日
Try this:
G = findgroups(A(:,1));
A=[4 0.5;4 0.25;1 0.125; 2 0.2;4 0.6;3 0.2; 1 2/3; 2 1; 2 1/16;4 0.5]
func = @(x)sum(x);
Y = splitapply(func,A(:,2),G);
[unique(G) Y]
ans =
1.0000 0.7917
2.0000 1.2625
3.0000 0.2000
4.0000 1.8500
Akira Agata
2019 年 1 月 10 日
Or simply:
A = [4 0.5;4 0.25;1 0.125; 2 0.2;4 0.6;3 0.2; 1 2/3; 2 1; 2 1/16;4 0.5];
B = splitapply(@sum,A(:,2),A(:,1));
The result is:
>>[unique(A(:,1)), B]
ans =
1.0000 0.7917
2.0000 1.2625
3.0000 0.2000
4.0000 1.8500
Clarisha Nijman
2019 年 1 月 11 日
採用された回答
その他の回答 (0 件)
カテゴリ
ヘルプ センター および File Exchange で Timing and presenting 2D and 3D stimuli についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!