Search code examples
matlabcell-arrayfunction-handle

Call multiple functions from cells in MATLAB


I store some functions in cell, e.g. f = {@sin, @cos, @(x)x+4}.

Is it possible to call all those functions at the same time (with the same input). I mean something more efficient than using a loop.


Solution

  • As constructed, the *fun family of functions exists for this purpose (e.g., cellfun is the pertinent one here). They are other questions on the use and performance of these functions.

    However, if you construct f as a function that constructs a cell array as

    f = @(x) {sin(x), cos(x), x+4};
    

    then you can call the function more naturally: f([1,2,3]) for example. This method also avoids the need for the ('UniformOutput',false) option pair needed by cellfun for non-scalar argument.

    You can also use regular double arrays, but then you need to be wary of input shape for concatenation purposes: @(x) [sin(x), cos(x), x+4] vs. @(x) [sin(x); cos(x); x+4].