Sum of previous 5 numbers

2 ビュー (過去 30 日間)
Gokhan Kayan
Gokhan Kayan 2021 年 10 月 23 日
コメント済み: Gokhan Kayan 2021 年 10 月 23 日
A=[2 3 4 5 6 7 8 9 10 8 5];
I want to calculate sum of 5 previous values for A(i)
so my new matrix should be like this
B=[0 2 5 9 14 20 25 30 35 40 42 ];
As there is no previous 5 value before A(1)=2 so B(1)=0, There is one value before A(2) and it is A(1). Therefore B(2)=A(1)=2. There are two values before A(3) so B(3)=2+3=5. For A(9)=10, previous 5 values are 5 + 6 + 7+ 8+ 9 so B(9)=35. How can I do this summation. Thanks for the help.

採用された回答

Walter Roberson
Walter Roberson 2021 年 10 月 23 日
編集済み: Walter Roberson 2021 年 10 月 23 日
A=[2 3 4 5 6 7 8 9 10 8 5];
B=[0 2 5 9 14 20 25 30 35 40 42 ];
N = 5;
C = movsum([0 A(1:end-1)], [(N-1) 0])
C = 1×11
0 2 5 9 14 20 25 30 35 40 42
isequal(C, B)
ans = logical
1
  2 件のコメント
Walter Roberson
Walter Roberson 2021 年 10 月 23 日
編集済み: Walter Roberson 2021 年 10 月 23 日
A=[2 3 4 5 6 7 8 9 10 8 5];
B=[0 2 5 9 14 20 25 30 35 40 42 ];
N = 5;
C = conv(A, [0, ones(1,N)]);
C = C(1:end-N)
C = 1×11
0 2 5 9 14 20 25 30 35 40 42
isequal(C, B)
ans = logical
1
Gokhan Kayan
Gokhan Kayan 2021 年 10 月 23 日
Thanks for the reply Walter Robenson, this is what I exactly want :)

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by