Help with findgroups command

15 views (last 30 days)
Qiana Curcuru
Qiana Curcuru on 19 Jul 2021
Answered: Akira Agata on 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);

Accepted Answer

Akira Agata
Akira Agata on 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

More Answers (0)

Categories

Find more on Software Development Tools in Help Center and File Exchange

Tags

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!