Cumulative Sum of a Vector - Syntax

前端 未结 3 1326
夕颜
夕颜 2021-01-25 08:42

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

  1. I have an array A = [2 3 4 5 8 9...]
  2. I wish to create an indexed cumulative, for
相关标签:
3条回答
  • 2021-01-25 09:35

    You are asking two questions, really. One is - how do I compute the cumulative sum. @SouldEc's answer already shows how the cumsum function does that. Your other question is

    Can someone please explain why the following does not work

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

    It is reasonable - you think that the vector expansion should turn

    1:x
    

    into

    1:1
    1:2
    1:3
    1:4
    

    etc. But in fact the arguments on either side of the colon operator must be scalars - they cannot be vectors themselves. I'm surprised that you say Matlab isn't throwing an error with your two lines of code - I would have expected that it would (I just tested this on Freemat, and it complained...)

    So the more interesting question is - how would you create those vectors (if you didn't know about / want to use cumsum)?

    Here, we could use arrayfun. It evaluates a function with an array as input element-by-element; this can be useful for a situation like this. So if we write

    x = 1:10;
    s = arrayfun(@(n)sum(A(1:n)), x);
    

    This will loop over all values of x, substitute them into the function sum(A(1:n)), and voila - your problem is solved.

    But really - the right answer is "use cumsum()"...

    0 讨论(0)
  • 2021-01-25 09:36

    Actually what you are doing is s(1:10)= sum(A(1:[1,2,3...10])) what you should do is

    for i=1:10
        s(i)=sum(A(1:i))
    end
    

    hope it will help you

    0 讨论(0)
  • 2021-01-25 09:45

    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
    

    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])'))
    
    0 讨论(0)
提交回复
热议问题