Help with findgroups command

9 Ansichten (letzte 30 Tage)
Qiana Curcuru
Qiana Curcuru am 19 Jul. 2021
Beantwortet: Akira Agata am 20 Jul. 2021
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);

Akzeptierte Antwort

Akira Agata
Akira Agata am 20 Jul. 2021
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

Weitere Antworten (0)

Kategorien

Mehr zu Software Development Tools finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by