Check if a function input exists in workspace
조회 수: 23 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
답변 (2개)
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?
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!