MATLAB: How to make multiples loops run at the same time

iterationwhile loop

Hello all. I am assigned to make a program in which multiple dots move at the same time. All movements are confined within a window created by user. I already have the following functions:
1. createDot(x,y,r) %make a dot with your wanted radius at certain location (x,y) in the window
2. createWin(w,h) %make a window with width and height
3. RunX(dot,unit) %move the dot x units horizontally
4. RunY(dot,unit) %move the dot y units vertically
So here is my loop to make the ball move:
ball = createDot(100,100,10)
dx = 1;
dy = 1;
n = 0;
while n < 1
RunX(ball,dx)
RunY(ball,dy)
pause(0.0001)
refigure %this function basically draws the dot at the new location
n = n + 0;
end
I tested my code and the ball run well (Let's not worry about whether the ball goes past the created window right now).
But my problem is, I have to make multiple balls move at the same time. But when I make "ball2" and create another separate loop for it, only the first ball is moving. So I guess the 2nd ball can only start moving after the first loop of the first ball ends (which it is not supposed to).
So how can I make the 2nd ball (and later more balls) start moving at the same instant the first ball moves?
Thank you so much!

Best Answer

Hi John - why not have an array of (ahem) balls each with their initial position and radius set, and then just the one while loop that iterates over each ball in the array and moves its x and y coordinates according to dx and dy:
ballArray=[];
ballArray[1] = createDot(100,100,10);
ballArray[2] = createDot(50,50,5);
% etc. for each ball
dx=1;
dy=1;
while true % just use the logical true to keep the while loop running
% iterate over each ball (use length to get the number of balls in array)
for i=1:length(ballArray)
RunX(ballArray[i],dx); % move ball i wrt x
RunY(ballArray[i],dy); % move ball i wrt y
end
pause(0.0001);
refigure;
end
Would the above work or do you need something where the balls have different initial start times?
Geoff
Related Question