Check if a function input exists in workspace

조회 수: 23 (최근 30일)
Eric M
Eric M 2016년 1월 28일
편집: Stephen23 2016년 1월 28일
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

답변 (2개)

Stephen23
Stephen23 2016년 1월 28일
편집: Stephen23 2016년 1월 28일
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 2016년 1월 28일
I would use the who or whos function to check for workspace variables.
For example:
variables = who

카테고리

Help CenterFile Exchange에서 Variables에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by