Exist function returning 0 for a variable that definitely exists?

조회 수: 2 (최근 30일)
I'm trying to use the 'exist' function to check whether a certain variable has been read in from a .csv file, as the existence of that variable defines the direction the rest of the code should take. This is what I have boils down to:
if exist('DATA.processedData.VTI_EX1048_09_CJC09', 'var')
CJCConfirm = 'Yes';
else
CJCConfirm = 'No';
end
(For reasons out of my control, the return has to be 'yes' or 'no'). However, even when running a data set where I know that DATA.processedData.VTI_EX1048_09_CJC09 exists (confirmed by putting it into the command window and seeing it returns a value), this:
exist DATA.processedData.VTI_EX1048_09_CJC09
still returns a 0. I've checked, and the exist function works fine with other variables in my workspace.
What do I need to do differently?

채택된 답변

James Tursa
James Tursa 2018년 7월 18일
편집: James Tursa 2018년 7월 18일
Don't use exist() with struct field syntax. Only use it for variable names. E.g.,
>> a.f = 4
a =
f: 4
>> exist('a','var')
ans =
1
>> exist('a.f','var')
ans =
0
>> exist('a','var') && isfield(a,'f')
ans =
1
  댓글 수: 2
Steven Lord
Steven Lord 2018년 7월 18일
Also keep in mind that you can't specify multiple levels of indexing in one call to isfield.
a = struct('b', struct('c', 2));
abc = a.b.c % 2
check_bc = isfield(a, 'b.c') % false
check_b_then_c = isfield(a, 'b') && isfield(a.b, 'c') % true
The struct a does not have a field named b.c (and that would be an invalid field name, so it can't have a field with that name) but the struct stored in a.b does have a field named c.
Brendan Macklem
Brendan Macklem 2018년 7월 18일
Using ismember worked! Thanks

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by