简体   繁体   English

Matlab:调用函数,该函数没有匿名函数的输出

[英]Matlab: Call function that has no outputs from an anonymous function

I'd like to call a certain function from within an anonymous function, as in 我想从匿名函数中调用某个函数,例如

@(){fooBar(baz)}

Trouble is, fooBar has no outputs, which makes the anonymous function complain. 麻烦的是, fooBar没有输出,这使匿名函数抱怨。 Is there a way around this besides making the fooBar function return a dummy output? 除了使fooBar函数返回虚拟输出之外,还有其他方法吗?

The problem is in your anonymous function definition. 问题出在您的匿名函数定义中。 By enclosing your function foobar(baz) between the characters {...} , you are programming a function which has to : 通过将函数foobar(baz)在字符{...} ,您正在编写必须具有以下功能的函数:

  • evaluate the expression foobar(baz) 计算表达式foobar(baz)
  • Place the result of this expression into a cell 将该表达式的结果放入cell
  • return the cell 返回细胞

Obviously in step (2) Matlab cannot place the result of the expression (1) in a cell because there is no output from (1). 显然,在步骤(2)中,Matlab无法将表达式(1)的结果放入单元格中,因为(1)没有输出。

So simply define your function without the curly braces: 因此,只需定义没有花括号的函数即可:

myFunction = @() fooBar(baz)

and everything should work ok. 一切应该正常。


To demonstrate with an example, let's define the function fooBar by doing something which does not produce an output (change an axe limits for example): 为了举例说明,让我们通过做一些不产生输出的事情来定义函数fooBar (例如,更改ax限制):

fooBar = @(axlim) set(gca,'XLim',axlim) 

I can now call fooBar([0 20]) and the current axes will directly have its axes limits set to [0 20] 我现在可以调用fooBar([0 20]) ,并且当前轴将直接将其轴限制设置为[0 20]

If there is an axis span which I use often ([-5 5] for example), I could be tempted to define a new function which will always call fooBar with the same (often used) parameters: 如果有一个我经常使用的轴跨度(例如[-5 5]),我很想定义一个新函数,该函数将始终使用相同(经常使用)的参数调用fooBar

fooBarPrefered = @() fooBar([-5 5])

Now every time I call fooBarPrefered() , my axes X limits are directly set to [-5 5]. 现在,每次我调用fooBarPrefered() ,我的轴X限制都直接设置为[-5 5]。


To further prove the point, since calling fooBar([-5 5]) does not produce an output, Matlab will indeed complain if I define my function with curly braces: 为了进一步说明这一点,由于调用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])}

But note that this is the same error than if you were trying to assign the output of fooBar to a variable directly in the workspace: 但是请注意,与尝试将fooBar的输出直接分配给工作空间中的变量时,这是相同的错误:

a = fooBar([0 20])
One or more output arguments not assigned during call to "set".
Error in @(axlim)set(gca,'XLim',axlim)

Bottom line: If a function does not have an output, do not try to redirect this output to a variable or an expression. 底线:如果函数没有输出,请勿尝试将此输出重定向到变量或表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM