How do I check isempty when the variable might not exist without using two if statements?
45 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
MathWorks Support Team
le 4 Oct 2018
Réponse apportée : MathWorks Support Team
le 4 Oct 2018
Often times, particularly when parsing inputs, I find that I first need to determine if a variable exists, before I can then see if there is anything in it. This results in a double nested if statement where purpose-wise, the functionality is really singular. I simply want to check if the variable is empty.
For example:
if exist('x')
if isempty(x)
disp('Exists and empty!')
end
end
As you can see, in order to tell whether a certain variable is empty, I first have to make sure that it even exists, or else the isempty function errors out if the variable does not exist. Is there a way to do this without needing two nested if statements?
Réponse acceptée
MathWorks Support Team
le 4 Oct 2018
This can be done by using an AND statement in the "if" statement and making sure the "exist" check comes first. As long as the "exist" check is first, MATLAB will only continue on to the rest of the "if" statement ("isempty") if it is true. This way "isempty" will not error.
if exist('x') && isempty(x)
disp('Exists and empty!')
end
0 commentaires
Plus de réponses (0)
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!