MATLAB Answers

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

4 views (last 30 days)
MINHOON KIM
MINHOON KIM on 19 Mar 2020
Commented: Walter Roberson on 19 Mar 2020
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

Sign in to comment.

Answers (2)

Walter Roberson
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

MINHOON KIM
MINHOON KIM on 19 Mar 2020
"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 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

Sign in to comment.


KSSV
KSSV on 19 Mar 2020
.var is to access fields of structures.
{} is to access cells.
Read about structures and cells.

  3 Comments

MINHOON KIM
MINHOON KIM on 19 Mar 2020
Table type is part of the Structure type??
Mohammad Sami
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.
MINHOON KIM
MINHOON KIM on 19 Mar 2020
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?

Sign in to comment.

Sign in to answer this question.

Products


Release

R2019b

Translated by