# conditional logic inside conditional logic

1 view (last 30 days)
Martin on 13 Jan 2019
Commented: Martin on 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...

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

### Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!
{"ft_lang_label":"__label__en","ft_lang_prob":0.80672956,"math_prob":0.65753305,"size":1496,"snap":"2023-14-2023-23","text_gpt3_token_len":436,"char_repetition_ratio":0.12935656,"word_repetition_ratio":0.030303031,"special_character_ratio":0.28074867,"punctuation_ratio":0.15662651,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.97705835,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-03-30T01:21:42Z\",\"WARC-Record-ID\":\"<urn:uuid:bd46494c-46e2-4f2d-a205-c13b1163553d>\",\"Content-Length\":\"129921\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:45f05ea0-7be0-4e4c-8fdf-1bfe34ffe716>\",\"WARC-Concurrent-To\":\"<urn:uuid:c91a840e-0dda-41ed-b0db-14e013391696>\",\"WARC-IP-Address\":\"23.34.160.82\",\"WARC-Target-URI\":\"https://it.mathworks.com/matlabcentral/answers/439578-conditional-logic-inside-conditional-logic?s_tid=prof_contriblnk\",\"WARC-Payload-Digest\":\"sha1:4HZYCPTJGFGTTMTHRO2TDCJ7JQE6XPIO\",\"WARC-Block-Digest\":\"sha1:U4ZQL7WQUBXLBXUEJSL6NOCKNVPXBFRS\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-14/CC-MAIN-2023-14_segments_1679296949093.14_warc_CC-MAIN-20230330004340-20230330034340-00148.warc.gz\"}"}