What is difference between indexing using ".var" and "{}"?

1 次查看(过去 30 天)
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

回答(2 个)

Walter Roberson
Walter Roberson 2020-3-19
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 个评论
MINHOON KIM
MINHOON KIM 2020-3-19
"tm{:,6} = CHAR" and "tm.MN_1 = CHAR" show same results.
In this situation,
Why "tm{:,6} = CHAR" doesn't work, although "tm.MN_1 = CHAR" works...?
Walter Roberson
Walter Roberson 2020-3-19
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
KSSV 2020-3-19
.var is to access fields of structures.
{} is to access cells.
Read about structures and cells.
  3 个评论
Mohammad Sami
Mohammad Sami 2020-3-19
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.
MINHOON KIM
MINHOON KIM 2020-3-19
You said that the .var is also used to access columns in a table.
If so, When I use () indexing in table type, where does this indexing access to?

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by