Remove lines outside plotted circle

6 visualizaciones (últimos 30 días)
Xen
Xen el 20 de Mzo. de 2017
Respondida: Riya el 3 de Jun. de 2025
Hi people.
I am plotting a circle using the rectangle function and then I am plotting several lines in the same plot using the line function; the lines are within the circle but also extend out of it (of course). How can I keep only the part of the lines within the circle? Or maybe plot the lines initially with a method that somehow confines them within the circle.
I am sure this is easily done as an image analysis problem, but I was wondering if it can be done with plots.
Thanks.

Respuestas (1)

Riya
Riya el 3 de Jun. de 2025
Hi Xen,
I understand that you are plotting a circle using the “rectangle” function and adding lines that go beyond the circle. You want to show only the parts of the lines that are inside the circle.
This can be achieved using basic geometry and parametric line equations. The approach is to detect intersection points of the lines with the circle and then redraw only the segments that lie inside.
Kindly refer to the following sample code for the same:
% Define the circle parameters
center = [0, 0];
radius = 5;
% Draw the circle
theta = linspace(0, 2*pi, 500);
x_circle = center(1) + radius * cos(theta);
y_circle = center(2) + radius * sin(theta);
plot(x_circle, y_circle, 'k', 'LineWidth', 1.5);
axis equal; hold on;
% Define line segments [x1 y1 x2 y2]
lines = [
-6, -1, 6, 1;
-4, 4, 4, -4;
-10, 0, 10, 0
];
% Loop through each line
for i = 1:size(lines, 1)
x1 = lines(i, 1); y1 = lines(i, 2);
x2 = lines(i, 3); y2 = lines(i, 4);
dx = x2 - x1;
dy = y2 - y1;
a = dx^2 + dy^2;
b = 2 * (dx * (x1 - center(1)) + dy * (y1 - center(2)));
c = (x1 - center(1))^2 + (y1 - center(2))^2 - radius^2;
discriminant = b^2 - 4 * a * c;
if discriminant < 0
% Check if both points lie inside the circle
if norm([x1 y1] - center) < radius && norm([x2 y2] - center) < radius
plot([x1 x2], [y1 y2], 'r');
end
else
% Compute the intersection points
t1 = (-b + sqrt(discriminant)) / (2 * a);
t2 = (-b - sqrt(discriminant)) / (2 * a);
t_min = max(0, min(t1, t2));
t_max = min(1, max(t1, t2));
if t_max >= t_min
xi1 = x1 + dx * t_min;
yi1 = y1 + dy * t_min;
xi2 = x1 + dx * t_max;
yi2 = y1 + dy * t_max;
plot([xi1 xi2], [yi1 yi2], 'r', 'LineWidth', 2);
end
end
end
title('Clipped Lines Inside Circle');
This code reshapes the plotting so that only the segment of the line within the circle is shown. This works by calculating the intersection points using the quadratic formula and then restricting the line to the portion that lies inside the circle.
Here is the output of the above sample code for your reference:
For further reference you may refer to the following official documentation:

Categorías

Más información sobre Annotations en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by