MATLAB: When I add columns to a table, it changes the assigned names to Var1, Var2 …! How to add columns to an existing table with the assigned names

table

I use this piece of script to create a table:
Tab = table(A.L1(:,1),A.L1(:,2),'VariableNames',{'A_X' 'A_Y'});
And I use this part to add columns to the table:
N1 = size(Tab,2);
Tab(:,N1+1:N+2) = table(B.L1(:,1),B.L1(:,2),'VariableNames',{'B_X' 'B_Y'});
Instead of having 'B_X' and 'B_Y' in the table, I get 'Var1' and 'Var2'.
Do you have any ideas how to have the assigned names in the table? What causes that?
Thanks 🙂

Best Answer

Hello Milad,
What I believe is happening is that the table first creates columns to hold the new data before it then assigns the data. This makes sense if you think about it as replacing a subset of existing data with new data. You wouldn't normally want to replace the variable name in this case:
Tab(2:3,1) = table([3 ; 4]);
Rather than assigning the values to not-yet-existing columns, simply do concatenation to preserve the variable names:
AT = table(rand(10,1),rand(10,1),'VariableNames',{'A_X' 'A_Y'});
BT = table(rand(10,1),rand(10,1),'VariableNames',{'B_X' 'B_Y'});
Tab = [AT BT]
-Cam