Combining Anonymous Functions in MATLAB

有些话、适合烂在心里 提交于 2021-02-08 04:50:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!