MATLAB: How to make coodinates bounce off the screen edge

coordinatesMATLABvisual

Hey all, Having some issues with the loops in my code, so the aim is to continuously bounce a set of coordinates off the edge of the screen up until a certain time. The coordinates change, however, once they reach a limit they just stay there and I can't get them to reverse. I've tried a few variations in my code but any feedback would be welcome.
xCoord = randi([20,30],1,1); yCoord = randi([20,30],1,1);
speed_1 = 1;
boundsLeft = 0; boundsTop = 0; boundsRight = 100; boundsBottom = 90;
Coords_1 = [xCoord, yCoord]
timeID = tic;
while 1
Coords_1 = Coords_1 + speed_1
if (toc(timeID) > 0.1)
break;
end
if Coords_1 > boundsRight
Coords_1 = Coords_1 - speed_1;
elseif Coords_1 > boundsBottom
Coords_1 = Coords_1 - speed_1;
end
if Coords_1 < boundsLeft
Coords_1 = Coords_1 + speed_1;
elseif Coords_1 < boundsTop
Coords_1 = Coords_1 + speed_1;
end
end

Best Answer

You have to make the following changes to your code
  1. test x and y coordinates separately using Coords_1(1) and Coords_1(2)
  2. reverse the direction after the bounds have been reached by using speed_1 = - speed_1;
  3. use - speed_1 also for the left and bottom border, to undo the + speed_1 above
And it would be better to rename speed_1 to dxy. I also added a plot to check the results and increased the time:
xCoord = randi([20,30],1,1); yCoord = randi([20,30],1,1);
speed_1 = 1;
boundsLeft = 0; boundsTop = 0; boundsRight = 100; boundsBottom = 90;
Coords_1 = [xCoord, yCoord]
timeID = tic;
axis([0 100 0 100])
hold on
while 1
Coords_1 = Coords_1 + speed_1
if (toc(timeID) > 10)
break;
end
if Coords_1(1) > boundsRight
Coords_1(1) = Coords_1(1) - speed_1;
speed_1 = -speed_1;
elseif Coords_1(2) > boundsBottom
Coords_1(2) = Coords_1(2) - speed_1;
speed_1 = -speed_1;
end
if Coords_1(1) < boundsLeft
Coords_1(1) = Coords_1(1) - speed_1;
speed_1 = -speed_1;
elseif Coords_1(2) < boundsTop
Coords_1(2) = Coords_1(2) - speed_1;
speed_1 = -speed_1;
end
plot(Coords_1(:,1), Coords_1(:,2), 'o')
drawnow
end