How can I determine is (x,y) pair is inside an orthogonal area?

1 次查看(过去 30 天)
Hi everyone,
Suppose we have an orthogonal area where the 4 x,y pairs are (1,5) , (3,5) , (1,7) and (3,7). I would like to test if a random pair, such as (0,6), is inside the orthogonal area. I did the following code but I don't get any answer:
x = [1, 3];
y = [5, 7];
x0 = 0;
y0 = 6;
if x0 < x(2)
if x0 > x(1)
if y0 < y(2)
if y0 > y(1)
answer0 == 1
else
answer0 == 0
end
end
end
end

采纳的回答

Rik
Rik 2018-12-17
编辑:Rik 2018-12-17
Your else statement is only reached in the inner part. If you want to use this structure, you should do the following:
x = [1, 3];
y = [5, 7];
x0 = 0;
y0 = 6;
answer0 =false;
if x0 < x(2)
if x0 > x(1)
if y0 < y(2)
if y0 > y(1)
answer0 = true;
end
end
end
end
However, a more compact/clearer way is this:
x = [1, 3];
y = [5, 7];
x0 = 0;
y0 = 6;
if x0>min(x) && x0<max(x) && ...
y0>min(y) && y0<max(y)
answer0=true;
else
answer0=false;
end

更多回答(1 个)

John D'Errico
John D'Errico 2018-12-17
编辑:John D'Errico 2018-12-17
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.

类别

Help CenterFile Exchange 中查找有关 Elementary Polygons 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by