From: Nina Hinchy on
"C Y" <me(a)nada.com> wrote in message <fcu2k9$29$1(a)fred.mathworks.com>...
> Hi,
>
> I have two 2-D contours with the x and y points for each
> known. I am trying to find the perpendicular distance from
> each point of contour 1 to contour 2 in Matlab.
>
> This is my general algorithm:
> 1. Perform cubic spline interpolation through the points of
> contour 1
> 2. Differentiate to get tangent equation.
> 3. Evaluate the tangent equation at every point on contour
> 1 to get the slopes of all the tangents.
> 4. Divide the slopes of the tangents by -1 to get the
> corresponding slopes of the normals to the tangents.
> 5. Find line equation of the normals by using the slopes
> and the points of contour 1
> 6. Iterate through the points in contour 2 and find the
> distance from every point to the normals by using the formula
> d = abs( (Ax + by = C) )/sqrt(A^2 + B^2);
> 7. The closest point to each normal is the point with the
> one with the min d.
> 8. Compute the euclidean distance from the point on contour
> 1 to the point of contour 2 which is closest to the normal
> traveling through the point on contour 1. Repeat for every
> point on contour 1.
>
> When I plot the normals and the tangents, I find that they
> are perpendicular, but a lot of times they are
> incorrect...the tangents sometimes are normals to the
> contour 1 which makes the normals tangent to it...
>
> Here is my code. Please help if you see my mistake!
>
> interpolatedP =
> csape(xPtsAutoContour,yPtsAutoContour,'periodic');
> tangent = fnder(interpolatedP);
>
> for idx=1:size(xPtsAutoContour)
>
> % tangent ax + by + c = 0
> a = ppval(tangent,xPtsAutoContour(idx))
> b = -1;
> c = yPtsAutoContour(idx) - a*xPtsAutoContour(idx)
>
> % normal Ax + By + C = 0
> A = -1/ppval(tangent,xPtsAutoContour(idx))
> B = -1
> C = yPtsAutoContour(idx) - A*xPtsAutoContour(idx)
>
> xNormal =
> (xPtsAutoContour(idx)-2):(xPtsAutoContour(idx)+2);
> yNormal = A*xNormal + C;
> %plot(xNormal,yNormal,'-g');
>
> xTangent = xNormal;
> yTangent = a*xTangent + c;
> %plot(xTangent,yTangent,'-m');
>
> for i=1:size(xPtsExpertContour)
> ptToNormalDistance(i) =
> abs(A*xPtsExpertContour(i) + B*yPtsExpertContour(i) +
> C)/sqrt(A^2+B^2);
> end
>
> % find closest point closest to the normal
> [smallestDistance, closestPtIdx] =
> min(ptToNormalDistance);
> closestXPt = xPtsExpertContour(closestPtIdx);
> closestYPt = yPtsExpertContour(closestPtIdx);
>
> plot([xPtsAutoContour(idx)
> closestXPt],[yPtsAutoContour(idx) closestYPt],'-b');
>
> end

Hi,

Did you work out a satisfactory solution to this problem? I'm trying to carryout the same task myself at the moment.

Thanks,
N.