如何在MATLAB中使用累计求和? [英] How do I get a cumulative sum using cumsum in MATLAB?

查看:141
本文介绍了如何在MATLAB中使用累计求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码

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

end

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

我希望1 + 2 + 3 + 4 + 5 = 15,所以我会在最后打印15.

I expected 1 + 2 + 3 + 4 + 5 = 15 so I would print 15 at the end.

但是它输出了5.000000.

But it output 5.000000.

如果我在for循环外编写代码"a = cumsum(b)",则不会计算出

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

如何获取我想要的值1 + 2 + 3 + 4 + 5?

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

谢谢

推荐答案

cumsum 执行类似于积分的操作,其中输出的每个元素都是直到该位置(包括)的所有元素的总和.输入向量.

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.

您的代码不起作用,因为您将单个值传递给 cumsum ,并且没有保存上一个结果的机制,因此最终只能有一个值,即最后一个- 5 .

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.

您无需为此循环,甚至不需要 cumsum -只需编写 sum(1:5)即可获得所需的结果.

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

这篇关于如何在MATLAB中使用累计求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆