append to a table using findgroups and splitapply
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
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)
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!