0
$\begingroup$

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?

Thanks in advance

$\endgroup$

1 Answer 1

1
$\begingroup$

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}}

enter image description here

You could also just use RegionIntersection instead:

Graphics[{Red, lin, Blue, rec, PointSize[Large], Yellow, RegionIntersection[lin, rec]}]

enter image description here

$\endgroup$
2
  • $\begingroup$ 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 $\endgroup$
    – saimon
    Apr 16, 2019 at 14:40
  • 1
    $\begingroup$ @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 $\endgroup$
    – Carl Woll
    Apr 16, 2019 at 14:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.