Change for-loop iteration inside the loop.

79 ビュー (過去 30 日間)
M G
M G 2013 年 10 月 10 日
コメント済み: NALLARASU KRISH 2023 年 5 月 30 日
Dear Matlab users,
I would like to change the For-loop iteration inside the loop if a condition is met. Suppose:
for i = 1:500
pause(0.1)
display(i)
if i == 40
i = 300;
end
end
So, I want whenever i == 40, the iteration changes from 39 to 300 and continues till 500. The code above does not work and every time the loop resets the i value. What I want should look like this:
i = 1, 2, 3, ... 39, 300, 301, 302, 303, ... 500.
  1 件のコメント
Himanshu Nagpal
Himanshu Nagpal 2016 年 6 月 14 日
You can use the following code
i = 1;
while (i <= 500)
pause(0.1)
display(i)
i = i + 1;
if (i == 40)
i = 300;
end
end

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

回答 (3 件)

Roger Stafford
Roger Stafford 2013 年 10 月 10 日
編集済み: Roger Stafford 2013 年 10 月 10 日
Matlab's for-loop is designed so that you cannot change its index, in this case, 'i', within the loop. Even though you have set it to 300, it will stubbornly return on the next trip with i = 41, not 300. To do what you indicate here you should do this instead:
for i = [1:39,300:500]
pause, etc ...
end
If a change in indexing cannot be predicted in advance of entering a for-loop you should use the 'while-end' construct instead where you must control the index yourself instead of an automatic advance at each step. Either that or if you want to sudden depart ahead of time from a for-loop, use the 'break' function.
  2 件のコメント
M G
M G 2013 年 10 月 10 日
Hi Roger, Thanks for response, but what if the IF-statement varies every time?
Roger Stafford
Roger Stafford 2013 年 10 月 10 日
See the edited version of my answer.

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


Sachin Patil
Sachin Patil 2016 年 9 月 20 日
Please see this code
i = 1;
for j = 1:500
pause(0.1)
display(i)
i = i + 1;
if i == 40
i = 300;
end
end
  2 件のコメント
Jose Martinez
Jose Martinez 2020 年 10 月 16 日
TRASH
NALLARASU KRISH
NALLARASU KRISH 2023 年 5 月 30 日
Yes! value of i goes upto 759 instaed of stopping at 500!!

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


Hector Cano
Hector Cano 2020 年 2 月 14 日
clc;clear;close all
n=[1 1 100];
while (n(1) <= n(3))
j(n(1))=n(1);
if (n(1) == 50)
n(2) = 10;
end
n(1) = n(1) + n(2);
if (n(1)==n(3))
n(3)=200;
end
end
j(j==0)=nan;
plot(j,'*-r')

カテゴリ

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