Creating new vector wich adds previous value with for loop

8 ビュー (過去 30 日間)
Johan  Lilliestråle
Johan Lilliestråle 2015 年 2 月 19 日
Hey everybody
Lets say that I have the vector:
a = [1, 1, ,1 ,1];
Then I want to create a new vector which adds all previous values, call it b
b = [1, 2, 3, 4];
the first value is the sum of the a(1,1), the second value is the sum of the previous value (which was 1) plus the new a(1,2) = 1. Then we get 1+1 =2. The third value is th1 sum of the previous value 2 and a(1,3) = 1 which is 1+2=3. And so on and on. If i want to do this in a for loop would that be:
a = [1, 1, ,1 ,1];
b = zeros(1,4)
for i=1:4;
b = 0;
b(i) = b + a(i);
end
I have tried that code but it doesnt work. If anyone a suggestion how to create an foor loop for this problem I would be grateful to see it. Cheers

回答 (2 件)

James Tursa
James Tursa 2015 年 2 月 19 日
編集済み: James Tursa 2015 年 2 月 19 日
b = cumsum(a);
To fix your explicit loop, don't set b = 0 at each iteration, and use proper indexing into the vectors. E.g.,
a = [1, 1, 1, 1];
b = a;
for i=2:4;
b(i) = b(i-1) + a(i);
end
  1 件のコメント
Johan  Lilliestråle
Johan Lilliestråle 2015 年 2 月 19 日
Thank you very much, sometimes it is hard to see the simplicity in things. Have a good day

サインインしてコメントする。


Star Strider
Star Strider 2015 年 2 月 19 日
There’s an easier way to do it with the repmat and triu functions:
a_sum = sum(triu(repmat(a, 4, 1)));
This will give you exactly what you want.
  1 件のコメント
Johan  Lilliestråle
Johan Lilliestråle 2015 年 2 月 19 日
Oh great with an inbuilt function, easy and fast :)

サインインしてコメントする。

カテゴリ

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