问题
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), ...]
回答1:
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
回答2:
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
回答3:
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.
来源:https://stackoverflow.com/questions/11232323/combining-anonymous-functions-in-matlab