MATLAB: Adding values to table at each step

append to tableismembermatching

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!

Best Answer

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')