Checking for loop coordinates to see whether two randomly generated positions are within 5 units of each other

1 次查看(过去 30 天)
Hello there,
I am in the process of coding a program that plots two people in a 100 x 100 unit area. Each person is allowed to move one unit per loop iteration, and there are 5000 iterations of the loop (for i=1:5000). I want to terminate the loop when the difference in positions, either in the x-axis or the y-axis, are equal to or less than 5. However, when I add an if statement or while loop to compute the difference between the x position and y position between the two people to check if it's less than or equal to 5, the entire position plot gets changed to two lines. Here are some examples:
c=man1x-man2x;
v=man1y-man2y; %these two are variables created to store the differences in position between the two people
while c > 5 && v > 5
continue;
end
break; % for some reason, the entire grid of numbers seems to change when this break is added to 5000 little movements to two %diagonal lines that simply converge on each other.
if c >= 5 || v >= 5
else
break; %This one produces some results, but still gets buggy when break; is added. The program will still have 2 diagonal lines %converge together from as far as 20 units away.
end
Any thoughts, assistance, advice, or insights would be greatly appreciated, as I cannot figure out why the break; command is what is causing the diagonal lines and the messy termination of my loop.
Thanks!
  3 个评论
Geoff Hayes
Geoff Hayes 2015-7-4
Out of curiosity, why does your code terminate the loop if there is difference of five between x or y? Why not use the (for example) Euclidean distance instead:
dist = sqrt((man1x-man2x)^2 + (man1y-man2y)^2);
while dist > 5
continue;
end

请先登录,再进行评论。

回答(1 个)

Anusha B
Anusha B 2015-7-9
Hi Daniel,
1. Can you try using while loop instead of FOR loop for '5000 iterations'? OR 2. Can you execute the following command and execute your code? >> feature accel off
However, this command can affect MATLAB performance.

类别

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