conditional logic inside conditional logic

2 vues (au cours des 30 derniers jours)
Martin
Martin le 13 Jan 2019
Commenté : Martin le 13 Jan 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...

Réponse acceptée

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

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by