MATLAB Answers

Why is exist(variable,'var') not seeing a variable?

9 views (last 30 days)
I have a function to which a variable is passed. The variable exists:
'signedOrNot = signed'
When I call 'exist signedOrNot var' it is found:
ans = 1
But when I use exist(signedOrNot,'var'), as I would in an if statement, it is not:
ans = 0
Any thoughts?

  0 Comments

Sign in to comment.

Accepted Answer

Fangjun Jiang
Fangjun Jiang on 24 Sep 2018
exist('signedOrNot','var')

  1 Comment

Bogdan Dzyubak
Bogdan Dzyubak on 24 Sep 2018
Right, of course... Thanks for reminding.

Sign in to comment.

More Answers (1)

Steven Lord
Steven Lord on 24 Sep 2018
This line of code tests whether the variable with the name signedOrNot exists in the workspace.
exist('signedOrNot', 'var')
This line of code tests whether the variable whose name is stored in the variable signedOrNot exists in the workspace.
exist(signedOrNot, 'var')
Compare:
% if a variable by this name exists, choose a different name
signedOrNot = 'thisVariableShouldNotExist';
passingName = exist('signedOrNot', 'var') % true, signedOrNot exists
passingContentsOfVariable = exist(signedOrNot, 'var') % false, thisVariableShouldNotExist doesn't
with:
x = 42;
signedOrNot = 'x';
passingName = exist('signedOrNot', 'var') % true, signedOrNot exists
passingContentsOfVariable = exist(signedOrNot, 'var') % true, x exists

  0 Comments

Sign in to comment.

Sign in to answer this question.