append to a table using findgroups and splitapply

4 visualizzazioni (ultimi 30 giorni)
Qiana Curcuru
Qiana Curcuru il 20 Lug 2021
Risposto: Simon Chan il 20 Lug 2021
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

Risposte (1)

Simon Chan
Simon Chan il 20 Lug 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)

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