Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: distance between point and line segment
Date: Thu, 3 Feb 2011 13:58:03 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 57
Message-ID: <iiec9b$881$1@fred.mathworks.com>
References: <4a2f4ac1-c21e-4ebf-8530-352f15098a47@41g2000hsc.googlegroups.com> <d122bed7-41d5-446a-8b0a-e786bdb938fb@a22g2000hsc.googlegroups.com> <fsrkeb$os2$1@fred.mathworks.com> <fsrvq5$5cu$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: www-02-blr.mathworks.com
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1296741483 8449 172.30.248.47 (3 Feb 2011 13:58:03 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Thu, 3 Feb 2011 13:58:03 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1861624
Xref: news.mathworks.com comp.soft-sys.matlab:707861

"Roger Stafford" wrote in message <fsrvq5$5cu$1@fred.mathworks.com>...
> "Chukwuemeka Igwe" <chukigwe@yahoo.com> wrote in message <fsrkeb
> $os2$1@fred.mathworks.com>...
> > Yes thanks for your replies.
> > 
> > However if I  use the cross product and assume that the z 
> > axis  have zero components  I actually get some reuslts 
> > which are more than an order of magnitude bigger thant the 
> > case when I use the determinant to solve for two 
> > dimensions.
> > Please what is happening to cause such a difference in 
> > results.
> > 
> > Thanks 
> > 
> > Chuk
> --------
>   First of all, Chuk, let me apologize for the errors in the formulas I gave back 
> on Feb. 19, and for not noticing them this past Saturday.  I cannot imagine 
> what I was thinking of.  The 3D formula should read:
> 
>  d = norm(cross(Q2-Q1,P-Q1))/norm(Q2-Q1);
> 
> and the 2D versions ought to read:
> 
>  d = abs(det([Q2-Q1,P-Q1]))/norm(Q2-Q1); % for col. vectors
>  d = abs(det([Q2-Q1;P-Q1]))/norm(Q2-Q1); % for row vectors.
> 
>   In this corrected form the 3D formula is identical to the formula (9) of the 
> website:
> 
>  http://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html
> 
> which ImageAnalyst mentioned.

Question was about distance between point and line segment, not between point and line.
Solution could be as follows:
=============================
x1 = Q1(1);
y1 = Q1(2);
x2 = Q2(1);
y2 = Q2(2);
x0 = P(1);
y0 = P(2);

if (min(x1,x2)<=x0 && max(x1,x2)>=x0) || (min(y1,y2)<=y0 && max(y1,y2)>=y0)
% if point is in "range" of line segment    
    d = abs((x2-x1)*(y1-y0)-(x1-x0)*(y2-y1))/sqrt((x2-x1)^2+(y2-y1)^2);
else
    d = min(sqrt((x2-x0)^2+(y2-y0)^2),sqrt((x1-x0)^2+(y1-y0)^2));
end
=============================

And my question is how to vectorize this code? Suppose that I have one line segment and n points. I can use loop or arrayfun, but is there another way to do this?

best regards
Grzegorz