Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

command line - How to execute multiple statements in a MATLAB anonymous function?

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...