MATLAB: How to draw a tangent line from a given point to a circle in Matlab

tangent to circle

Hi I am trying to draw a tangent line from a given external point to a circle of known radius and origin as the center
Please help

Best Answer

Let P1 be a 1 x 2 row vector of the external point's cartesian coordinates and P2 a similar vector of the circle's center coordinates. Let r be the circle's radius. Then Q1 and Q2 below will be the two possible points of tangency of a line from P1. Q1 is to the right and Q2 to the left as viewed from P1 looking toward P2.
P = P1-P2;
d2 = dot(P,P);
Q0 = P2+r^2/d2*P;
T = r/d2*sqrt(d2-r^2)*P*[0,1;-1,0];
Q1 = Q0+T;
Q2 = Q0-T;