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

closest value

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.

Best Answer

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];
inpolygon(2,6,px,py)
ans =
logical
1
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
isinterior(PS,2,6)
ans =
logical
1
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 =
1
2
4
3
1
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.