我想从匿名函数中调用某个函数,如
@(){fooBar(baz)}
Run Code Online (Sandbox Code Playgroud)
麻烦的是,fooBar
没有输出,这使得匿名函数抱怨.除了使fooBar
函数返回虚拟输出之外,有没有办法解决这个问题?
问题出在你的匿名函数定义中.通过将函数包含foobar(baz)
在字符之间{...}
,您正在编写一个函数,该函数必须:
foobar(baz)
cell
显然,在步骤(2)中,Matlab不能将表达式(1)的结果放在单元格中,因为(1)没有输出.
因此,只需在没有花括号的情况下定义您的函数:
myFunction = @() fooBar(baz)
Run Code Online (Sandbox Code Playgroud)
一切都应该工作正常.
为了演示一个例子,让我们fooBar
通过做一些不产生输出的东西来定义函数(例如改变一个斧头限制):
fooBar = @(axlim) set(gca,'XLim',axlim)
Run Code Online (Sandbox Code Playgroud)
我现在可以调用fooBar([0 20])
,当前轴将直接将其轴限制设置为[0 20]
如果我经常使用轴间距(例如[-5 5]),我可能会想要定义一个新函数,该函数将始终fooBar
使用相同(常用)参数调用:
fooBarPrefered = @() fooBar([-5 5])
Run Code Online (Sandbox Code Playgroud)
现在我每次打电话时fooBarPrefered()
,我的X轴限制都直接设置为[-5 5].
为了进一步证明这一点,由于调用fooBar([-5 5])
不会产生输出,如果我用花括号定义我的函数,Matlab确实会抱怨:
fooBarPrefered = @() {fooBar([-5 5])} ;
>> fooBarPrefered()
One or more output arguments not assigned during call to "set".
Error in @(axlim)set(gca,'XLim',axlim)
Error in @(){fooBar([-5,5])}
Run Code Online (Sandbox Code Playgroud)
但请注意,这与您尝试fooBar
直接在工作空间中将变量的输出分配给变量时的错误相同:
a = fooBar([0 20])
One or more output arguments not assigned during call to "set".
Error in @(axlim)set(gca,'XLim',axlim)
Run Code Online (Sandbox Code Playgroud)
底线:如果函数没有输出,请不要尝试将此输出重定向到变量或表达式.