Info
This question is closed. Reopen it to edit or answer.
How to store the number of iterations used until the while loop condition is met?
1 view (last 30 days)
Show older comments
I am coding a 2D collision problem in a 11x11 grid. In my while loop, I am trying to code that when an if condition of both particles A and B share the same coordinates, the number of steps used until this condition is met gets stored in the Moves array and it doesn't work the way I want it as 0, 1, and 2 gets stored in the Moves array and that's IMPOSSIBLE since it's a 11x11 grid and A & B can't just move 1, 2, or no steps until they meet knowing that they are allowed to move randomly in any direction one tile pers step. Here's my code so far.
I STILL NEED HELP!
for j = 1:5000
% run while loop if Collision is not found.
Collision = 0; k = 0;
while Collision == 0 && k < 1000
k = k + 1;
% Using the RandWalk_2D function for the new position of A and B.
[xAkp1, yAkp1] = RandWalk_2D(xAk,yAk,BC);
[xBkp1, yBkp1] = RandWalk_2D(xBk,yBk,BC);
% Create the path of particle A.
xAkPATH = [xAk - 0.5, xAk + 0.5, xAk + 0.5, xAk - 0.5];
yAkPATH = [yAk - 0.5, yAk - 0.5, yAk + 0.5, yAk + 0.5];
xAkp1PATH = [xAkp1 - 0.5, xAkp1 + 0.5, xAkp1 + 0.5, xAkp1 - 0.5];
yAkp1PATH = [yAkp1 - 0.5, yAkp1 - 0.5, yAkp1 + 0.5, yAkp1 + 0.5];
% Create the path of particle B.
xBkPATH = [xBk - 0.5, xBk + 0.5, xBk + 0.5, xBk - 0.5];
yBkPATH = [yBk - 0.5, yBk - 0.5, yBk + 0.5, yBk + 0.5];
xBkp1PATH = [xBkp1 - 0.5, xBkp1 + 0.5, xBkp1 + 0.5, xBkp1 - 0.5];
yBkp1PATH = [yBkp1 - 0.5, yBkp1 - 0.5, yBkp1 + 0.5, yBkp1 + 0.5];
% Update new positions of A and B.
xAk = xAkp1; yAk = yAkp1;
xBk = xBkp1; yBk = yBkp1;
% if condition when both A and B collide to restart a new trial.
if xAk == xBk && yAk == yBk
% Collision happens!
Collision = 1;
% Storing the number of moves in this trial in the 'Moves' array.
Moves(j) = k;
end
end
end
2 Comments
Jackson Burns
on 2 Aug 2019
Your code seems fine to me, but I can'tbe sure without seeing:
RandWalk_2D
I suspect the error is in there.
Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!