adding values to table at each step

3 views (last 30 days)
Hi,
I have a table 1x 5 eg values with code names such as:
C='ABO1' 'ABO2' 'ADE3' 'ADE4' 'AGUG' 'ACE4'
And I have many other tables, each one generated at time step like:
table 1 step 1:
'ABO1' 7521.3
'ABO2' 12360
'ACE4' 540
'AGUG' 558.5
and table 2 step 2 e.g.:
'ACE4' 0.5
'AGUG' 2
I would like to fill the first table at each time step with corresponding values if there are, if not put nan. So that resulting table would look like:
'ABO1' 'ABO2' 'ADE3' 'ADE4' 'AGUG' 'ACE4'
1 7521.3 12360 nan nan 558.2 nan
2 nan nan nan nan 2 nan
thanks a lot for any hints!
  2 Comments
Guillaume
Guillaume on 19 Oct 2017
Edited: Guillaume on 19 Oct 2017
Is what you call a table actually what matlab calls a table or something else (maybe a cell array?). If it is actually a table, is a code name what matlab calls a table variable? Or something completely different.
Please, use valid matlab commands to construct your example so we're clear how your data is stored.
sensation
sensation on 20 Oct 2017
Hi Guillaume,
thanks for rising thi up. To be more clear yes it is a Table where first row are all code names (ABO1 etc). Table variables are Code 1 Code 2 etc. I could also use the cell instead or array but not sure how to fill them up at each time step with new values. Thanks!

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 20 Oct 2017
If I understood correctly you're generating tables in a loop and want to fill another table one row at a time at each step of the loop, in which case:
codes = {'ABO1' 'ABO2' 'ADE3' 'ADE4' 'AGUG' 'ACE4'};
maintable = array2table(zeros(0, numel(codes)+1), 'VariableNames', ['step', codes]); %create empty destination table
%your loop replace by actual code
numsteps = 10;
looptables = cell(numsteps, 1);
for step = 1:numsteps %your loop, replace by actual code
%random generation of loop table, replace by actual code
randrows = randi(numel(codes));
looptable = table(codes(randperm(numel(codes), randrows))', rand(randrows, 1)*20000, 'VariableNames', {'codes', 'values'});
looptables{step} = looptable;
%filling of the main table
filler = nan(1, numel(codes));
[~, destcol] = ismember(looptable.codes, codes);
filler(destcol) = looptable.values;
maintable{step, :} = [step, filler];
end
maintable
Note that, assuming you've kept all the looptables around, the same can be achieved in one go at the end of the loop with:
maintable2 = vertcat(looptables{:});
maintable2.step = repelem((1:numel(looptables))', cellfun(@height, looptables));
maintable2 = unstack(maintable2, 'values', 'codes')

More Answers (0)

Categories

Find more on Data Type Identification in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!