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

조회 수: 1 (최근 30일)
MINHOON KIM
MINHOON KIM 2020년 3월 19일
댓글: Walter Roberson 2020년 3월 19일
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