Not hard. But it takes a little effort. (I should post a tool for this on the FEX. SIGH. Actually, I have a tool that does this, but it is more complicated to use than I want it to be for me to post it.)

The general idea is to...

- Triangulate the region. If you have a convex region, bounded by a polygon, then there are many ways to do this.
- Determine the area of each triangle.
- Choose a random triangle inside the region, with probability based on the relative fraction of the area of the differfent triangles.
- Once you have the triangle, then generate a random point that lies uniformly inside the triangle.

Each of the above steps is easy enough in theory, though many users might find them complex. I can't say. In fact, all of the above steps are doable in a way that is fast, efficient, and even vectorized.

So, given a list of points that form a polygon, if the polygon is convex, a simple way to triangulate it is a delaunay triangulation. I'll want a list of vertices for later, so do it like this:

XY = [x(:),y(:)];

tri = delaunay(XY);

Or, you could do it using the delaunayTriangulation function. Or, you can do it by starting with the convex hull of the points, and then add on point at the centroid of the polygon. Then connect each edge of the convex hull to the centroidal point. Or, given a polygon, you could use ear clipping to create a triangulation. As I said, lots of ways to do it.

Next, we can compute the area of each triangle simply enough. In fact, this is easily done as a vectorized computation.

v1 = XY(tri(:,1),:);

v2 = XY(tri(:,2),:);

v3 = XY(tri(:,3),:);

v1 = v1-v3;

v2 = v2-v3;

areas = (v1(:,1).*v2(:,2) - v1(:,2).*v2(:,1))/2;

areas = areas/sum(areas);

Now, pick a random triangle, proportional to the relative area of each triangle. You can do this for many points at once, using the discretize tool. I'll assume you want to generate nsample points. I'll do these computations for the data provided, here, for 1000 points.

nsample = 1000;

R = rand(nsample,1);

tind = discretize(R,cumsum([0;areas]));

Next, for each triangle chosen, we will find ONE point that lives inside that triangle. Again, a vectorized computation.

v1 = XY(tri(tind,1),:);

v2 = XY(tri(tind,2),:);

v3 = XY(tri(tind,3),:);

R1 = rand(nsample,1);

xyrand = v1.*repmat(R1,[1 2]) + v2.*repmat(1-R1,[1 2]);

R2 = sqrt(rand(nsample,1));

xyrand = xyrand.*repmat(R2,[1 2]) + v3.*repmat(1-R2,[1 2]);

I used repmat above, but it is also easily done using scalar dimension expansion as found in R2016b or later, or using bsxfun.

Did it work?

plot(xyrand(:,1),xyrand(:,2),'.')

hold on

plot(x,y,'r-')

Of course. Uniformly generated samples in a polygonal region. Fully vectorized too.

## 0 Comments

Sign in to comment.