문제

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.

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top