MATLAB: How to pick the points in meshgrid within a outline

alphashapeinshapemeshgrid

Hi,
I would like to identify the points in meshgrid that fall inside the outline below.
X = [0 2 2 4 4 5 5 3 3 0 0 1 1 0];
Y = [0 0 1 1 0 0 7 7 5 5 3 3 1 1];
It looks like this if I do: plot(X,Y)
2019-04-03 19_02_52-Figure 2.png
And I created the meshgrid below
del = 0.1;
x_min = min(X);
x_max = max(X);
y_min = min(Y);
y_max = max(Y);
[xg,yg] = meshgrid(x_min:del:x_max, y_min:del:y_max);
So my question is that is there an easy way to pick the points inside the outline?
I tried to use alphaShape and inShape, but they didn't work. The result always looked strange.
I have tried to come up with an algorithm but it's not universially applicable to all outlines. I wish there is a built-in function or something like that to do the job.
The final result should look somethign like this (without the lines fell outside of the outline):
Please advice.
Thank you,
Derek

Best Answer

inpolygon is celeberated function here.
X = [0 2 2 4 4 5 5 3 3 0 0 1 1 0];
Y = [0 0 1 1 0 0 7 7 5 5 3 3 1 1];
del = 0.1;
x_min = min(X);
x_max = max(X);
y_min = min(Y);
y_max = max(Y);
[xg,yg] = meshgrid(x_min:del:x_max, y_min:del:y_max);
idx = inpolygon(xg,yg,X,Y) ;
figure
hold on
plot(xg(~idx),yg(~idx),'.r')
plot(xg(idx),yg(idx),'.b')
plot(X,Y,'k')
untitled.bmp