How do I check isempty when the variable might not exist without using two if statements?

77 Ansichten (letzte 30 Tage)
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?

Akzeptierte Antwort

MathWorks Support Team
MathWorks Support Team am 4 Okt. 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

Weitere Antworten (0)

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Produkte


Version

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by