MATLAB: How to check to see if a struct field exists OR is empty

conditionalevents functionexistsMATLABstruct

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?

Best Answer

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.