Vectorization of a for loop (addition of a vector)

1 view (last 30 days)
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!

Accepted Answer

Mohammad Abouali
Mohammad Abouali on 23 Oct 2014
Edited: Mohammad Abouali on 23 Oct 2014
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

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!