How to exist(obj.struct.var)?

조회 수: 10 (최근 30일)
Douglas Farinelli
Douglas Farinelli 2018년 9월 6일
댓글: Steven Lord 2018년 9월 6일
exist(obj.struct.var) always returns 0 regardless if the var exists or not.

채택된 답변

Douglas Farinelli
Douglas Farinelli 2018년 9월 6일
isfield(obj.struct,'var')
  댓글 수: 1
Steven Lord
Steven Lord 2018년 9월 6일
If you're not sure if the obj variable is a struct or has a field named struct, you can call isfield twice.
y = isfield(obj, 'struct') && isfield(obj.struct, 'var');
The first isfield call will return false if obj is not a struct or is a struct that does not have a field named struct. Only if the first isfield call returns true will the short-circuit && operator cause the second isfield call to be evaluated. In fact, that documentation page includes an example (Change Structure Field Value) that is somewhat related to this question.
obj = 42; % Not a struct
y1 = isfield(obj, 'struct') && isfield(obj.struct, 'var') % false
obj = struct('abc', 'def'); % struct but without the correct field
y2 = isfield(obj, 'struct') && isfield(obj.struct, 'var') % false
obj = struct('struct', struct('var', 'std'));
y3 = isfield(obj, 'struct') && isfield(obj.struct, 'var') % true

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by