Problem 43642. Euclidean distance from a point to a polynomial
A not uncommon problem in the area of computational geometry is to find the closest point to a straight line from a given point, or the distance from a point to a line. As you might expect, there is a simple formula for those things.
As an extension, I decided one day to write a tool that would compute the distance from a point to a general polynomial function in the (x,y) plane. That is your problem here:
Given a point (x0,y0), and a polynomial in the form y=P(x) where the function P is defined by the coefficients of a polynomial, you need to compute the minimum Euclidean distance to that polynomial. So you need to find and return the minimum distance in the (x,y) plane between the point (x0,y0), and the function y=P(x).
The function P will be passed in as the coefficients of a polynomial in standard MATLAB form, thus with the highest order coefficient first in a vector, like that generated by polyfit, and used by polyval. (P might be as simple as a constant function.) The point in question will be passed in as a vector of length 2, thus [x0,y0].
As test case for you to check your code, the distance from the point (-2,-5) to the curve y=x^2/2+3*x-5 should be:
x0y0 = [-2 -5]; P = [0.5 3 -5]; D = distance2polynomial(P,xy) D = 1.89013819497707
(Be careful plotting these curves in case you want to plot your solution. The command "axis equal" is a good idea.)
The symbolic TB tells me the distance is 1.8901381949770695260066523338279..., but I'll allow some slop in your solution, since you may have chosen a different algorithm than the one I chose. You should expect to provide at least 13 correct significant digits in the solution.
Disclaimer: I'm not really sure why anyone needs such a code, which is why I've not posted my solution on the FEX. Anyway, my solution is a pretty one that I thought might make a fun Cody problem, and I wanted to see how others might approach the problem. I expect that my reference solution will score poorly for Cody purposes, since it is carefully coded, complete with error checks, and returns more than just the minimum distance.
Solution CommentsShow comments
Problem Recent Solvers27