How would I check to see if a struct field exists OR is empty?
161 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Darren Wethington
el 28 de Feb. de 2019
Respondida: Andrei Cimponeriu
el 19 de Abr. de 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 comentarios
Walter Roberson
el 28 de Feb. de 2019
Editada: Walter Roberson
el 28 de Feb. de 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.
Respuesta aceptada
Walter Roberson
el 28 de Feb. de 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 comentarios
Más respuestas (1)
Andrei Cimponeriu
el 19 de Abr. de 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 comentarios
Ver también
Categorías
Más información sobre Variables en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!