cumulative sum of an array
Show older comments
Hi, so I have an array,b, I need to find the cumulative sums for every 5 values.
To calculate the cumulative sum S of an array a with 5 values
b=[1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0];
a=[1 2 3 4 5];
amean=mean2(a);
S=zeros([1 length(a)]);
S(1)=a(1)-amean
for i=2:5
S(i)=S(i-1)+(a(i)-amean)
end
S=-2 -3 -3 -2 0
The result for b should look like S = -2 -3 -3 -2 0 0 1 3 6 0 -2 -3 -3 -2 0 0 1 3 6 0
2 Comments
James Tursa
on 13 Aug 2018
What is your question? For the given b, what would be your desired output?
Lanceric Tse
on 13 Aug 2018
Edited: Lanceric Tse
on 13 Aug 2018
Accepted Answer
More Answers (1)
>> N
N =
5
>> S=sum(reshape(b,[],length(b)/N))
S =
15 30 15 30
>>
>> S=cumsum(reshape(b,[],length(b)/N))
S =
1 6 1 6
3 13 3 13
6 21 6 21
10 30 10 30
15 30 15 30
>>
2 Comments
Lanceric Tse
on 13 Aug 2018
dpb
on 13 Aug 2018
Sorry, typo...the fix should be obvious... :)
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!