Search code examples
matlabvectorizationcell-array

Vectorized or single line evaluation of function array in MATLAB


In a previous question, a user asked about iterating over a cell array of anonymous functions. I am wondering whether there is a way to evaluate a set of functions without the explicit use of a for loop.

As an example, the following code creates an array of (simple) functions, evaluates them for a fixed value and stores the results:

fcnList = {@(x) (x+1), @(x) (x+2)};
a = 2;
for i = 1:numel(fcnList)
    y(i) = fcnList{i}(a);
end

Is there a way to do this without looping?


Solution

  • For your example, you could do the following using the cellfun function:

    fcnList = {@(x) (x+1), @(x) (x+2)};
    a = 2;
    cellfun(@(func) func(a),fcnList)
    ans =
    
       3   4
    

    Where I have created a handle called func which accepts as input a function from the fcnList variable. Each function is then evaluated for a.

    If you need to pass a vector instead of a scalar, for instance b, you will need to set the 'UniformOutput' option to false:

    b=[3 4]
    fcnList = {@(x) (x+1), @(x) (x+2)};
    cellfun(@(func) func(b),fcnList,'UniformOutput',false)
    ans =
    {
      [1,1] =
         4   5
      [1,2] =
         5   6
    }