conditional logic inside conditional logic

2 ビュー (過去 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by