Check if a function input exists in workspace

23 Ansichten (letzte 30 Tage)
Eric M
Eric M am 28 Jan. 2016
Bearbeitet: Stephen23 am 28 Jan. 2016
Dear all,
Simple question about checking if a variable exists. I want my function to check if a given parameter exists in the workspace before attempting to modify it. If it doesn't exist, my function should behave differently.
Something like this:
function out1 = myFun(in1,in2)
if( exist(in1, 'var') )
out1 = in1;
else
out1 = in2;
end
Unfortunately, exist requires the varname in a string. I'm sorry to say that I don't know how to get around this. I've read that using eval should be avoided, otherwise I considered making the first input called as a string, e.g. myFun('in1',in2)...
function out1 = myFun(in1,in2)
if( exist(in1, 'var') )
out1 = eval(in1);
else
out1 = in2;
end
I tried using exist( inputname(1), 'var' ) without any luck. Possibly, this is a scope issue that eludes me. Could someone point me in the right direction?
Regards, Eric

Antworten (2)

Stephen23
Stephen23 am 28 Jan. 2016
Bearbeitet: Stephen23 am 28 Jan. 2016
The fastest and most reliable way to check which inputs have been provided is to use nargin, like this:
function out1 = myFun(in1,in2)
switch nargin
case 0
...
case 1
...
otherwise
...
end
end
If this variable is simply popping into existence in your workspace (via eval, assignin, or one of the other awful methods that beginners insist on using to pass variable between workspace), then you are learning why these methods are awful ways to pass variables:
How does it end up in the workspace without you knowing its name, or whether it exists?

Star Strider
Star Strider am 28 Jan. 2016
I would use the who or whos function to check for workspace variables.
For example:
variables = who

Kategorien

Mehr zu Variables finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by