A fully vectorised calculation of distances from a given set of points to a set of segments.
CSMV calculates distances from a given set of points to a set of linear segments
SYNOPSIS: [squared_distances_to_segments I t]=csmv(P,R,Q,to_plot)
[squared_distances_to_segments I t]=csmv(P,R,Q,...)
INPUT P,R : arrays of coordinates of 2n segment endpoints
(i.e., if there are n segments considered in pdimensional
Euclidean space, than P and R are nbyp matrices); the sizes of P
and R should coincide; p should be greater or equal than unity.
Q : an array of coordinates corresponding to the set of m points
from which distances to the segments PR are calculated
(Q should therefore be an mbyp matrix).
to_plot : (optional) graphical output.
Any nonzero value would cause the graphical output. There will be
no graphical output by default (if this parameter is not passed).
OUTPUT squared_distances_to_segments : an nbym matrix whose jth column
contains n squared distance from the jth point of Q to the segments PR.
I : a vector of m elements representing indices of the segments PR
which are the closest to points from Q.
t : an nbym matrix whose ijth element is a real number between 0
and 1 equal to P(i,:)Qi*(j,:)/P(i,:)R(i,:), where Qi*(j,:) is the
point on the segment P(i,:)R(i,:) closest to Q(j,:). Thus, for example, if
P(i,:) is closest to Q(j,:), then t(i,j)=0; if R(i,:) is closest to
Q(j,:), then t(i,j)=1.
NOTE: (i) the dimensions of P and R should coincide!
(ii) you may encounter an error if some points P and R coincide;
this can be easily avoided by suitably changing the code  feel
free to do so.
1.4  A third output argument is added. This explicitly indicates whether the closest points on the segments are inner points or the end points. 

1.3  onedimensional case is added (p=1) 

1.2  minor corrections in the description of the function csmv 

1.1  Small changes in the description of this function have been made. 
leila (view profile)
Does the tool specify whether closest point falls within the line segment or not?
Ben (view profile)
Andrei Bejan (view profile)
Steve, thanks!
I think I should complete this function by considering the case p=1. Will do soon.
Steve (view profile)
This is exactly what I needed. Thanks very much, that's a great contribution.