简体   繁体   中英

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. Is there a way around this besides making the fooBar function return a dummy output?

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 :

  • evaluate the expression foobar(baz)
  • Place the result of this expression into a 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).

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 = @(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]

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:

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

Now every time I call fooBarPrefered() , my axes X limits are directly set to [-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:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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