1

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.

Void
  • 153
  • 4
  • 12

1 Answers1

1

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.

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • It didn't give me correct answer. Could you elaborate on it? Thanks.I found a cumbersome way to work around: g=@(x)cellfun(@(f)f(x),f);gg=@(x)cumsum(g(x)).Now gg(x) gives me what I wanted. Is there any smarter way to do this though? – Void Mar 27 '14 at 22:11
  • @Void Sorry, there was a mistake. Please see now – Luis Mendo Mar 27 '14 at 22:14