Andrew
Andrew

Reputation: 1851

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), ...]

Upvotes: 2

Views: 2597

Answers (3)

mars
mars

Reputation: 804

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

Upvotes: 4

Jonas
Jonas

Reputation: 74940

You can use str2func to create your anonymous function without having to resort to eval:

ca = {@sin,@cos,@tan}
%# create a string, using sprintf for any number
%# of functions in ca
cc = str2func(['@(x)[',sprintf('ca{%i}(x) ',1:length(ca)),']'])

cc = 
    @(x)[ca{1}(x),ca{2}(x),ca{3}(x)]

cc(pi/4)

ans =
    0.7071    0.7071    1.0000

Upvotes: 1

Andrew
Andrew

Reputation: 1851

I found that by naming each function, I could get them to fit into an array. I don't quite understand why this works, but it did.

f = ca{1};
g = ca{2};

h = @(X) [f(X), g(X)];

I feel like there should be an easier way to do this. Because I am dealing with an unknown number of functions, I had to use eval() to create the variables, which is a bad sign. On the other hand, calling the new function works like it is supposed to.

Upvotes: 0

Related Questions