How to check if a column of a table exist?

46 次查看(过去 30 天)
The below command works if I know the exact names of the Table column variable names.
any(strcmp('TESTNAME', T1.Properties.VariableNames))
What if either side has trailing spaces? How do I check the first 4 characters of the two elements, i.e., 'TEST' against the first 4 characters of all the T1.Properties.VariableNames?
Thanks.

采纳的回答

Adam Danz
Adam Danz 2020-3-10
编辑:Adam Danz 2020-3-10
Use strtrim to remove leading and trailing whitespace. Use startsWith to determine if the any of the character arrays start with the pattern.
startsWith(strtrim(T1.Properties.VariableNames), 'EXPO')
startsWith() requires Matlab r2016b or later. For earlier releases use strncmp() to compare the first n characters.

更多回答(1 个)

Steven Lord
Steven Lord 2020-3-10
Use the tools from the "Find and Replace" section on this documentation page. startsWith, matches, or contains will probably be most useful.
load patients
patients = table(LastName,Gender,Age,Height,Weight,Smoker,Systolic,Diastolic);
Let's check if patients contains a variable whose name starts with Sm. There is one, Smoker, so this should return true.
any(startsWith(patients.Properties.VariableNames, 'Sm'))
Now let's check for a variable starting with Ha. The Height variable is close but not a match, so this should return false.
any(startsWith(patients.Properties.VariableNames, 'Ha'))
We can use the logical output from startsWith to select variables. Let's ask for all those whose name starts with s (lower-case or upper-case doesn't matter) and get those variables from the first ten columns of patients.
propsStartWithS = startsWith(patients.Properties.VariableNames, 's', 'IgnoreCase', true);
T = patients(1:10, propsStartWithS) % Contains the Smoker and Systolic variables

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by