Building an anonymous function from an array of anonymous functions
Mostrar comentarios más antiguos
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.
Respuestas (1)
Walter Roberson
el 7 de Ag. de 2015
finalfun = @(x) sum(arrayfun(@(K) doublearray(K).*anonymousfunctionarray{K}(x), 1:length(doublearray)));
3 comentarios
Michael
el 7 de Ag. de 2015
Walter Roberson
el 7 de Ag. de 2015
UniformOutput false, cell2mat() the result of arrayfun, sum() over the appropriate dimension.
Michael
el 10 de Ag. de 2015
Categorías
Más información sobre Structures en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!