nargin vs exist

前端 未结 6 2034
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-30 06:46

Given a function like:

function foo(myParam)
if nargin<1
  myParam = \'default value\';
end % if
end % function

I\'ve seen people use so

6条回答
  •  抹茶落季
    2020-12-30 07:11

    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

    if (nargin<1) || isempty(myparam)
    
      myparam = defaultvalue;
    
    elseif
    
      ...
    
    end
    

    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.

提交回复
热议问题