append to a table using findgroups and splitapply

조회 수: 4 (최근 30일)
Qiana Curcuru
Qiana Curcuru 2021년 7월 20일
답변: Simon Chan 2021년 7월 20일
I have a for loop that creates a table every iteration but i just want to append the new data table to the end of the last table that was made instead of over writing the table every iteration. how would i do that?
for i=1:10
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)
end

답변 (1개)

Simon Chan
Simon Chan 2021년 7월 20일
Create an empty cell and empty array before the loop.
Then create the table after the loop.
combinefields={}; % Empty cell
combinex = []; % Empty array
for i=1:10
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
combinefields = vertcat(combinefields, fields); % Combine 'fields'
combinex = [combinex; x]; % Combine 'x'
end
tResult = table(combinefields, combinex,... % Create table after finishing the loop
'VariableNames',{'Item','Value'});
%% Show the result
disp(tResult)

카테고리

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