I am using QGIS 3.10 and have shapefile that contains multiple polygons (1615 polygons to be precise). In order to calculate the "compactness" of the shape of each polygon I want to calculate the average distance between random points within each polygon. Therefore, I use the research tool "Random Points inside Polygon", which creates points within each of the polygons (e.g. 100 per polygon). However, I can't find a way to easily compute the distance between the points only within the same polygon. If I calculate the distance matrix, this would give me the distance between every random point irrespective if it is inside the same polygon or not (1615 x 100 points). Is there a way to tell QGIS to only compute the distance between points if they share the same value/feature (e.g. the polygon ID)?
You can use the QGIS DB Manager to create an SQL query using Virtual layers.
The following SQL code corresponds to the test layer I created. You need to change the names to match those of your data.
select a.rand_point_id, a.id, b.rand_point_id, b.id, distance(a.geometry, b.geometry) dist from r_points as a, r_points as b where a.id = b.id and a.rand_point_id != b.rand_point_id order by a.id
r_points is the random points layer, rand_point_id is the automatically generated point id and id is the polygon id.
A bit of a workaround , but you could do the following:
- Generate your
random points inside polygonstool normally. A unique ID is generated
- Run a distance matrix, using the unique ID generated as the required unique ID for the too, and specifying the
output matrix typeas
Standard N X T distance matrix
- Intersect the resulting
distance matrixwith the polygon layer.
The result is calculated from all points to all points, but you have an additional column you can use to differentiate which points fall within each polygon: