How to check whether a column exist in a table?

조회 수: 513 (최근 30일)
Alon Rozen
Alon Rozen 2016년 11월 24일
댓글: Nikolaus Koopmann 2024년 7월 2일
Hi all,
I search for this question in the web and found the following solution: Suppose I have a table named 'My_Table' and want to check if it contains a column (field) named 'My_Column'. The code:
Exist_Column = strmatch('My_Column',My_Table.Properties.VariableNames)
should result in logical that answer the question. I checked it and it works. However, the Matlab editor commented that 'strmatch' is not a recommended function to use because it is about to be removed in future version and suggest instead the use of either 'strncmp' or 'validatestring'. Problem is that both do not return a logical and more steps are required to get the answer.
So, my question is: what is the simplest recommended way to determine if a certain column name exist in a table?
Thanks,
Alon
  댓글 수: 1
Carlos Aguilar
Carlos Aguilar 2017년 12월 31일
Just came across to this question. An anonymous function will also do the job (and will be reusable within the scope):
isTableCol = @(t, thisCol) ismember(thisCol, t.Properties.VariableNames);

댓글을 달려면 로그인하십시오.

채택된 답변

KSSV
KSSV 2016년 11월 24일
Exist_Column = strcmp('My_Column',My_Table.Properties.VariableNames)
val = Exist_Column(Exist_Column==1) ;
  댓글 수: 6
Gabriel Blanco
Gabriel Blanco 2019년 6월 25일
Bonjour Nic!
Nikolaus Koopmann
Nikolaus Koopmann 2022년 11월 29일
any("MyColumn" == string(My_Table.Properties.VariableNames))

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

jkr
jkr 2019년 5월 14일
sum(ismember(mx.Properties.VariableNames,'NameYouWantToCheck'))
returns 1 if found, 0 if not
  댓글 수: 2
AusPollen
AusPollen 2021년 5월 23일
Nice! although you don't need to sum if you switch the ismember arguments, ie. use ismember('My_Column',My_Table.Properties.VariableNames)
Nachiket Wadwankar
Nachiket Wadwankar 2024년 2월 9일
This is exactly what I wanted. Thanks a lot for this trick!!

댓글을 달려면 로그인하십시오.


Sean Lynch
Sean Lynch 2021년 9월 5일
I used "any", but agree "ismember" is even better
exists = any(strcmp('Column-Name', My_Table.Properties.VariableNames))

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by