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

78 ビュー (過去 30 日間)
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?

採用された回答

MathWorks Support Team
MathWorks Support Team 2018 年 10 月 4 日
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 件)

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by