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

78 visualizaciones (últimos 30 días)
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?

Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 4 de Oct. de 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

Más respuestas (0)

Categorías

Más información sobre Programming en Help Center y File Exchange.

Productos


Versión

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by