Overwriting table columns with ()-indexing
Show older comments
Suppose I have two tables,
T1=array2table(rand(5,3))
T2=array2table(char(randi([65,90],5,3)),Var={'Col1','Col2','Col3'})
I wish to replace the final column of T1 with that of T2. One way to accomplish this is,
T3=[T1(:,1:2) , T2(:,3) ]
Why, though, does this indexing approach not give the same result?
T3=T1;
T3(:,3)=T2(:,3)
The result is the same as what would be obtained with brace indexing,
T3=T1;
T3{:,3}=T2{:,3}
I understand why brace-indexing gives this result, but I thought ()-indexing was supposed to keep the data contained in a table. Why don't the tabular properties of T2(:,3), like the column name and data type, get transfered as well when parentheses are used?
1 Comment
I think the table subsind/subsref operations are much more overloaded than they first appear to be. One might expect them to have a similar nature array indexing, i.e. that they refer to actual locations in memory (of pointers or data). But given that each column/variable seems to be stored as its own array in memory, implementing generalized parenthesis indexing over multiple columns/variables is non-trivial. And I suspect, somewhat overloaded.
We can already see this in the fact that one can assign cell arrays to a table:
T = array2table(rand(3,5))
T(2,3:5) = {0,42,99}
Accepted Answer
More Answers (2)
Srinjoy
on 15 Jun 2026 at 11:50
T3(:,3) = T2(:,3);
When you do the above,
MATLAB is not actually replacing the third variable of T3. Instead, it is modifying the existing variable Var3.
Since Var3 in T3 is already of type double, MATLAB keeps that type and tries to fit the new data into it. The column from T2 contains characters, so MATLAB converts those characters to their numeric codes. That is why you see values like 78, 74, etc., which correspond to the ASCII values of 'N', 'J', and so on.
But, when you do
T3 = [T1(:,1:2), T2(:,3)];
you are creating a completely new table. In this case, MATLAB takes the third variable directly from T2, including its type and name, so it remains a character column.
So even though parentheses indexing returns a table, assignment with () does not necessarily copy over the variable metadata. If the target variable already exists, MATLAB preserves its type and assigns the new values into it, performing any required type conversion.
Hope this helps.
1 Comment
2 Comments
I had to recalibrate on where this question started ... which was:
"I wish to replace the final column of T1 with that of T2. "
Why isn't ordinary .field indexing sufficient to achieve the desired assignment?
rng(100);
T1 = array2table(rand(5,3))
T2 = array2table(char(randi([65,90],5,3)),Var={'Col1','Col2','Col3'})
T3 = T1;
T3.Var3 = T2.Col3
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!