MATLAB: Intersection points between random polygon and a circle

circleintersectionMapping ToolboxMATLABpolygon

Hi, I have a random polygon (with known coordinates of the vertices) and a circle(with know center coordinates and center). I want to find the intersection points in between them. I have used linecirc function, but the problem is it also gives the intersection points which does not lie on the polygon. I have developed the following program, but sometimes it does not provide all the intersection points. Please help me to find out where I went wrong. Thanks
for i=1:length(V_x) %closed polygon with 7 vertices
V_x(8)=V_x(1);
V_y(8)=V_y(1);
m(i)=(V_y(i)-V_y(i+1))/(V_x(i)-V_x(i+1));
b(i)=-m(i)*V_x(i)+V_y(i);
[xout,yout] = linecirc(m(i),b(i),C_x,C_y,R);
crossX(i,1)=xout(1,1);
crossX(i,2)=xout(1,2);
crossY(i,1)=yout(1,1);
crossY(i,2)=yout(1,2);
DistCircleVertex(i)=distance(C_x,V_x(i),C_y,V_y(i));
EdgeLength(i)=distance(V_x(i),V_x(i+1),V_y(i),V_y(i+1));
DistPoint1Vertex1(i)=distance(V_x(i),crossX(i,1),V_y(i),crossY(i,1));
DistPoint1Vertex2(i)=distance(V_x(i+1),crossX(i,1),V_y(i+1),crossY(i,1));
DistPoint2Vertex1(i)=distance(V_x(i),crossX(i,2),V_y(i),crossY(i,2));
DistPoint2Vertex2(i)=distance(V_x(i+1),crossX(i,2),V_y(i+1),crossY(i,2));
%checking if intersection points lies on the polygon
if EdgeLength(i)==DistPoint1Vertex1(i)+DistPoint1Vertex2(i)& EdgeLength(i)==DistPoint2Vertex1(i)+DistPoint2Vertex2(i)
InpointX(i,1)=crossX(i,1);
InpointY(i,1)=crossY(i,1);
InpointX(i,2)=crossX(i,2);
InpointY(i,2)=crossY(i,2);
else if EdgeLength(i)==DistPoint1Vertex1(i)+DistPoint1Vertex2(i)
InpointX(i,1)=crossX(i,1);
InpointY(i,1)=crossY(i,1);
InpointX(i,2)=NaN;
InpointY(i,2)=NaN;
else if EdgeLength(i)==DistPoint2Vertex1(i)+DistPoint2Vertex2(i)
InpointX(i,1)=NaN;
InpointY(i,1)=NaN;
InpointX(i,2)=crossX(i,2);
InpointY(i,2)=crossY(i,2);
else
InpointX(i,1)=NaN;
InpointY(i,1)=NaN;
InpointX(i,2)=NaN;
InpointY(i,2)=NaN;
end
end
end
end

Best Answer

I have used linecirc function, but the problem is it also gives the intersection points which does not lie on the polygon.
Why not just discard the points that do not lie on the polygon? You can test this with inpolygon or with one of several File Exchange submissions, e.g.,