How to check if a column of a table exist?

44 visualizzazioni (ultimi 30 giorni)
Leon
Leon il 10 Mar 2020
Modificato: Leon il 7 Dic 2020
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.

Risposta accettata

Adam Danz
Adam Danz il 10 Mar 2020
Modificato: Adam Danz il 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.

Più risposte (1)

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

Accedi per commentare.

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Prodotti


Release

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by