Path: news.mathworks.com!not-for-mail From: <HIDDEN> Newsgroups: comp.soft-sys.matlab Subject: Re: Shortest distance from Matrix to a line segment Date: Mon, 15 Aug 2011 20:56:26 +0000 (UTC) Organization: The MathWorks, Inc. Lines: 22 Message-ID: <j2c15q$r4f$1@newscl01ah.mathworks.com> References: <j2bu2g$ghi$1@newscl01ah.mathworks.com> Reply-To: <HIDDEN> NNTP-Posting-Host: www-04-blr.mathworks.com Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 8bit X-Trace: newscl01ah.mathworks.com 1313441786 27791 172.30.248.35 (15 Aug 2011 20:56:26 GMT) X-Complaints-To: news@mathworks.com NNTP-Posting-Date: Mon, 15 Aug 2011 20:56:26 +0000 (UTC) X-Newsreader: MATLAB Central Newsreader 1187260 Xref: news.mathworks.com comp.soft-sys.matlab:740076 "James D" <j.e.daniell@gmail.com> wrote in message <j2bu2g$ghi$1@newscl01ah.mathworks.com>... > Dear all, > I have a problem that I am trying to solve. > > I have a matrix of 600 x 840 different positions of latitude and longitude and I am trying to find and output the shortest distance to a line segment. > > I have created the following for the distance to a point and vectorised it so that it works faster than a for statement. > > I was wondering how I would code the shortest distance to a particular line segment for each of the 600 x 840 points in the matrix. > > distancematrix=sqrt( bsxfun(@plus, ((yllcorner+600*spacing-0.020833333:-spacing:yllcorner+0.020833333).'-centrallat).^2 ,... > ((xllcorner+0.020833333:spacing:xllcorner+840*spacing-0.020833333)-centrallong).^2 ) ); > > I hope that you can help! > Many thanks in advance, > James. - - - - - - - - - - That seems a remarkably inefficient way of finding the minimum distance from an evenly-spaced rectangular gridwork of points to a given point. You are having to compute 600*840 = 504,000 distances that way. It's very easy to find the gridwork coordinates of the four corners of a square (rectangle?) that immediately surrounds your given point. It just takes one subtraction, followed by one division, and then a call on 'ceil' and 'floor', for each of the two dimensions. Then you only have to find the minimum among four distances. Finding the minimum distance to a line segment is more complicated but I think the above reasoning can be applied in an analogous manner to greatly reduce the total number of distances that need to be computed. Of course you will have to decide precisely what you mean by the distance to a line segment. The usual definition is the distance to the orthogonal projection of a point onto the line of the line segment if the projected point lies within the segment, and otherwise the distance to the closer of the segment's two endpoints. Roger Stafford