t=0;
dt=0.5;
x1=1;
y1=0;
v1x=0;
v1y=0;
m1=1;
x2=-8;
y2=0;
v2x=2;
v2y=0;
m2=1;
subplot (3, 1, 1)
plot ([-10, 10], [-10, 10], 'w')
r1 = rectangle ('Position', [x1,y1,1,1], 'FaceColor', 'r', 'Curvature', [1,1]);
r2 = rectangle ('Position', [x2,y2,1,1], 'FaceColor', 'b', 'Curvature', [1,1]);
axis ([-10 10 -10 10]);
subplot (3, 1, 2)
plot (t, x1)
plot (t, x2)
xlabel ('Time')
ylabel ('Position-X')
subplot (3, 1, 3)
plot (t, y1)
plot (t, y2)
xlabel ('Time')
ylabel ('Position-Y')
xx1 = [ ];
xx2 = [ ];
yy1 = [ ];
yy2 = [ ];
while t < 100
v1xold = v1x; v2xold = v2x; v1yold = v1y; v2yold = v2y;
if 1 < sqrt((x2-x1)^2+(y2-y1)^2)
x1 = x1 + (v1x * dt);
x2 = x2 + (v2x * dt);
y1 = y1 + (v1y * dt);
y2 = y2 + (v2y * dt);
xx1 = [xx1, x1];
xx2 = [xx2, x2];
yy1 = [yy1, y1];
yy2 = [yy2, y2];
else
v1x = ((m1-m2)/(m1+m2))*v1xold + ((2*m2)/(m1+m2)) * v2xold;
v1y = ((m1-m2)/(m1+m2))*v1yold + ((2*m2)/(m1+m2)) * v2yold;
v2x = ((m2-m1)/(m1+m2))*v2xold + ((2*m1)/(m1+m2)) * v1xold;
v2y = ((m2-m1)/(m1+m2))*v2yold + ((2*m1)/(m1+m2)) * v1yold;
x1 = x1 + (v1x * dt);
x2 = x2 + (v2x * dt);
y1 = y1 + (v1y * dt);
y2 = y2 + (v2y * dt);
xx1 = [xx1, x1];
xx2 = [xx2, x2];
yy1 = [yy1, y1];
yy2 = [yy2, y2];
end
if x1+dt*v1x>9
v1x= -v1x;
end
if x2+dt*v2x>9
v2x=-v2x;
end
if x1+dt*v1x<-10
v1x=abs(v1x);
end
if x2+dt*v2x<-10
v2x=abs(v2x);
end
if y1+dt*v1y>9
v1y=-v1y;
end
if y2+dt*v2y>9
v2y=-v2y;
end
if y1+dt*v1y<-10
v1y=abs(v1y);
end
if y2+dt*v2y<-10
v2y=abs(v2y);
end
set(r1,'Position', [x1,y1,1,1]);
set(r2,'Position', [x2,y2,1,1]);
subplot (3, 1, 2)
plot (t, x1,'ro',t,x2,'bs')
axis([0 100 -10 10])
xlabel ('Time')
ylabel ('Position-X')
subplot (3, 1, 3)
plot (t, y1,'ro',t,y2,'bs')
axis([0 100 -10 10])
xlabel ('Time')
ylabel ('Position-Y')
drawnow
t= t+ dt;
end
Best Answer