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!