필터 지우기
필터 지우기

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

조회 수: 1 (최근 30일)
gsourop
gsourop 2018년 12월 17일
편집: John D'Errico 2018년 12월 17일
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
Stephen23
Stephen23 2018년 12월 17일
The if - else is not required:
answer0 = x0>min(x) && x0<max(x) && y0>min(y) && y0<max(y)

댓글을 달려면 로그인하십시오.

추가 답변 (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