Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

Help to Improve this short code (intersection point between two straight lines given end points)

조회 수: 2 (최근 30일)
Hello there!!
I have write this code to find the intersection point given initial and final point of two straight lines, its to simple but in implementation calling this function to many times is not fast as another functions (InterX.m) . Im not shure why is too slow. Please help !!!! Thank you
function [pX] = pInter(A,B,C,D)
%intersection point between two straight lines given end points
%A : initial point of first straight line
%B : final point of first straight line
%C: initial point of second straight line
%D : final point of second straight line
a = B(2) - A(2);
b = A(1) - B(1);
c = a*A(1) + b*A(2);
a1 = D(2) - C(2);
b1 = C(1) - D(1);
c1 = a1*C(1)+ b1*C(2);
det = a*b1 - a1*b;
if det == 0
pX= NaN; %are parallel
else
X = (b1*c - b*c1)/det;
Y = (a*c1 - a1*c)/det;
pX=[X,Y];
end
end
  댓글 수: 1
Aaron Garcia
Aaron Garcia 2020년 4월 29일
편집: Aaron Garcia 2020년 4월 29일
I find the solution !!! by calling it 1000 times in another code, total time decrease from 15s to 3s !!!
The problem was how i call for the function(variables) , this is how i was doing:
Pi1 = [x(1) L1(1)];
Pi2 = [x(end) L2(end)];
Pf1 = [x(1) L1(1)];
Pf2 = [x(end) L2(end)];
pX=pInter(Pi1,Pf1,Pi2,Pf2);
First solution:
Call
pX = pInterNew1(x,L1,L2);
Function
function [pX] = pInterNew1(x,L1,L2)
A = [x(1) L1(1)];
B = [x(end) L1(end)];
C = [x(1) L1(1)];
D = [x(end) L2(end)];
%====Same code of original function
end
Anoter solution:
Call
pX = pInterNew2(x(1),x(end),L1(1),L1(end),L2(1),L2(end));
function
function [pX] = pInterNew2(xin,xEnd,Pi1,Pf1,Pi2,Pf2)
a = Pf1 - Pi1;
b = xin - xEnd;
c = a*xin + b*Pi1;
a1 = Pf2 - Pi2;
b1 = xin - xEnd;
c1 = a1*xin+ b1*Pi2;
det = a*b1 - a1*b;
if det == 0
pX= NaN; %are parallel
else
X = (b1*c - b*c1)/det;
Y = (a*c1 - a1*c)/det;
pX=[X,Y];
end
end

답변 (1개)

David Hill
David Hill 2020년 4월 29일
function ans = pInter(A,B,C,D)
a=B-A;
b=D-C;
if isequal(a(2)/a(1),b(2)/b(1))
NaN;
else
[-a(2)/a(1),1;-b(2)/b(1),1]\[A(2)-A(1)*a(2)/a(1);C(2)-C(1)*b(2)/b(1)];
end
  댓글 수: 1
David Hill
David Hill 2020년 4월 29일
I would just load up all your points in a matrices A,B,C,D and only execute the function once.
function p = pInter(A,B,C,D)
a=B-A;
b=D-C;
p=zeros(size(A));
for k=1:length(A)
if isequal(a(k,2)/a(k,1),b(k,2)/b(k,1))
p(k,:)=[NaN,NaN];
else
p(k,:)=([-a(k,2)/a(k,1),1;-b(k,2)/b(k,1),1]\[A(k,2)-A(k,1)*a(k,2)/a(k,1);C(k,2)-C(k,1)*b(k,2)/b(k,1)])';
end
end

이 질문은 마감되었습니다.

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by