nargin vs存在 [英] nargin vs exist

查看:72
本文介绍了nargin vs存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出类似的功能

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

我已经看到人们在nargin版本中使用以下内容

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?

对我来说,〜exist ..."版本的优点是,如果我更改函数参数的顺序,则它应该仍然可以工作.但是,我对这种方法的担心是,在嵌套函数的情况下,我可能会无意间选择全局定义的变量或周围函数范围内的变量.

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.

对此问题有何想法?

推荐答案

两者都应该起作用.但是...

Both should work. But...

Exist的运行速度通常很慢,因为它必须在您的工作空间中查找有问题的变量.当您像这样编写错误检查时,您不希望它们占用CPU周期.对nargin的测试是对单个数值的简单测试.

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

在elseif分支中,我将进行一组附加测试,以查看参数是否具有预期的大小,形状,变量类等.如果这些测试失败,我将返回一条友好的错误消息,说明怎么了.

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.

这篇关于nargin vs存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆