conditional logic inside conditional logic

조회 수: 1 (최근 30일)
Martin
Martin 2019년 1월 13일
댓글: Martin 2019년 1월 13일
Hello, I would like to know if there is any way to write the following in one line ?
if isfield(hund.A)
if hund.A == 1
'do something'
end
end
Since I need to know if field 'A' exist I cannot just do if hund.A == 1 right away.
Is there a way to do something like this:
if isfield(hund.A) Then if hund.A == 1
'do something'
end
I would like to avoid too many if's. Thanks in advance...

채택된 답변

Jan
Jan 2019년 1월 13일
편집: Jan 2019년 1월 13일
if isfield(hund.A)
This will not work. I guess you mean:
if isfield(hund, 'A')
Then this works:
if isfield(hund, 'A') && hund.A == 1
The condition hund.A==1 is evaluated only, if the first condition is true. If the field 'A' does not exist, the 2nd part is not reached. This is called "shortcircuting".
Alternative: Create a function, which replies a default value for not existing fields:
function R = SafeGetField(S, F)
if isfield(S, F)
R = S.F;
else
R = [];
end
end
Then:
if isequal(SafeGetField(hund, 'A'), 1)
Or:
function T = CompareField(S, F, V)
if isfield(S, F)
T = isequal(S.F, V);
else
T = false;
end
end
and in the main code:
if CompareField(hund, 'A', 1)
  댓글 수: 1
Martin
Martin 2019년 1월 13일
I meant as you said
if isfield(hund, 'A')
ya. Great, thanks for answer, didnt even knew that concept of "shortcircuting"

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by