Finding intersection between two 3D lines
13 views (last 30 days)
I am trying to find whether there is an intersection (point) between 2 lines in 3D.
For a more extensive explanation: I made a (PDE) mesh and now, with my code, I am able to plot a line between the origin and every node of my mesh (line1 every loop). And also I made a more simple line (line2, blue) which stays at the same height.
Now I want to know whether line1 and line2 intersect. Because when line1 intersect with line2, the algoritm is not allowed to plot it (this I want to add with an 'if' statement when I know how to find out whether they intersect.
In the image you see the result I now got.
Besides, I would really like to plot my mesh and lines in the same plot, but for now I couldn't found out how. So if you know also a solution for that.
Thanks a lot!
(I also added my STL file from which I made the mesh)
model = createpde(1);
mesh = generateMesh(model, 'Hmax',5);
for i = 1:length(mesh.Nodes)
A = mesh.Nodes(:,i);
B = [0,0,0];
C = [-150,-150,0];
% sqrt(sum((A - B) .^ 2))
line1 = plot3(v(:,1),v(:,2),v(:,3),'r');
line2 = plot3(h(:,1),h(:,2),h(:,3),'b');
Bjorn Gustavsson on 12 Jun 2022
You can do this rather automatic with geometry and linear algebra if you write your the positions and along lines as:
If and are equal we can subtract the two equations to get:
for some lengths and away from the respective "reference points". This gives us 3 equations (the x, y and z components) in 2 unknowns ( and ):
This we can solve rather easily in matlab:
function [does_intersect,r_intersect] lines_intersect(r10,e1,r20,e2,tol_intersect)
if nargin < 5
tol_intersect = 1e-6; % adjust to suit your preferences
l1l2 = [e1,e2]\(r20-r10); % lengths along lines
r1 = r10 + l1l2(1)*e1;
r2 = r20 + l1l2(2)*e2;
dr = r1-r2;
if norm(dr) < tol_intersect
does_intersect = 1;
r_intersect = (r1 + r2)/2;
does_intersect = 0;
r_intersect = ;
Here the inputs should be 3-by-1 column arrays.