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

16 ビュー (過去 30 日間)
Chang Li
Chang Li 2022 年 12 月 31 日
コメント済み: Star Strider 2023 年 1 月 3 日
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.

採用された回答

Star Strider
Star Strider 2022 年 12 月 31 日
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 件のコメント
Voss
Voss 2023 年 1 月 3 日
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 2023 年 1 月 3 日
I had problems getting that to work when I tried it. That’s the reason I went with cellfun in the end.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeTables についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by