How to find if a pair is within an unorthogonal area with parallel sides?

1 view (last 30 days)
Hi everyone,
Suppose I have the area within the following x,y pairs, (3,1), (3,5), (12,1), (12,7), (6,5) and (6,7). I would like to test whether a random pair, say (5,6) is inside the area of interest. Is there any way to generalize the code to test for any random pairs?
I would appreciate any help. Thanks in advance.
John D'Errico
John D'Errico on 17 Dec 2018
Edited: John D'Errico on 17 Dec 2018
And I stated explicitly that the answer I posted to your last question had no need for parallel sides, that it would work on ANY polygon. READ THE ANSWER. It does not even require the polygon has only 4 vertices. As long as the points form a polygon, which convhull can help you to fix, it works. And if your polygon is not convex, it still works.

Sign in to comment.

Accepted Answer

John D'Errico
John D'Errico on 17 Dec 2018
Edited: John D'Errico on 17 Dec 2018
Was it really necessary to post this, when I just answered that same question in your last? Sigh.
A better solution, rather than such nested, specific tests, is to use a tool like inpolygon. Make sure they are sorted, so it truly represents a polygon, in that order. But the points are easily sorted in terms of angle.
px = [1 , 3 , 3 , 1];
py = [5 , 5 , 7, 7];
ans =
In newer releases of MATLAB, we also have the polyshape tools.
PS = polyshape(px,py)
PS =
polyshape with properties:
Vertices: [4×2 double]
NumRegions: 1
NumHoles: 0
ans =
The nice thing about inpolygon and polyshape is these tools are not restricted to simple rectangular, 90 degree polygons.
So, if your points are not known to lie in a good order to represent a polygon, we could convert to polar coordinates, and then sort the sequence of points around the centroid. Simpler is to just use a convex hull to do the heavy thinking for you. So if I swap points 3 and 4, so the polygon turns into sort of a figure 8, we can easily recover a proper order:
px = [1 , 3 , 1, 3];
py = [5 , 5 , 7, 7];
edgelist = convhull(px,py)
edgelist =
PX = px(edgelist)
PX =
1 3 3 1 1
PY = py(edgelist)
PY =
5 5 7 7 5
So even though the points in px and py were mi-sorted, convhull reordered them. It also connected the polygon, so the first and last point were the same, but tools like inpolygon and polyshape won't care.

More Answers (0)


Find more on Elementary Polygons in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!