MATLAB: Plotting a moving particle in a box with elastic collisions

animationhelpmotionplottrajectorywhile loop

Hi, I'm having trouble with this problem:
Develop a Matlab model for the trajectory of a single particle with velocity v = {vx, vy} in a two dimensional square box. Treat the collisions with the walls of the box as elastic, so that when a particle collides with a wall, the sign of its velocity component in the direction normal to the wall is inverted.
I understand the question but I'm just not very good at coding and I have no idea how to make the relevant velocity component switch signs when the particle hits a wall… Please help!
This is what I've come up with so far: (it doesn't work but I can't see why)
n = 100;
x = zeros(1,100); y = zeros(1,100);
v_x = zeros(1,100); v_y = zeros(1,100);
while i=2:n
x(i)=x(i-1)+v_x(i);
y(i)=y(i-1)+v_y(i);
if x(i)<-5
v_x(i)=-v_x(i-1);
elseif x(i)>5
v_x(i)=-v_x(i-1);
elseif y(i)<-5
v_y(i)=-v_y(i-1);
elseif y(i)>5
v_y(i)=-v_y(i-1);
else
v_x(i)=v_x(i-1);
v_y(i)=v_y(i-1);
end
plot(x(i),y(i),'or','MarkerSize',5,'MarkerFaceColor','r')
axis([-5 5 -5 5])
pause(0.1)
end

Best Answer

Hi, there is no initial velocity, the particle will keep staic.
clear;clc;
n = 100;
x = zeros(1,100); y = zeros(1,100);%current position
v_x = zeros(1,100); v_y = zeros(1,100);%current velocity
v0_x = 1; v0_y = 1.5;%initial velocity
v_x(1) = v0_x; v_y(1) = v0_y;
clf;figure(1);
for i=2:n
x(i)=x(i-1)+v_x(i-1);
y(i)=y(i-1)+v_y(i-1);
if x(i)<-5
x(i)=-10-x(i);
v_x(i)=-v_x(i-1);
v_y(i)=v_y(i-1);
elseif x(i)>5
x(i)=10-x(i);
v_x(i)=-v_x(i-1);
v_y(i)=v_y(i-1);
elseif y(i)<-5
y(i)=-10-y(i);
v_x(i)=v_x(i-1);
v_y(i)=-v_y(i-1);
elseif y(i)>5
y(i)=10-y(i);
v_x(i)=v_x(i-1);
v_y(i)=-v_y(i-1);
else
v_x(i)=v_x(i-1);
v_y(i)=v_y(i-1);
end
plot(x(i),y(i),'or','MarkerSize',5,'MarkerFaceColor','r');hold off;
axis([-5 5 -5 5])
pause(0.1)
end