Help with findgroups command

8 visualizzazioni (ultimi 30 giorni)
Qiana Curcuru
Qiana Curcuru il 19 Lug 2021
Risposto: Akira Agata il 20 Lug 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);

Risposta accettata

Akira Agata
Akira Agata il 20 Lug 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

Più risposte (0)

Categorie

Scopri di più su Software Development Tools in Help Center e File Exchange

Prodotti


Release

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by