Set value for elements within a polygon

Hi all,
I am new to Matlab and trying to solve a problem with polygon.
I want to create a random 2-D matrix, let's say 100 by 100 as a domain.
domain=ones(100);
Then by enter the x & y coordinates of the polygon, I would like to draw that polygon and set all the elements inside the polygon to a different value.
xv=[40;50;60;50;40];
yv=[60;50;60;70;60];
plot(xv,yv) %plot the polygon
in=inpolygoon(xq,yq,xv,xv);
domain(in)=2;
I am stuck right here, I dont know how to define xq and yq to complete the inpolygon syntax. Please help :(.
Thank you all.

 採用された回答

Matt J
Matt J 2021 年 8 月 7 日
編集済み: Matt J 2021 年 8 月 7 日

0 投票

If you have the Image Processing Toolbox,
domain=ones(100);
xv=[40;50;60;50;40];
yv=[60;50;60;70;60];
in = roipoly(domain,xv,yv);
domain( in )=2;
imshow(domain); caxis([0,2])

3 件のコメント

Anh Mai
Anh Mai 2021 年 8 月 8 日
Thanks for your suggestion. I just realized that I also can do the following syntax, look amateur but it works. lol.
domain=ones(100);
count=1;
for i=1:100
for j=1:100
xq(count)=i;
yq(count)=j;
count=count+1;
end
end
xv=[10;40;70;10];
yv=[50;30;50;50];
in=inpolygon(xq,yq,xv,yv);
domain(in)=2;
imagesc(domain);
Matt J
Matt J 2021 年 8 月 8 日
編集済み: Matt J 2021 年 8 月 8 日
That will be very slow. Sean's answer does essentially the same thing, but much faster. My answer will be even faster than that, if you have the required toolbox.
Anh Mai
Anh Mai 2021 年 8 月 9 日
Yup, that's true. That's why I said it might look amateur :)). Thanks again for the solution.

サインインしてコメントする。

その他の回答 (1 件)

Sean de Wolski
Sean de Wolski 2021 年 8 月 7 日

1 投票

Something along this line will work too. Note, you may need to deal with x/y v. row/col indexing (swap meshgrid for ndgrid).
domain = ones(100);
[xx,yy] = meshgrid(1:100);
xv=[40;50;60;50;40];
yv=[60;50;60;70;60];
% plot(xv,yv) %plot the polygon
xvec = xx(:);
yvec = yy(:);
in=inpolygon(xx(:),yy(:),xv,yv);
domain(sub2ind([100 100],xvec(in),yvec(in)))=2;
imshow(domain); caxis([0,2])

1 件のコメント

Matt J
Matt J 2021 年 8 月 8 日
編集済み: Matt J 2021 年 8 月 8 日
No need for sub2ind that I can see:
domain( inpolygon(xx(:),yy(:),xv,yv) )=2;

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeGraphics Performance についてさらに検索

製品

リリース

R2021a

タグ

質問済み:

2021 年 8 月 7 日

コメント済み:

2021 年 8 月 9 日

Community Treasure Hunt

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

Start Hunting!

Translated by