Vectorization of a for loop (addition of a vector)

1 回表示 (過去 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by