for loop doesn't repeat the operation (Matlab)

2 ビュー (過去 30 日間)
Afluo Raoual
Afluo Raoual 2021 年 3 月 23 日
コメント済み: Steven Lord 2021 年 3 月 24 日
Dear members
I have a program in which I don't have errors when running it, but it doesn't repeat the operation n=n+1 when the result of for loop is not 0.
I don't know where is the problem with for loop.
  1 件のコメント
Steven Lord
Steven Lord 2021 年 3 月 24 日
Why did you edit away your code?

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

回答 (1 件)

Steven Lord
Steven Lord 2021 年 3 月 23 日
Notice that the first n in the line "n = n+1;" is underlined? If you hover over that variable, you will see a Code Analyzer message that I believe will recommend not changing the value of the loop variable inside the loop. Any changes you make will persist only to the end of that iteration of the loop; when the next iteration starts the loop variable will take on the next value from the vector over which you're iterating.
for k = 1:5
fprintf("First, k is %d.\n", k)
k = k + 10;
fprintf("Next, k is %d.\n", k)
end
First, k is 1.
Next, k is 11.
First, k is 2.
Next, k is 12.
First, k is 3.
Next, k is 13.
First, k is 4.
Next, k is 14.
First, k is 5.
Next, k is 15.
If you just mean to skip to the next value of n (from 1:iteration) then just eliminate that line.
If you mean to skip (from 1 to 3 at the next iteration, not running the body of the loop for n = 2) then you're going to need to switch to a while loop.
If you want to stop the loop entirely when or if L becomes 0, use break.
  1 件のコメント
Afluo Raoual
Afluo Raoual 2021 年 3 月 23 日
both if and n are underlined and I don't know how to solve this problem

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

カテゴリ

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