# Redoing iteration of for loop if certain outcome happens

36 views (last 30 days)
Joseph Crespo on 18 Mar 2020
Answered: Raynier Suresh on 23 Mar 2020
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 CommentsShowHide 1 older comment
Joseph Crespo on 18 Mar 2020
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.

Raynier Suresh on 23 Mar 2020
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: