Building an anonymous function from an array of anonymous functions

Hello.
I have a question about anonymous function and their combinations. Lets say, I have a cell-array of 100 anonymous functions and a double array with 100 values. What I would like to do now is to multiply each anonymous function with a value of the double array and sum all of them up. The result should be a anonymous function. I have a solution, which is really slow and I hope there is a better one. This is my solution for a simple test problem:
anonymousfunctionarray = cell(100,1);
for ii = 1:100
anonymousfunctionarray{ii,1}=@(x) x*ii;
end
doublearray = (1:100)';
finalfun =@(x)doublearray(1,1)*anonymousfunctionarray{1,1}(x);
for ii = 2:100
finalfun =@(x)finalfun(x)+doublearray(ii,1)*anonymousfunctionarray{ii,1}(x);
end
Is there a better way to do that? Also, I want to store the resulting function (finalfun) at the end and load it again later. Thank You.

Answers (1)

finalfun = @(x) sum(arrayfun(@(K) doublearray(K).*anonymousfunctionarray{K}(x), 1:length(doublearray)));

3 Comments

Thank you very much for your answer. It is already nearly what I need. My function is actually dependent on 2 variables (x,y), which is not the problem. The problem is, that the input parameters x and y are matrices and not scalar. Therefore, I get the error "...Set 'UniformOutput' to false...". Of course if I do that I get the result in cell-arrays and "sum" want work anymore. Is there a nice way to solve that, without converting all cells to arrays? Thank you.
UniformOutput false, cell2mat() the result of arrayfun, sum() over the appropriate dimension.
Thank you for the answer again. Is this the best way to do it?
finalfun = @(x)reshape(sum(reshape(cell2mat(arrayfun(@(K) doublearray(K).*anonymousfunctionarray{K}(x), 1:length(doublearray),'UniformOutput',0)),length(x(:,1))*length(x(1,:)),length(doublearray)),2),length(x(:,1)),length(x(1,:)));

Sign in to comment.

Categories

Find more on Programming in Help Center and File Exchange

Asked:

on 6 Aug 2015

Commented:

on 10 Aug 2015

Community Treasure Hunt

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

Start Hunting!