3

I have a bunch of anonymous functions stored in a cell array as follows:

F = {@(x) x + 1, @(x) x * x}

I want to create a new anonymous function to add them all up and average the result given an input x. F can have arbitrary number of function handles and is generated at run time. If F is known, then it is simply f = @(x) (F{1}(x) + F{2}(x)) / length(F). But I don't know how to append all elements of F onto this new anonymous function (presumably in a loop?) How would I do this?

1
  • 2
    Have a look at cellfun Commented Nov 26, 2015 at 16:54

1 Answer 1

3

Use cellfun to define a function that evaluates each function f in F using just one line. An anonymous function handle for arbitrary F and x is as follows:

F = {@(x) x + 1, @(x) x * x};
%// Build anonymous function that evaluates each function, sums, 
%// divides by length of F
new_F = @(x,F)sum(cellfun(@(f)f(x), F)) / length(F);

Then, to evaluate, simply call:

x = 2; %// data to apply fcns on
result = new_F(x, F)
Sign up to request clarification or add additional context in comments.

1 Comment

Wow! Did not know this is valid syntax! The functional programming is strong with Matlab.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.