필터 지우기
필터 지우기

Vectorization of a for loop (addition of a vector)

조회 수: 4 (최근 30일)
David
David 2014년 10월 23일
편집: Mohammad Abouali 2014년 10월 23일
Hello MATLAB community,
I have a question concerning the vectorization of a for loop to speed up my code. What I have is a vector, let´s say:
a = [1 2 3 4 5 6 7 8 ]
What I want to do is to create a vector, which makes an addition of all values in the vector to the point which I am actually at. In this case it would be:
a_new = [1 3 6 10 15 21 28 36]
It´s no problem to code this with a for loop.
s_neu = zeros (1,length(s),'double');
s_neu(1,1) = s(1,1);
for i = 2:length(s)
s_neu(1,i) = s_neu(1,i-1)+s(1,i);
end
Do anyone of you know, how to code this without the for loop? Thank you very much!

채택된 답변

Mohammad Abouali
Mohammad Abouali 2014년 10월 23일
편집: Mohammad Abouali 2014년 10월 23일
This is cumulative sum so use cumsum function
a = [1 2 3 4 5 6 7 8 ]
a_new=cumsum(a)
a_new =
1 3 6 10 15 21 28 36

추가 답변 (0개)

카테고리

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