How would I check to see if a struct field exists OR is empty?
163 views (last 30 days)
Show older comments
Darren Wethington
on 28 Feb 2019
Answered: Andrei Cimponeriu
on 19 Apr 2024
I'd like to program a conditional statement that checks if an optional events function for an ODE was triggered. This would look something like:
if ~isfield(sol,'xe') || isempty(sol.xe)
fprintf('Event Not Triggered\n')
else
fprintf('Event Triggered\n')
end
However, this fails if sol.xe doesn't exist because no events function was specified. In the interest of shorter/cleaner code, I'd like to avoid this solution:
if isfield(sol,'xe')
if isempty(sol.xe)
fprintf('Event Not Triggered\n')
else
fprintf('Event Triggered\n')
end
else
fprintf('Event Not Triggered\n')
end
Is there a better way to do this?
3 Comments
Walter Roberson
on 28 Feb 2019
Edited: Walter Roberson
on 28 Feb 2019
Conditions are evaluated left to right except when there are (), in which case everything before the () is evaluated and then the inside of the () is evaluated as a group.
When the || or && operators are used, the values on the two sides must be scalar (even empty is not permitted), and the calculation within that group stops as soon as it figures out the answer-- so
if A||B
declares success if A is true, without executing B, but continuing on to B if A is false; and
if A&&B
declares failure if A is false, without executing B, but continuing on to B if A is true.
This is not the case for the & or | operators: they execute both sides anyhow.
Accepted Answer
Walter Roberson
on 28 Feb 2019
You might find this clearer:
if isfield(sol,'xe') && ~isempty(sol.xe)
fprintf('Event Triggered\n')
else
fprintf('Event Not Triggered\n')
end
However, your existing code is fine. In your existing code, if there is no xe field then the ~isfield is true and the || short-circuits and you get the Not Triggered. If there is an xe field then the ~isfield is false but you are in a || so the second test is performed which is about emptiness. You can only reach the Triggered message if there is an xe field and it is not empty, which is what you want.
0 Comments
More Answers (1)
Andrei Cimponeriu
on 19 Apr 2024
Hi,
For a structure named TT having one of the fields called FF, you could try this:
if ismember('FF',fieldnames(TT)) ...
Best regards,
Andrei
0 Comments
See Also
Categories
Find more on Variables 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!