2

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

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

In my experience cellfun (or matfun) is very efficient in iterating over arrays. This is probably the fastest way to do this.
1

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

Comments

0

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.

Comments

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.