What is difference between indexing using ".var" and "{}"?
1 view (last 30 days)
Show older comments
tm =readtable ('EPLteams.xlsx');
tm(:,6) = tm{:,5};
tm.Properties.VariableNames(6) = {'MN_1'};
MN_0 = tm(:,5);
MN_1 = tm(:,6);
a = tm{:,6}
a_1 = tm.MN_1
CHAR(1:20,1) = 'a'
tm
% Using ".var"
tm.MN_1 = CHAR
% Using "{}"
tm.MN_1 = tm{:,5}; % This is the code to change the 'table type' to 'cell type' again. Ignore it.
tm{:,6} = CHAR
0 Comments
Answers (2)
Walter Roberson
on 19 Mar 2020
Using the .variable name can only select one variable at a time, but most of the time it is easier to understand the code when you use the .variable version.
For any one table variable what you can do with the two forms is the same, and is also the same as using tm{:, 'MN_1'}.
Exception: a table entry can contain a cell array or table entry, and you might want to index that. If you were to try tm.MN_1(1) followed directly by () or {} indexing, like tm.MN_1(1)(:,7) then that is not valid syntax, but tm{:, 6}(:,7) is valid syntax. So technically using {} can do something with an individual variable that using .variable cannot do.
2 Comments
Walter Roberson
on 19 Mar 2020
tm{:,6} gets you to the cell array of character vectors, and you are trying to assign a character array to it, same as if you had had
tm6 = cell(20,1);
tm6(:,1) = ('a':'t').'; %trying to assign char elements to places that are cell is going to fail
tm.MN_1 = CHAR is defined as replacing the entire variable MN_1 with whatever is in CHAR
Internally the difference is roughly
%tm{rows,6} = CHAR becomes
assert(size(tm.data{1,6}(rows,:),1) == size(CHAR,1), 'wrong size')
tm.data{1,6}(rows,1) = CHAR %fails because char is not cell
%tm.MN_1 = CHAR becomes
assert(height(tm) == size(CHAR,1), 'wrong size')
tm.data{6} = CHAR %works because everything is replaced
KSSV
on 19 Mar 2020
.var is to access fields of structures.
{} is to access cells.
Read about structures and cells.
3 Comments
Mohammad Sami
on 19 Mar 2020
In addition to fields of structure, the .var is also used to access columns in a table. Similarly you can use {:,idx} to retrieve the contents of a column by index instead of by column name.
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!