问题描述
我想做这样的事情:
>> foo = @() functionCall1() functionCall2()
所以当我说:
>> foo()
它会先执行functionCall1()
,然后再执行functionCall2()
.(我觉得我需要类似 C ,运算符)
It would execute functionCall1()
and then execute functionCall2()
. (I feel that I need something like the C , operator)
functionCall1
和 functionCall2
不一定是返回值的函数.
functionCall1
and functionCall2
are not necessarily functions that return values.
推荐答案
尝试通过命令行完成所有操作而不将函数保存在 m 文件中可能是一项复杂而混乱的工作,但这是我想出的一种方法..
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...
首先,制作您的匿名函数并将它们的<句柄.com/help/matlab/cell-arrays.html" rel="noreferrer">元胞数组:
First, make your anonymous functions and put their handles in a cell array:
fcn1 = @() ...;
fcn2 = @() ...;
fcn3 = @() ...;
fcnArray = {fcn1 fcn2 fcn3};
...或者,如果您已经定义了函数(如在 m 文件中),请将函数句柄放入元胞数组中,如下所示:
...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};
然后你可以创建一个新的匿名函数,使用内置函数调用数组中的每个函数 cellfun
和 发烧:
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.
如果 fcnArray
中的函数需要使用输入参数调用,您首先必须确保数组中的所有函数都需要相同的输入的数量.在这种情况下,以下示例显示如何使用每个输入参数调用函数数组:
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
警告语:cellfun
指出计算输出元素的 order 未指定且不应依赖.这意味着不能保证
fcn1
在 fcn2
或 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.
这篇关于如何在 MATLAB 匿名函数中执行多条语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!