# Solve: line and rectangle intersections

I have been trying to find the intersections between a rectangle and a line, following the example given in the Solve function:

Solve[{x, y} ∈ Line[{{-1, 0}, {2, 1}}] && {x, y} ∈
Circle[], {x, y}]
Graphics[{{Blue, Line[{{-1, 0}, {2, 1}}],
Circle[]}, {PointSize[Large], Red, Point[{x, y}] /. %}}]


this code works well of course, finding both intersections between the circle and the line. However, if I try to substitute the circle with a rectangle the code stops working:

lin := Line[{{-2, -3}, {2, 1}}]
rec := Rectangle[{-1, -1}, {1, 1}]
Solve[{x, y} ∈ lin && {x, y} ∈ rec, {x, y}]
Graphics[{{Red, lin, Blue, rec}, {PointSize[Large], Yellow,
Point[{x, y}] /. %}}]


Any idea of how to make it work?

The problem is that Rectangle has dimension 2, so the intersection of lin and recis a line and not 2 points. You can fix this by taking the boundary of the Rectangle instead:

lin = Line[{{-2, -3}, {2, 1}}]
rec = RegionBoundary @ Rectangle[{-1, -1}, {1, 1}]
Solve[{x, y} ∈ lin && {x, y} ∈ rec, {x, y}]
Graphics[{
{Red, lin, Blue, rec},
{PointSize[Large], Yellow, Point[{x, y}] /. %}
}]


Line[{{-2, -3}, {2, 1}}]

Line[{{-1, -1}, {1, -1}, {1, 1}, {-1, 1}, {-1, -1}}]

{{x -> 0, y -> -1}, {x -> 1, y -> 0}} You could also just use RegionIntersection instead:

Graphics[{Red, lin, Blue, rec, PointSize[Large], Yellow, RegionIntersection[lin, rec]}] • thanks, I was about to write that I solved the issue using a polyline instead of a rectangle. Your solution seems much simpler in practice though. I have been trying to implement your code, but for some reason the RegionBoundary function seems not to work (it remains blue in the code). It looks like the built-in function is read as a variable with no value assigned... I am perplexed – saimon Apr 16 at 14:40
• @saimon RegionBoundary was introduced in M10, so you must be using an earlier version. In that case, you need to convert the Rectangle to a polyline yourself – Carl Woll Apr 16 at 14:51