필터 지우기
필터 지우기

cumulative sum of an array

조회 수: 4 (최근 30일)
Lanceric Tse
Lanceric Tse 2018년 8월 13일
댓글: James Tursa 2018년 8월 13일
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
James Tursa
James Tursa 2018년 8월 13일
What is your question? For the given b, what would be your desired output?
Lanceric Tse
Lanceric Tse 2018년 8월 13일
편집: Lanceric Tse 2018년 8월 13일
The desired output with be an array S, which contains the cumulative sums of every 5 values.
The code under the %% is how I would get the cumulative sum of an array of 5 values

댓글을 달려면 로그인하십시오.

채택된 답변

Matt J
Matt J 2018년 8월 13일
편집: Matt J 2018년 8월 13일
br=reshape(b,5,[]);
S=reshape( cumsum(br-mean(br)) ,1,[])
  댓글 수: 1
James Tursa
James Tursa 2018년 8월 13일
And, for older versions of MATLAB
S = reshape( cumsum(bsxfun(@minus,br,mean(br))) ,1,[])

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

dpb
dpb 2018년 8월 13일
편집: dpb 2018년 8월 13일
>> 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
Lanceric Tse
Lanceric Tse 2018년 8월 13일
I'm looking for the cumulative sum, not sum
dpb
dpb 2018년 8월 13일
Sorry, typo...the fix should be obvious... :)

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by