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

后端 未结 2 723
旧巷少年郎
旧巷少年郎 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 10:58

    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?

提交回复
热议问题