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

假装没事ソ 提交于 2021-02-05 12:21:59

问题


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 the end.

But it output 5.000000.

If i code "a = cumsum (b)" outside the for loop, it will not be calculated

How can I get the value I want 1 + 2 + 3 + 4 + 5?

Thanks you


回答1:


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.




回答2:


This is not how cumsum works. It takes the cumulative sum of an array the example below may explain better

a = 1:5;
b = cumsum(a); % b = [1, 3, 6, 10, 15]
c = sum(a) % add up all the elements c = 15

Does that help?



来源:https://stackoverflow.com/questions/50151489/how-do-i-get-a-cumulative-sum-using-cumsum-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!