How to check if a column of a table exist?

44 ビュー (過去 30 日間)
Leon
Leon 2020 年 3 月 10 日
編集済み: Leon 2020 年 12 月 7 日
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.
  1 件のコメント
Kristina Collins
Kristina Collins 2020 年 12 月 7 日
This rocks, thank you.

サインインしてコメントする。

採用された回答

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
  1 件のコメント
Leon
Leon 2020 年 3 月 10 日
Many thanks, Steven! I wish I could accept two answers at the same time.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by