Help with findgroups command

9 ビュー (過去 30 日間)
Qiana Curcuru
Qiana Curcuru 2021 年 7 月 19 日
回答済み: Akira Agata 2021 年 7 月 20 日
I want to sum the first 3 values in the second column for each category.
For example, in this case I want the result to be:
apples: 4
orange: 2
I have the following code and i can't get it to work. Thanks!
a={'apples' 1 2;
'orange' 2 3;
'apples' 3 4;
'Pear' 4 5;
'apples' 5 6;}
[G,fields]=findgroups(a(:,1));
a(1:3)
G(1:3)
b=a(:,2)
X=splitapply(@sum, b ,G);

採用された回答

Akira Agata
Akira Agata 2021 年 7 月 20 日
Like this?
a = {...
'apples' 1 2;...
'orange' 2 3;...
'apples' 3 4;...
'Pear' 4 5;...
'apples' 5 6;};
% Extract the first 3 items
a2 = a(1:3,:);
% Apply findgroups
[G, fields] = findgroups(a2(:,1));
% Execute splitapply
x = splitapply(@sum, cell2mat(a2(:,2)), G);
% Summarize the result
tResult = table(fields, x,...
'VariableNames',{'Item','Value'});
% Show the result
disp(tResult)
Item Value __________ _____ {'apples'} 4 {'orange'} 2

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSoftware Development Tools についてさらに検索

タグ

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by