Create a For Loop

조회 수: 6 (최근 30일)
Ivy Shen
Ivy Shen 2018년 9월 12일
댓글: Ivy Shen 2018년 9월 15일
Hi, the task is that:
S0 = 0;
S1 = S0+p1-q1-e1;
S2 = S1+p2-q2-e2;
and so on
p,q,and e are all known. I tried to write a for loop for it as following:
for i = 1:121
S(i) = S(i-1)+p(i)-q(i)-e(i);
S = S(i);
end
but S(i-1) gives S(0) which is not allowed in matlab.
Can anyone give me some advice on how to modify it to make it work?
Thank you!

채택된 답변

James Tursa
James Tursa 2018년 9월 12일
편집: James Tursa 2018년 9월 12일
Simply adjust your expectations of how to use indexing. E.g., let
S(1) mean the same thing as S0
S(2) mean the same thing as S1
etc
Then just adjust your indexing:
S(1) = 0;
for i = 2:122
S(i) = S(i-1)+p(i)-q(i)-e(i);
end
Or, if the indexing of the p, q, e vectors already started at 1, then maybe this variation will work for you:
S(1) = 0;
for i = 2:122
S(i) = S(i-1)+p(i-1)-q(i-1)-e(i-1);
end
  댓글 수: 1
Ivy Shen
Ivy Shen 2018년 9월 15일
Thank you very much!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품


릴리스

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by