As per my understanding, you have a set of points (let us say P) and each of them has a corresponding set of line segments (say Li for each Pi). Then, you want to find the nearest segment for each point.
The pseudo code for this should look like this,
for each Pi
for each Li
dist = distance(Pi, Li)
mindist(Pi) = min(mindist(Pi), dist)
However, I see four for loops in the code snippet you have provided.
Coming to the optimizations, as the calculations for each of the point-segment combinations are independent, we can parallelize this code. There are multiple options available,
- Vectorize the code. Update the function point_to_line to take vector of P, and a matrix of L as input, and then calculate the distance as a matrix operation(s).
- Use parfor. You can combine this with vectorization.
- Use GPU Coder. Keep the for loops and convert them to kernels.
As for the calculation of distance, it is
- Perpendicular distance from point to segment if the perpendicular intersection falls on the segment
- Otherwise, Smaller of the distance from the two vertices.
In your specific case, it might also be worth checking if there is any relationship between the closest segment, and the closest vertex (that is, whether the closest vertex is part of the closest segment. If so, you can simply calculate the Euclidean distance from all vertices.