@ Michael. I don't think your reply to the above correction is correct. I have found wrong performance of your code due to numerical imprecision as well. When a rib is exactly vertical, or horizontal, the projected point, due to numerical error, might not lay exactly on the rib and then the test for whether the projected point is inside the line segment or not returns the wrong result and as a result the wrong distance is reported.
I have fixed it with slightly different code, though not importantly so:
% DN: correct projected point locations for exactly vertical or horizontal
% ribs, because of numerical precision problem the projection may not lay
% exactly on the rib, and then the test below to find if in segment errors
qvertical = B==0;
qhorizontal = A==0;
The following code you added to my original function is unnecessary, since the formula that computes xp and yp automatically takes care of these cases:
% Test for the case where a polygon rib is
% either horizontal or vertical. From Eric Schmitz
id = find(diff(xv)==0);
id = find(diff(yv)==0);
The only case we should guard against is a case when BOTH A (-diff(yv)) and B (diff(xv)) are identically zero at some points. It effectively means that the input for polygon verices includes duplicate points, i.e. some ribs have zero length and no projection is possible. This case should be flagged out and the function should return an error.
03 Apr 2008
Reasonably good. A couple of minor points to quibble about.
There is no H1 line. When you wish to remember the name of that function you downloaded last year to find the closes point on a polygon, how will you remember the name p_poly_dist? You might want to try lookfor. Lookfor is a nice tool that searches the FIRST comment line of all the functions on your search path, looking for keywords. The first comment line here is sadly composed of just a bunch of asterisks. So the only way to find this function will be if you try
Please add an H1 line to all your functions as you write them.
Next, I found no checks for errors in the code. Friendly code will look for simple mistakes by the user, and return meaningful error messages. Here, the author might verify that px and py are of the same lengths. I'd have put in checks to ensure that x and y are scalars, since it only processes a single point at a time.
The help is clear enough. I might have added an example of use, as this is a good way to resolve any questions that users have.
The code is nicely vectorized, searching the entire polygon at once. Though I'd want to add the ability to deal with multiple points at once, projecting each to a given polygon. Yes, it will be a loop over the points, but it save the additional function and setup overhead if you must put the loop outside this function.
A 4 rating seems appropriate here. I'd happily revise this rating upwards given some changes to this code.