MATLAB: Distance between two moving particles

animationdistance

I'm new to programming and just started learning MATLAB last week. If anyone could help me out, I'd very much appreciate it.
Let's say I have two particles moving with constant speeds along straight line paths in 3-D space (figure enclosed). For each time step of 0.1 second, I need to calculate the distance between the moving particles. Is there any code available for this?

Best Answer

Perhaps we need to look at this differently. You have two particles, I'll call them P and Q.
P and Q are moving along two straight line trajectories in 3 dimensions. They have their own velocities, but those velocities are fixed. So as a function of time, what is the distance between the two particles? Can we write this as a function?
Each line is defined by a starting point and a velocity vector. Each of those are vectors themselves, of length 3. So, I'll pick some random lines.
P0 = [1 2 3];
Q0 = [5 4 2];
Pvel = [0.1 0.2 0.1];
Qvel = [-0.25 -0.3 0.15];
The lines P and Q are defined simply enough as functions of time.
P = @(t) P0 + t(:)*Pvel;
Q = @(t) Q0 + t(:)*Qvel;
The functions work if you have the current release of MATLAB. On older releases, those last two lines will fail, so I would have had to write them as:
P = @(t) bsxfun(@plus,P0,t(:)*Pvel);
Q = @(t) bsxfun(@plus,Q0,t(:)*Qvel);
The latter form will work in any release.
How about the distance between the two points, as a function of time?
Dpq = @(t) sqrt(sum((P(t) - Q(t)).^2,2));
So now lets look at the lines.
t = 0:.1:20;
P_t = P(t);
Q_t = Q(t);
plot3(P_t(:,1),P_t(:,2),P_t(:,3),'r-');
hold on
plot3(Q_t(:,1),Q_t(:,2),Q_t(:,3),'b-');
box on
grid on
So, two lines. They are general, skew lines.
plot(t,Dpq(t))
The distance between them should be an arc of a hyperbola. Easy enough to show that is true:
syms T
simplify(((P0 + T*Pvel).^2 + (Q0 + T*Qvel).^2)*ones(3,1))
ans =
(47*T^2)/200 - (27*T)/10 + 59
This is the SQUARE of the distance. So effectively, we have this equation
D^2 = (47*T^2)/200 - (27*T)/10 + 59
relating distance (D) between the lines as a function of time (T). You should be able to convince yourself that this is the equation of a hyperbola. As T approaches infinity in either direction, the curve approaches a straight line as an asymptote.
Now, I'm not totally sure what you are looking for in all of this. But if your goal is merely to compute distance between the points at any time t, Dpq(t) does exactly that for you. It is vectorized, so if you have a vector of times in t, it will generate a vector of distances.
Perhaps this is what you are looking for?
Related Question