Vectorization of a for loop (addition of a vector)

1 次查看(过去 30 天)
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