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

75 views (last 30 days)
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?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 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

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!