Concatenate vertically multiple tables with different dimensions

I'd like to concatenate vertically several tables with common and uncommon columns: in this example code columns is common to A and B but not the others. The example expected result is C. In this example Type doesnt exist for A, then in C it is replaced by Nan. In my example, there are only 2 tables with one common column. I need to do this for 8 tables with 3 common columns and 5-7 columns in total.
A =
3×2 table
code Name
____ _________
1001 {'Jones'}
1002 {'James'}
1001 {'Robert'}
B =
3×2 table
code Type
____ _________
201 {'Car'}
201 {'Bus'}
203 {'Train'}
C = code Name Type
____ _________ _________
1001 {'Jones'} Nan
1002 {'James'} Nan
1001 {'Robert'} Nan
201 Nan {'Car'}
201 Nan {'Bus'}
203 Nan {'Train'}

 Accepted Answer

You can do this with the outerjoin command:
A = table([1001; 1002; 1003],{'Jones';'James';'Robert'},...
'VariableNames',{'code','Name'});
B = table([201; 202; 203],{'Car'; 'Bus'; 'Train'},...
'VariableNames',{'code' 'Type'});
outerjoin(A,B,'MergeKeys',true)
ans = 6x3 table
code Name Type ____ __________ __________ 201 {0×0 char} {'Car' } 202 {0×0 char} {'Bus' } 203 {0×0 char} {'Train' } 1001 {'Jones' } {0×0 char} 1002 {'James' } {0×0 char} 1003 {'Robert'} {0×0 char}
Because the variables with missing values are character type, MATLAB will leave them as empty character arrays. (It would have used NaN for missing numeric variables.)

3 Comments

Thanks a lot, but what if there are same values in the common column?
A =
code Name
____ _________
201 {'Jones'}
B =
code Type
____ _________
201 {'Car'}
I dont want them to be joined, just really one below the other:
C =
code Name Type
____ _________ _________
201 {'Jones'} Nan
201 Nan {'Car'}
Ah, sorry. I assume you wanted to merge data. I believe that to simply concatenate them, you'll need to add the "missing" columns to each table. For example:
A = table([1001; 1002; 1003; 201],{'Jones';'James';'Robert';'Nancy'},...
'VariableNames',{'code','Name'});
B = table([201; 202; 203],{'Car'; 'Bus'; 'Train'},...
'VariableNames',{'code' 'Type'});
% Add new columns corresponding to the missing ones
A.Type = cell(size(A,1),1);
B.Name = cell(size(B,1),1);
C = [A; B]
C = 7x3 table
code Name Type ____ ____________ ____________ 1001 {'Jones' } {0×0 double} 1002 {'James' } {0×0 double} 1003 {'Robert' } {0×0 double} 201 {'Nancy' } {0×0 double} 201 {0×0 double} {'Car' } 202 {0×0 double} {'Bus' } 203 {0×0 double} {'Train' }
I just did the laziest way I could think of to add "empty" data. You could do other things.

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2020a

Community Treasure Hunt

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

Start Hunting!