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.
I'm enjoying these creative solutions.
John, I just tried your file exchange solution out of pure curiosity. Your guess is correct; it does score poorly. I also got the error "You may not use the command(s) builtin in your code" for the test cases. All I did was change only the first line to call the function and the variable names with no other checking. I'll do some real work on it now. :-)
Will not solution like this be sooo much slower than simple loops?! Short yes, efficient no.
well, I think I was wrong...This solution is slower if the degree of the polynomial is small but much faster if the degree gets higher...solving polynomials of high degree is really slow with ROOTS.
Arrange vector in ascending order
564 Solvers
463 Solvers
110 Solvers
Pernicious Anniversary Problem
698 Solvers
310 Solvers