# Calculating distance between points only within same polygon in QGIS

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)? • Distance of points to... what? – 15Step Mar 1 at 9:40
• Ah sorry for the unclear description. I want to calculate the distance between each of the random points within the same polygon. So if there are 100 points within one polygon, I want to calculate for each of these 100 points the dsitance to the remaining 99 points. Basically a distance matrix between points at the polygon level. – Random_GIS_dude Mar 1 at 9:53
• Have a look at this question: gis.stackexchange.com/questions/386866/… - it deals with a similar issue, but uses a different approach. – Erik Mar 1 at 10:01

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:

1. Generate your `random points inside polygons` tool normally. A unique ID is generated
2. Run a distance matrix, using the unique ID generated as the required unique ID for the too, and specifying the `output matrix type` as `Standard N X T distance matrix`
3. Intersect the resulting `distance matrix` with 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: • Thanks, that works as well with a bit or workaround. – Random_GIS_dude Mar 1 at 11:39