Given a function like:
function foo(myParam) if nargin<1 myParam = 'default value'; end % if end % function
I’ve seen people use something like the following in the place of the nargin version
if ~exist('myParam', 'var') myParam = 'default value'; end %if
I’m wondering if there is any preference either way?
The ‘~exist…’ version to me has the advantage that if I change the order of my function parameters then it should still work. However my concern with this approach is that I might inadvertently pick up variables that are defined globally or in the scope of a surrounding function in the case of nested functions.
Any thoughts on the issue?
Both should work. But…
Exist tends to be slow, since it must look through your workspace for the variable in question. When you write error checks like this, you don’t want them to suck up CPU cycles. The test against nargin is a simple test against a single numeric value.
I’d also generally suggest a more extensive test. Something like
Inside the elseif branch, I’ll put a set of additional tests to see if the parameter has the expected size, shape, class of variable, etc. If those tests fail, I’ll return a friendly error message that explains what was wrong.