# How can I improve the speed of computing region intersection?

I have a polygon defined by a list of nodes (x,y). I want to cut the polygon by a horizontal line at position y = a and get the new polygon above the position y = a. I am using the RegionIntersect function, but it seems very slow if I want to combine the function with Manipulate function as well. Is there any way to improve my code to get better speed?

R2 = Polygon[{{0, 0}, {300, 0}, {300, 500}, {0, 750}}] ;
Manipulate[
R1 = ImplicitRegion[{0 <= x <=  300, a <= y <= 700}, {x, y} ];
R3 = RegionIntersection[R1, R2];
RegionPlot[R3], {a, 1, 499}]

• May be you can put R2 = Polygon[{{0, 0}, {300, 0}, {300, 500}, {0, 750}}]; outside Manipulate, so that it doesn't get evaluated everytime a changes. Mar 7, 2017 at 0:49
• It doesn't improve that much. The slider is not as smooth as I want it to be. Mar 7, 2017 at 1:06

It's a lot faster to find the intersection with a Polygon than with an ImplicitRegion. In your case you can write your region succinctly as a simple Polygon

DynamicModule[{R1, R2, R3},
R2 = Polygon[{{0, 0}, {300, 0}, {300, 500}, {0, 750}}];
Manipulate[
R1 = Polygon[{{0, a}, {300, a}, {300, 700}, {0, 700}}];
R3 = RegionIntersection[R1, R2];
RegionPlot[R3,
{a, 1, 499}]
]


If you want it faster, you can skip using RegionPlot, since your Region is just another Polygon. Something like this gives a good approximation of RegionPlot

DynamicModule[{R1, R2, R3},
R2 = Polygon[{{0, 0}, {300, 0}, {300, 500}, {0, 750}}];
Manipulate[
R1 = Polygon[{{0, a}, {300, a}, {300, 700}, {0, 700}}];
R3 = RegionIntersection[R1, R2];
Graphics[{
RGBColor[0.36, 0.5, 0.7],
EdgeForm[Directive[Thick, RGBColor[0.36, .5, .7]]],
Opacity[0.4],
R3},
Frame -> True, AspectRatio -> 5/6],
{a, 1, 499}]
]


On my machine doing everything in one step and discretizing the regions appears to smooth things out a bit.

Manipulate[
RegionPlot[
DiscretizeRegion@
RegionIntersection[
DiscretizeRegion@
Polygon[{{0, 0}, {300, 0}, {300, 500}, {0, 750}}],
DiscretizeRegion@
ImplicitRegion[{0 <= x <= 300, a <= y <= 700}, {x, y}]]], {a, 0, 500}]

• it actually smoothed things a bit, why was that ? I would have thought DiscretizeRegion would give the computer more work to do thus slower things down ! Mar 7, 2017 at 1:57
• I'm not exactly sure, but my guess would be that evaluating the expression symbolically is sufficiently more complicated then determining the RegionIntersection numerically. Mar 7, 2017 at 2:00
• I added an option, it seems to improve a bit MaxCellMeasure -> [Infinity] Mar 7, 2017 at 2:17
R1 = ImplicitRegion[{0<=x<=300,a<=y<=700},{x,y}];
R2 = Polygon[{{0,0},{300,0},{300,500},{0,750}}];
ineq = RegionMember[RegionIntersection[R1,R2],{x,y}]//Simplify//Rest
With[{ineq = ineq},
Manipulate[RegionPlot[ineq,{x,0,300},{y,0,700},PerformanceGoal->"Quality"],{a,1,499}]]