Concatenate horizontally two tables

315 views (last 30 days)
SYML2nd on 6 May 2020
Edited: Adam Danz on 6 May 2020
I have two tables 3262x218 (let's call it A) and 3262x255 (let's call it B) . Both have an header line. I want to concatenate horizontally these two tables in order to obtain an array 3262x473. Unfortunally I cannot just do C=[A,B], because it is not an array but tables. If I do C=[A,B] , it gives me the error "Duplicate table variable name".
I already tried to use this command:
C=outerjoin(A, B, 'Type', 'Left', 'MergeKeys', false)
I obtain an arary 3262x473, but the part of the array related with the array B is Nan.
How can i fix this problem?
  1 Comment
Guillaume on 6 May 2020
Concatenation and joining are two different operations. You can concatenate tables but indeed they must have different variable names, otherwise it's ambiguous what should be done with the duplicate variables. If you want them to be distinct variables in the result, then you do need a concatenation with [] but you'd have to rename one of the duplicate variable name.
If you are looking at joining the table, then there are different types of joins: left outer join, right outer join, full outer join, inner join, and plain join. All merge the rows of the table which have identical key but they all behave differently with regards to rows that don't match or when there are several match. At the moment, we don't have enough information on what you want to tell you which to use and how to use it.

Sign in to comment.

Answers (1)

Adam Danz
Adam Danz on 6 May 2020
Edited: Adam Danz on 6 May 2020
Follow this demo to automatically add "2" to duplicate variable names in table #2.
Also see Guillaume's suggesting to use matlab.lang.makeUniqueStrings
% Create 2 tables of equal height; 2 of 3 variable names are the same.
T1 = array2table(rand(10,3), 'VariableNames', {'A', 'B', 'C'});
T2 = array2table(rand(10,3), 'VariableNames', {'A', 'B', 'D'});
% Determine which columns have the exact same case-sensitive name
isSame = ismember(T1.Properties.VariableNames, T2.Properties.VariableNames);
% Append duplicate names in T2 with a number
T2.Properties.VariableNames(isSame) = strcat(T2.Properties.VariableNames(isSame), repmat({'2'},1,sum(isSame)));
% Horizontally concatenate the tables.
T3 = [T1, T2]
Alternatively, to keep the rows of tables T1 and T2 in the same order, use T = outerjoin(Tleft,Tright)
Adam Danz
Adam Danz on 6 May 2020
Your English is impeccable. My weird mental block is not being able to immediately see my own typos which happens frequently to me.

Sign in to comment.


Community Treasure Hunt

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

Start Hunting!