append to a table using findgroups and splitapply
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
Simon Chan
am 20 Jul. 2021
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 Kommentare
Siehe auch
Kategorien
Mehr zu Language Fundamentals finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!