Redoing iteration of for loop if certain outcome happens

조회 수: 49 (최근 30일)
Joseph Crespo
Joseph Crespo 2020년 3월 18일
답변: Raynier Suresh 2020년 3월 23일
I am writing a rock-paper-scissors code for class, and I need to have the for loop redo the iteration of the two "players" tie. I have tried using a while loop instead, but I cannot get any test results because it takes absolutely forever (I need to run 10000 iterations). Everything else in the code runs perfectly, I just can't find a way that redoes the iteration if a tie results. Here is my code(the issue comes in when trying to figure out what to do with the first if condition):
d = 0;
e = 0;
%% Rock Paper Scissors
%for the game, rock will correspond to 1, scissors will correspond to 2,
%and paper will correspond to 3
i = 1;
player_A = zeros;
player_B = zeros;
for i = 1:10000
player_A(i) = randi(3);
player_B(i) = randi(3);
if player_A(i) == player_B(i)
%issue is what to put here for this condition
end
if player_A(i) == 1 && player_B(i)== 2
d = d + 1;
end
if player_A(i) == 2 && player_B(i) == 3
d = d + 1;
end
if player_A(i) == 3 && player_B(i) == 1
d = d + 1;
end
if player_A(i) == 1 && player_B(i) == 3
e = e + 1;
end
if player_A(i) == 2 && player_B(i) == 1
e = e + 1;
end
if player_A(i) == 3 && player_B(i) == 2
e = e + 1;
end
x(i) = d;
y(i) = e;
end
  댓글 수: 2
darova
darova 2020년 3월 18일
I have an idea
Joseph Crespo
Joseph Crespo 2020년 3월 18일
I had actually tried this before posting, and it "worked" in a sense, but didn't redo all instances where there was a tie. I ended up just creating a simplified for loop that accomplshed the same task I wanted done. Problem resolved.

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

답변 (1개)

Raynier Suresh
Raynier Suresh 2020년 3월 23일
For a “for” loop, MATLAB resets the loop index to the next value when it returns to the top of the outer loop, it ignores any changes that took place within the loop or in a nested loop, So it’s not possible for you to go back to a previous iteration in for loop. But to do so you could use a “while” loop, in “while” loop you could put something like I = I – 1 or something else to go back to a previous iteration.
Refer to the link below for more details:

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by