MATLAB: How to check if a line segment intersects a circle

circlegeometryImage Processing Toolboxintersection of line and circleline

is there any formula to check whether a line intersects a circle in matlab.can someone help me out. suppose i have got a line segemtn with ends x,y and x1,y2 and there is a circle with centre h,k with radius r. how can i know if the line segement intersects the circle or not

Best Answer

Calculate the distance between the line and the center of the circle:
P1 = [-2, -2]; % Point 1 of the line
P2 = [2, 2]; % Point 2 of the line
C = [0, 0]; % Center of circle
R = 2; % Radius of circle
P12 = P2 - P1;
N = P12 / norm(P12); % Normalized vector in direction of the line
P1C = C - P1; % Line from one point to center
v = abs(N(1) * P1C(2) - N(2) * P1C(1)); % Norm of the 2D cross-product
doIntersect = (v <= R);
The geometrical explanation is easy: The cross-product replies the area of the parallelogram build by the normal of the line and the vector fro P1 to C. The area of this parallelogram is identical to the area of the rectangle build by the normal N and the vector orthogonal to N through C. The value of this area is the distance multiplied by 1 (the length of the N). Summary: The distance between the line and a point in 2D is the absolute value of the 3rd component of the cross-product between N and the vector from P1 (or P2) to C.
All you have to do is to compare, if this distance is smaller or equal to the radius.
In 3D the norm of the 3D cross-product is needed:
v = norm(cross(N, P1C));