How do I get a cumulative sum using cumsum in MATLAB?

后端 未结 2 720
旧巷少年郎
旧巷少年郎 2021-01-29 10:46

This is code

for i = 1 : 5
    b = i;
    a=cumsum(b);

end

fprintf(\'%f \\n\', a);

I expected 1 + 2 + 3 + 4 + 5 = 15 so I would print 15 at t

2条回答
  •  生来不讨喜
    2021-01-29 11:12

    cumsum performs something like integration, where each element of the output is the sum of all elements up to that position (including) of the input vector.

    Your code doesn't work because you pass a single value into cumsum and there is no mechanism by which the previous result is saved, so you end up having only a single value, which is the last one - 5.

    You don't need a loop for this, nor even cumsum - just write sum(1:5) to get the desired result.

提交回复
热议问题