title: How to find the second lowest value in a tensorflow array
body: <p>I am writing a clustering algorithm and for part of it I calculate a euclidean distance matrix for each cluster of points. (FYI all of this is in Tensorflow). each cluster is a list of 8 dimensional vectors, which I then turn into one M*8 matrix. For each point in each cluster, I want to find the distance between it and its closest neighbor. I believe the most efficient way to do this would be to do compute pairwise distance between points for each cluster, and then find the second smallest value in each row of the resulting M*M matrix (because the smallest value in each row will always be 0, the distance between a given point and itself).</p>
  
  <p>Here is the code I use to create the euclidean distance matrix for each cluster:</p>
  
  <pre><code>    partitionedData = tf.dynamic_partition(inputs, pred, num_classes)
      for partition in partitionedData:
          N = tf.to_int32(partition.get_shape()[0])
          qexpand = tf.expand_dims(partition,1)
          qTexpand = tf.expand_dims(partition,0)
          qtile = tf.tile(qexpand,[1,N,1])
          qTtile = tf.tile(qTexpand,[N,1,1])
          deltaQ = qtile - qTtile
          deltaQ2 = deltaQ*deltaQ
          d2Q = tf.reduce_sum(deltaQ2,2)
  </code></pre>
  
  <p>The resulting matrix might look something like this (Note: this is a matrix of squares of distances):</p>
  
  <pre><code>[[  0.   8.   2.  18.]
   [  8.   0.  10.   2.]
   [  2.  10.   0.  20.]
   [ 18.   2.  20.   0.]]
  </code></pre>
  
  <p>for an input matrix of:</p>
  
  <pre><code>[[2,3],[4,5],[1,4],[5,6]]
  </code></pre>
  
  <p>What I would like to get in the end is the second smallest value in each row, in this case 2,2,2, and 2. Additionally, if there is a better way to find the distance to the nearest neighbor in tensorflow for every point in a cluster that is computationally efficient, that would be extremely helpful.</p>