matlabanonymous-functioncell-array

Evalute cell array of anonymous functions with different arity


I have a cell array of anonymous functions, all of which take different variables in general, e.g.

{@(x)x, @(x,y)x+y, @(y)y^2}

I want to evalute all of these functions for a pair of values {x,y}, i.e. do something like

{@(x)x, @(x,y)x+y, @(y)y^2}(x,y)

How can I do this in Matlab?


Edit: Since I could not find a nice solution, I manually parse the function definition now.


Solution

  • I'd loop through the functions but I'd imagine there is a more elegant and concise way. I also used the ~ placeholder so no error will propagate for too many inputs. The ~ placeholder can be used for inputs and outputs that plan to be unused.

    %Input variables%
    x = 1;
    y = 2;
    
    Functions = {@(x,~) x, @(x,y) x+y, @(~,y) y^2};
    
    %Looping through functions and evaluating%
    for Function_Index = 1: length(Functions)
       
    Functions{Function_Index}(x,y)
    
    end
    

    Using MATLAB version: R2019b