How do I code this for loop?

1 回表示 (過去 30 日間)
JM321
JM321 2021 年 6 月 11 日
コメント済み: JM321 2021 年 6 月 11 日
vd_inc is a matrix where I obtain values from, I then want to store p1-p5 in a matrix.
p1= 0;
p2 = p1+ vd_inc(31);
p3= p2 + vd_inc(30);
p4 = p3+ vd_inc(29);
p5= p4 + vd_inc(28);
This is my attempt, the problem is that p(index) is going up in increments and vd_inc is decreasing, 2 for loops are required?
for index1 = 1:31
index1=1
p(index+1)= p(index)+ vd_inc(index);
end

採用された回答

DGM
DGM 2021 年 6 月 11 日
I don't know how you're getting anything out of it, since the index isn't even being used.
You could do this:
vd_inc = 1:100;
p = zeros(1,5);
for index = 1:numel(p)-1
p(index+1)= p(index)+ vd_inc(31-index+1);
end
p
p = 1×5
0 31 61 90 118
but you really don't even need the loop
p = [0 cumsum(vd_inc(31:-1:28))]
p = 1×5
0 31 61 90 118
  1 件のコメント
JM321
JM321 2021 年 6 月 11 日
Forgot to add the 1 to make it index1, thanks for your help

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

その他の回答 (0 件)

カテゴリ

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

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by