# Construct a single anonymous function from a cell array of anonymous functions

5 views (last 30 days)
Leo Simon on 11 Dec 2021
Commented: Leo Simon on 15 Dec 2021
I want to run a double loop that creates an anonymous function
h
consisting of the cell array of anonymous functions f . I can do it long-hand, the way that I constructed
g
but that's obviously hopelessly inefficient when f has a large size. I presume I need to use arrayfun but the examples that matlab provides don't help me. Thanks for any suggestions.
Here's my example for how I constructed g.
function nothing
syms a b c d
f{1,1}= @(a,b,c,d) a;
f{1,2}= @(a,b,c,d) b;
f{2,1}= @(a,b,c,d) c;
f{2,2}= @(a,b,c,d) d;
g = @(a,b,c,d)[ f{1,1}(a,b,c,d),f{1,2}(a,b,c,d);f{2,1}(a,b,c,d),f{2,2}(a,b,c,d)];
g(1,2,3,4)
keyboard;

Voss on 15 Dec 2021
If f is a cell array of handles to functions that return a scalar result, then you can use cellfun and feval to achieve the result you want:
h = @(a,b,c,d)cellfun(@(x)feval(x,a,b,c,d),f);
Leo Simon on 15 Dec 2021
Perfect, thanks very much