Building an anonymous function from an array of anonymous functions
Show older comments
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)
Walter Roberson
on 7 Aug 2015
finalfun = @(x) sum(arrayfun(@(K) doublearray(K).*anonymousfunctionarray{K}(x), 1:length(doublearray)));
3 Comments
Michael
on 7 Aug 2015
Walter Roberson
on 7 Aug 2015
UniformOutput false, cell2mat() the result of arrayfun, sum() over the appropriate dimension.
Michael
on 10 Aug 2015
Categories
Find more on Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!