필터 지우기
필터 지우기

Summation in a for loop without cumulitive

조회 수: 1 (최근 30일)
Ot
Ot 2014년 2월 26일
답변: Jos (10584) 2014년 2월 26일
I have a very simple question.
I want to summate the variable A for a certain interval + and - B.
for i=(b+1):length((a)-b)
C(i) = sum(a(i-b):(i+b));
end
This loop works, however the output that I get is a cumulative sum of all the previous. So I get an exponential increase. However I would like to just have the sum over the interval -b:b for all values of i. So no cummulation.

채택된 답변

Iain
Iain 2014년 2월 26일
C(i) = sum( a([i-b]:[i+b]) )
That puts into C(i), the sum of the (i-b)th index of a, to the (i+b)th index of a.
What you had, put into C(i), the sum of the (i-b)th index of a to (i+b)
  댓글 수: 2
Ot
Ot 2014년 2월 26일
Based on your remark I changed it to:
for i=(b+1):length((a)-b)
C(i) = sum(a([i-b]:[i+b]))
end
However now I get an error: ??? Index exceeds matrix dimensions.
Iain
Iain 2014년 2월 26일
If i+b is bigger than the length of a, you'll get that error.
length((a)-b) should be (length(a)-b)

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

추가 답변 (1개)

Jos (10584)
Jos (10584) 2014년 2월 26일
Another solution:
% hide the for-loop
% A is the array, B is a scalar
A = randperm(10)
B = 2
C1 = arrayfun(@(x) sum(A(x-B:x+B)), B+1:numel(A)-B)
% and yet another solution
cumA = cumsum(A)
C2 = cumA(2*B+1:end) - [0 cumA(1:end-2*B)]

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by