Finding intersection between two 3D lines

26 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);
importGeometry(model,'Bovenste GS.stl');
mesh = generateMesh(model, 'Hmax',5);
% pdeplot3D(mesh)
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');
hold on;
line2 = plot3(h(:,1),h(:,2),h(:,3),'b');
hold off;

Answers (1)

Bjorn Gustavsson
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.
Bjorn Gustavsson
Bjorn Gustavsson on 13 Jun 2022
My plan was to have dr be the array between the closest points on the two lines (you better check this function because I very much hoofed this function up at the prompt). Therefore checking that the norm of dr is smaller than tol_intersect will make the function return a does_intersect for all lines that are closer than than that tol_intersect - just because of numerical accuracy we typically cannot rely on all points that "physically" or mathematically do intersect will actually intersect perfectly "numerically" with finite precision arithmetic.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by