Vectorization of a for loop (addition of a vector)

1 visualizzazione (ultimi 30 giorni)
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!

Risposta accettata

Mohammad Abouali
Mohammad Abouali il 23 Ott 2014
Modificato: Mohammad Abouali il 23 Ott 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

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by