closest distance between a circle and a line in matlab

One approach to find the closest distance between a circle and a line is as follows:

  1. Find the closest point on the line to the center of the circle
  2. Find the distance between the closest point on the line and the center of the circle
  3. If the distance is less than the radius of the circle, then the closest distance is zero. Otherwise, the closest distance is the difference between the distance and the radius of the circle.

Here's the implementation of the above approach in MATLAB:

main.m
function dist = closestDistCircleLine(cx, cy, r, x1, y1, x2, y2)
    % Find the closest point on the line to the center of the circle
    vx = x2 - x1;
    vy = y2 - y1;
    wx = cx - x1;
    wy = cy - y1;
    c1 = vx * wx + vy * wy;
    if c1 <= 0
        % Closest point on the line is x1, y1
        dist = sqrt((cx - x1)^2 + (cy - y1)^2) - r;
        return;
    end
    c2 = vx * vx + vy * vy;
    if c2 <= c1
        % Closest point on the line is x2, y2
        dist = sqrt((cx - x2)^2 + (cy - y2)^2) - r;
        return;
    end
    frac = c1 / c2;
    qx = x1 + frac * vx;
    qy = y1 + frac * vy;

    % Find the distance between the closest point on the line and the center of the circle
    dist = sqrt((cx - qx)^2 + (cy - qy)^2) - r;

    % If the distance is negative, then the circle intersects the line
    if dist < 0
        dist = 0;
    end
end
865 chars
31 lines

Here, cx and cy are the coordinates of the center of the circle, r is the radius of the circle, x1, y1, x2, y2 are the coordinates of two points on the line. The function returns the closest distance between the circle and the line. If the distance is negative, the circle intersects the line.

related categories

gistlibby LogSnag