Indexing behavior of table properties

Suppose we have a table such as,
T=table(rand(3,1,'single'), randi(5,3,1))
T = 3×2 table
Var1 Var2 _______ ____ 0.58963 3 0.2204 3 0.84045 1
What is it that allows the VariableTypes to be indexed by a string this way,
T.Properties.VariableTypes("Var1")
ans = "single"
but not this way,
z=T.Properties.VariableTypes,
z = 1×2 string array
"single" "double"
z("Var1")
Error using indexing
Unable to use a value of type string as an index.

 Réponse acceptée

In the former case, it is table's indexing code that is performing all the indexing steps. It knows how to index into the properties of itself using strings (to get the VariableTypes of one particular variable in the table.)
T=table(rand(3,1,'single'), randi(5,3,1));
T.Properties.VariableTypes("Var1") % essentially equivalent of:
ans = "single"
subsref(T, substruct('.', 'Properties', '.' ,'VariableTypes', '()', {'Var1'}))
ans = "single"
Note that in the subsref() call, it does three levels of indexing chained together.
For the latter, you're using table's indexing code to extract a string array containing the VariableTypes. Then trying to index into the variable you extracted goes through string's indexing code, which doesn't know how to index into a string using another string.
VT = T.Properties.VariableTypes; % Same as above without the last 2 inputs to substruct
class(VT)
ans = 'string'
VT("Var1") % String indexing doesn't support this
Error using indexing
Unable to use a value of type string as an index.

Plus de réponses (0)

Catégories

Produits

Version

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by