Help to Improve this short code (intersection point between two straight lines given end points)
정보
이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.
이전 댓글 표시
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
2020년 4월 29일
편집: Aaron Garcia
2020년 4월 29일
답변 (1개)
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
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
이 질문은 마감되었습니다.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!