How to sum an array over time

7 ビュー (過去 30 日間)
Vezzaz
Vezzaz 2020 年 11 月 6 日
コメント済み: Dave B 2020 年 11 月 6 日
I am new to coding and I have no idea what to actually call the problem I have so I cant look to see if a solution is posted. I have an array of 224 data points(made a huge array cause my text file was not uploading) and I need to make a graph of a sum of each points. So I need the first number in my array to be the initial value then add the second number to it and plot the sum of those two. Then add the third to that and plot that sum and so on. I know I need to do a for loop but I am not sure how to do it. I will just do the first 5 points to show what I did on a smaller scale. The error is in my for loop.
x=1:5;
y= [ 1 4 9 12 13];
for i=1:5
P(i+1)=y(i+1)+y(i);
end
plot(x,P)
I may have gone about this all wrong and if I did just let me know. Any help is greatly appreciated. The graph should have the points (1,1) (2,5) (3,14) (4,26) (5, 39) incase I explained it poorly

採用された回答

Dave B
Dave B 2020 年 11 月 6 日
Hi Vezzaz: It sounds like the function you're looking for is cumsum, you don't need a loop!
x = 1:5;
y = [1 4 9 12 13];
yc = cumsum(y)
plot(x,yc)
  2 件のコメント
Vezzaz
Vezzaz 2020 年 11 月 6 日
Thank you!!!
Dave B
Dave B 2020 年 11 月 6 日
No problem, hang in there it'll get easier with practice!

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

その他の回答 (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