How would I check to see if a struct field exists OR is empty?
161 次查看(过去 30 天)
显示 更早的评论
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 个评论
Walter Roberson
2019-2-28
编辑:Walter Roberson
2019-2-28
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.
采纳的回答
Walter Roberson
2019-2-28
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 个评论
更多回答(1 个)
Andrei Cimponeriu
2024-4-19
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 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!