Cumulative Sum of a Vector - Syntax

前端 未结 3 1327
夕颜
夕颜 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()"...

提交回复
热议问题