How to check if a column of a table exist?

44 views (last 30 days)
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.

Accepted Answer

Adam Danz
Adam Danz on 10 Mar 2020
Edited: Adam Danz on 10 Mar 2020
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.

More Answers (1)

Steven Lord
Steven Lord on 10 Mar 2020
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
  1 Comment
Leon
Leon on 10 Mar 2020
Many thanks, Steven! I wish I could accept two answers at the same time.

Sign in to comment.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!