How to execute multiple statements in a MATLAB anonymous function?

Daniel LeCheminant picture Daniel LeCheminant · Feb 17, 2009 · Viewed 20.9k times · Source

I'd like to do something like this:

>> foo = @() functionCall1() functionCall2()

So that when I said:

>> foo()

It would execute functionCall1() and then execute functionCall2(). (I feel that I need something like the C , operator)

EDIT:

functionCall1 and functionCall2 are not necessarily functions that return values.

Answer

gnovice picture gnovice · Feb 17, 2009

Trying to do everything via the command line without saving functions in m-files may be a complicated and messy endeavor, but here's one way I came up with...

First, make your anonymous functions and put their handles in a cell array:

fcn1 = @() ...;
fcn2 = @() ...;
fcn3 = @() ...;
fcnArray = {fcn1 fcn2 fcn3};

...or, if you have functions already defined (like in m-files), place the function handles in a cell array like so:

fcnArray = {@fcn1 @fcn2 @fcn3};

Then you can make a new anonymous function that calls each function in the array using the built-in functions cellfun and feval:

foo = @() cellfun(@feval,fcnArray);

Although funny-looking, it works.

EDIT: If the functions in fcnArray need to be called with input arguments, you would first have to make sure that ALL of the functions in the array require THE SAME number of inputs. In that case, the following example shows how to call the array of functions with one input argument each:

foo = @(x) cellfun(@feval,fcnArray,x);
inArgs = {1 'a' [1 2 3]};
foo(inArgs);  %# Passes 1 to fcn1, 'a' to fcn2, and [1 2 3] to fcn3


WORD OF WARNING: The documentation for cellfun states that the order in which the output elements are computed is not specified and should not be relied upon. This means that there are no guarantees that fcn1 gets evaluated before fcn2 or fcn3. If order matters, the above solution shouldn't be used.