How to extract column number of a variable in matlab table?

11 vues (au cours des 30 derniers jours)
Chang Li
Chang Li le 31 Déc 2022
Commenté : Star Strider le 3 Jan 2023
How to extract column number of a variable in matlab table? For example, the column number of the variable A2 in a table: table.A2 is 2. How do I use “table.A2” as input to extract the column#: 2 and save 2 in another variable? Thank you very much.

Réponse acceptée

Star Strider
Star Strider le 31 Déc 2022
One approach —
T1 = array2table(randn(7,5), 'VariableNames',{'A1','A2','A3','A4','A5'})
T1 = 7×5 table
A1 A2 A3 A4 A5 ________ ________ _________ ________ ________ -1.9106 -0.22123 -0.47514 -0.06542 0.13593 -0.14144 -1.8162 -1.1542 0.55953 -0.22285 -2.8992 0.23029 0.61249 0.12032 1.4226 1.2559 0.94259 -0.027742 1.2783 -1.6119 1.4119 -0.18684 0.78489 0.29917 -1.2797 -0.6079 -0.43467 -0.093609 -0.45867 -1.4682 -1.2539 -1.2575 -1.5183 0.21204 2.1747
VN = T1.Properties.VariableNames;
Lvc = cellfun(@(x)strcmp(x,'A2'), VN, 'Unif',0);
ColNr = find(cell2mat(Lvc))
ColNr = 2
.
  2 commentaires
Voss
Voss le 3 Jan 2023
Note that strcmp works with a cell array of character vectors, so cellfun and cell2mat are unnecessary in this case:
T1 = array2table(randn(7,5), 'VariableNames',{'A1','A2','A3','A4','A5'})
T1 = 7×5 table
A1 A2 A3 A4 A5 ________ ________ __________ ________ ________ -0.40518 -1.296 -0.5102 0.098651 1.4641 -1.1006 -0.53507 -0.0015906 -0.50055 -0.66593 -0.72622 -0.50025 -0.9243 0.90477 -1.174 0.65818 -0.43009 -1.1515 0.42241 -1.2278 -0.41902 -1.3493 1.1826 1.302 0.36007 -1.3057 -1.3507 -0.80558 0.12925 -0.88737 0.42965 1.0593 -0.27105 0.73376 0.49773
VN = T1.Properties.VariableNames;
ColNr = find(strcmp(VN,'A2'))
ColNr = 2
Star Strider
Star Strider le 3 Jan 2023
I had problems getting that to work when I tried it. That’s the reason I went with cellfun in the end.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Tables dans Help Center et File Exchange

Produits


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by