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 CenterFile Exchange에서 Software Development Tools에 대해 자세히 알아보기

태그

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by