向量的累积总和-语法 [英] Cumulative Sum of a Vector - Syntax

查看:253
本文介绍了向量的累积总和-语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解决以下Matlab语法不起作用的原因.

I am trying to resolve why the following Matlab syntax does not work.

  1. 我有一个数组 A = [2 3 4 5 8 9 ...]
  2. 例如,我希望创建一个索引累加 s(1)= 2; s(2)= 5,s(3)= 9; ...等等
  1. I have an array A = [2 3 4 5 8 9...]
  2. I wish to create an indexed cumulative, for example s(1) = 2; s(2)=5, s(3)=9; ... and so on

有人可以解释以下原因为何

Can someone please explain why the following does not work

x = 1:10
s(x) = sum(A(1:x))

逻辑是,如果使用x为s创建向量,为什么sum函数的行为不一样?上面的代码只返回所有x的第一个元素(2).

The logic is that if a vector is created for s using x, why would not the sum function behave the same way? The above returns just the first element (2) for all x.

推荐答案

要计算累加和,应使用cumsum:

For calculating the cumulative sum, you should be using cumsum:

>> A = [2 3 4 5 8 9]

A =

     2     3     4     5     8     9

>> cumsum(A)

ans =

     2     5     9    14    22    31

问题在于1:x1,而sum减少了线性数组.要正确执行此操作,您需要一个2D数组,然后对行求和:

The issue is that 1:x is 1 and that sum reduces linear arrays. To do this properly, you need a 2d array and then sum the rows:

s(x)=sum(triu(repmat(A,[prod(size(A)) 1])'))

这篇关于向量的累积总和-语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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