Shortest distance from point to line segment in 3D
Here is the implementation of the solution provided by Wolfram Alpha, as was suggested in the comments of the OP.

The implemented equation is: 

$$ d=\frac{|(\mathbf{x}_2-\mathbf{x}_1)\times(\mathbf{x}_2-\mathbf{x}_1)|}{|\mathbf{x}_1-\mathbf{x}_0|} $$ 

where

$$x_1=(x_1,y_1,z_1)$$
$$x_2=(x_2,y_2,z_2)$$

are two points on the line and \$x_0\$ is a third point.

function d = point_seg_dist(x0, x1, x2)

    % Make sure we are in 3D
    if length(x0) == 2
        x1(3) = 0;
        x2(3) = 0;
        x0(3) = 0;
    end

    % We want column arrays
    if size(x0,1) &lt; size(x0,2)
         x0 = P';
         x1 = x1';
         x2 = x2';
    end

    d = norm(cross(x2-x1 , x1-x0)) / norm(x2-x1);


Apart from a couple of checks on the input, the calculation is on one line and it does not need projections or checks on the projected point's position.