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

4 次查看（过去 30 天）
Leo Simon 2021-12-11

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 2021-12-15
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);
##### 1 个评论显示 无隐藏 无
Leo Simon 2021-12-15
Perfect, thanks very much

### 类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!