如何使用 varargin 和 varargout 包装函数? [英] How to wrap a function using varargin and varargout?

查看:29
本文介绍了如何使用 varargin 和 varargout 包装函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

小例子:

function varargout = wrapper(varargin)
varargout = someFunction(varargin);

这就是我首先要做的.但是例如,如果 someFunction = ndgrid 这会产生一个 not defined for cell arrays 错误,所以下一次尝试使用 someFunction(varargin{:}) 代替.这是一个成功的调用,但是调用 [a,b] = wrapper([1,2], [3,4]) 不会产生与直接调用 ndgrid<相同的结果/code>,那我做错了什么?

That's how I'd do it first. But for example if someFunction = ndgrid this yields a not defined for cell arrays error, so the next try was using someFunction(varargin{:}) instead. That's a successful call, but calling [a,b] = wrapper([1,2], [3,4]) does not yield the same result as a direct call to ndgrid, so what am I doing wrong?

推荐答案

实际上,Mikhail 的回答并不完全正确.如果 someFunction 是一个即使没有请求也返回一个值的函数,这就是函数指示值应该分配给 ans 的方式,Mikhail 的包装器将失败.例如,如果将 someFunction 替换为 sin 并且您比较了运行包装器和直接运行 sin ,您会看到:

Actually, Mikhail's answer is not quite right. In the case that someFunction is a function that returns a value even if none is requested, which is how a function indicates that the value should be assigned to ans, Mikhail's wrapper will fail. For example, if someFunction were replaced with sin and you compared running wrapper versus running sin directly, you'd see:

>> wrapper(0)
>> sin(0)

ans =

   0

正确的做法是

function varargout = wrapper( varargin )
[varargout{1:nargout}] = someFunction( varargin{:} ); 

之所以有效,是因为 MATLAB 索引规则中的一个鲜为人知的边缘情况,至少从 R2006a(可能更长)以来,这种情况就已经存在.这是 MATLAB 索引中的一个问题,但被认为是处理此类事情所必需的.

The reason this works is due to a little known edge case in MATLAB indexing rules that has existed precisely for this case since at least R2006a (probably longer). It is something of a wart in MATLAB indexing but was deemed necessary to handle this sort of thing.

规则是:

执行下标赋值时,如果

  • 下标赋值给未初始化的变量,AND
  • 未初始化的变量是花括号索引的,并且
  • 花括号中的索引为空,AND
  • 左侧出现在方括号内,AND
  • 右侧解析为一个值/返回一个输出

然后为未初始化的变量分配一个标量单元格,其中包含右侧返回的值.

Then the uninitialized variable is assigned a scalar cell containing the value returned by the right-hand side.

例如:

>> clear uninit % just to make sure uninit is uninitialized
>> [uninit{[]}] = sin(0)

uninit = 

    [0]

这篇关于如何使用 varargin 和 varargout 包装函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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