MATLAB: How to combine table arrays including the same variable name horizontally

arraycombineconcatenateMATLABtable

There are two table arrays and for each containing a column with the same variable name.
When I try to concatenate them horizontally, the following error occurs:
>> T = [T1,T2]
Duplicate table variable name: 'x1'.
I would like to know how to combine 2 tables by deleting duplicated one or changing the variable name.

Best Answer

You can use join function if the values held by the same variable name are the same.
>> T = join(T1,T2);
T =
5×3 table
x1 x2 x3
_________ ________ ________
0.10665 0.86869 0.86869
0.9619 0.084436 0.084436
0.0046342 0.39978 0.39978
0.77491 0.25987 0.25987
0.8173 0.80007 0.80007
If the table retains different values in the same variable, there are possible ways to do this.
  1. Detect the same variable name and change the variable name
  2. Create a common variable that is the key and combine it with innerjoin function
1. Detect the same variable name and change the variable name
T1 = array2table(rand(5,2),'VariableNames',{'x1','x2'});
T2 = array2table(rand(5,2),'VariableNames',{'x1','x3'});
% Detect if there is the same variable name
ind = contains(T2. Properties.VariableNames,T1. Properties.VariableNames);
T2. Properties.VariableNames{ind} = [T2. Properties.VariableNames{ind},'_T2']; % Change variable name
T_all = [T1,T2]; % join
>> T_all
T_all =
5×4 table
x1 x2 x1_T2 x3
________ ________ ________ ________
0.075854 0.12991 0.45054 0.82582
0.05395 0.56882 0.083821 0.53834
0.5308 0.46939 0.22898 0.99613
0.77917 0.011902 0.91334 0.078176
0.93401 0.33712 0.15238 0.44268
2. Create a common variable that is the key and combine it with innerjoin function
T1 = array2table(rand(5,2),'VariableNames',{'x1','x2'});
T2 = array2table(rand(5,2),'VariableNames',{'x1','x3'});
Add variable that is % Key
T1. Key = (1:height(T1))';
T2. Key = (1:height(T2))';
T_all = innerjoin (T1,T2,'Keys','Key') % Join
T_all. Key = [] % Delete Key
>> T_all
T_all =
5×4 table
x1_T1         x2       x1_T2         x3   
    ________    ________    ________    ________
0.075854     0.12991     0.45054     0.82582
     0.05395     0.56882    0.083821     0.53834
      0.5308     0.46939     0.22898     0.99613
     0.77917    0.011902     0.91334    0.078176
     0.93401     0.33712     0.15238     0.44268