How to check if a column of a table exist?

44 visualizaciones (últimos 30 días)
Leon
Leon el 10 de Mzo. de 2020
Editada: Leon el 7 de Dic. de 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.

Respuesta aceptada

Adam Danz
Adam Danz el 10 de Mzo. de 2020
Editada: Adam Danz el 10 de Mzo. de 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.

Más respuestas (1)

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

Iniciar sesión para comentar.

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by