conditional logic inside conditional logic

1 visualizzazione (ultimi 30 giorni)
Martin
Martin il 13 Gen 2019
Commentato: Martin il 13 Gen 2019
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...

Risposta accettata

Jan
Jan il 13 Gen 2019
Modificato: Jan il 13 Gen 2019
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 Commento
Martin
Martin il 13 Gen 2019
I meant as you said
if isfield(hund, 'A')
ya. Great, thanks for answer, didnt even knew that concept of "shortcircuting"

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by