Filter löschen
Filter löschen

How to find the index of string column in a table?

44 Ansichten (letzte 30 Tage)
Elysi Cochin
Elysi Cochin am 25 Apr. 2023
Beantwortet: Cris LaPierre am 25 Apr. 2023
How to get the column ids of a table with string column.
LastName = {'Sanchez';'Johnson';'Li';'Diaz';'Brown'};
Age = [38;43;38;40;49];
Health = {'Fair';'Poor';'Excellent';'Good';'Fair'};
Height = [71;69;64;67;64];
Weight = [176;163;131;133;119];
BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80];
T1 = table(LastName,Age,Health,Height,Weight,BloodPressure)
In the above example the first and third columns are of string datatype.
So I wanted to get
idx = [1 3];
How do I find the index of string column?

Akzeptierte Antwort

Cris LaPierre
Cris LaPierre am 25 Apr. 2023
First comment - none of your table variables are strings. They are cell arrays of character vectors. That may matter depending how you implement a solution.
There are a couple ways depending on what you ultimately want to do. If you want to extract the colums, see the Access Data in Tables doc page. Use this syntax: S = vartype(type); T{rows,S}
LastName = {'Sanchez';'Johnson';'Li';'Diaz';'Brown'};
Age = [38;43;38;40;49];
Health = {'Fair';'Poor';'Excellent';'Good';'Fair'};
Height = [71;69;64;67;64];
Weight = [176;163;131;133;119];
BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80];
T1 = table(LastName,Age,Health,Height,Weight,BloodPressure)
T1 = 5×6 table
LastName Age Health Height Weight BloodPressure ___________ ___ _____________ ______ ______ _____________ {'Sanchez'} 38 {'Fair' } 71 176 124 93 {'Johnson'} 43 {'Poor' } 69 163 109 77 {'Li' } 38 {'Excellent'} 64 131 125 83 {'Diaz' } 40 {'Good' } 67 133 117 75 {'Brown' } 49 {'Fair' } 64 119 122 80
S = vartype("cell");
T1(:,S)
ans = 5×2 table
LastName Health ___________ _____________ {'Sanchez'} {'Fair' } {'Johnson'} {'Poor' } {'Li' } {'Excellent'} {'Diaz' } {'Good' } {'Brown' } {'Fair' }
However, if you do want the index number, the most direct way I can think of is to use varfun with iscell.
idx_LI = varfun(@iscell,T1,'OutputFormat','uniform')
idx_LI = 1×6 logical array
1 0 1 0 0 0
C = 1:width(T1);
idx = C(idx_LI)
idx = 1×2
1 3

Weitere Antworten (0)

Kategorien

Mehr zu Tables finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by