Question

I have a cell of function handles:

f{1}=@(x)a1(x);
f{2}=@(x)a2(x);
...
f{N}=@(x)aN(x);

N is a large number here. What is the most convenient way to perform cumulative sum on all these function handles? e.g. I want to have a cell of new function g{} with:

g{1}=f{1};
g{2}=f{1}+f{2};
...
g{N}=f{1}+...+f{N}.

Thanks.

Was it helpful?

Solution

If you can do with a single function g that returns the cumulative sum for scalar x:

g = @(x) cumsum(cellfun(@(y) y(x), f))

Example:

f{1} = @(x) x;
f{2} = @(x) x^2;
f{3} = @(x) x^3;
g = @(x) cumsum(cellfun(@(y) y(x), f))
g(3)
ans =
     3    12    39

Explanation: cellfun takes each component function f{1}, f{2} etc and returns the result of evaluating that function at x. The result for each function should be scalar. The cumulative sum of all those values is then computed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top