I am trying to resolve why the following Matlab syntax does not work.
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()
"...
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
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])'))