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 CenterFile Exchange에서 Tables에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by