Search code examples
matlabanonymous-functioncell-array

Combining Anonymous Functions in MATLAB


I have a cell array of anonymous function handles, and would like to create one anonymous function that returns the vector containing the output of each function.

What I have:

ca = {@(X) f(X), @(X)g(X), ...}

What I want:

h = @(X) [ca{1}(X), ca{2}(X), ...]

Solution

  • Yet another way to it:

    You can use cellfun to apply a function to each cell array element, which gives you a vector with the respective results. The trick is to apply a function that plugs some value into the function handle that is stored in the cell array.

    ca = {@(X) X, @(X) X+1, @(X) X^2};
    h=@(x) cellfun(@(y) y(x), ca);
    

    gives

    >> h(4)
    
    ans =
         4     5    16