When I add columns to a table, it changes the assigned names to Var1, Var2 ...! How can I add columns to an existing table with the assigned names?

조회 수: 3 (최근 30일)
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 :)

채택된 답변

Cam Salzberger
Cam Salzberger 2017년 9월 8일
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

추가 답변 (1개)

Peter Perkins
Peter Perkins 2017년 9월 14일
This
Tab(:,{'B_X' 'B_Y'}) = table(B.L1(:,1),B.L1(:,2))
or this
Tab(:,{'B_X' 'B_Y'}) = array2table(B.L1)
or perhaps this (if you really only have two)
Tab.B_X = B.L1(:,1);
Tab.B_Y = B.L1(:,2))
do what you want. As Cam says, you would not want assignment to move the names over because the assignment might be only to some elements of existing variables.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by