title: Vectorize function that finds an array of nearest values
body: <p>I am still wrapping my head around vectorization and I'm having a difficult time trying to resolve the following function I made...</p>
  
  <pre><code>for i = 1:size(X, 1)
    min_n = inf;
    for j=1:K
      val = X(i,:)' - centroids(j,:)';
      diff = val'*val;
      if (diff &lt; min_n)
        idx(i) = j;
        min_n = diff;
      end
    end
  end
  </code></pre>
  
  <p><code>X</code> is an array of <code>(x,y)</code> coordinates...</p>
  
  <pre><code>2    5
  5    6
  ...
  ...
  </code></pre>
  
  <p><code>centroids</code> in this example is limited to 3 rows. It is also in <code>(x,y)</code> format as shown above.</p>
  
  <p>For every pair in <code>X</code> I am computing the closest pair of <code>centroids</code>. I then store the index of the centroid in <code>idx</code>.</p>
  
  <p>So <code>idx(i) = j</code> means that I am storing the index <code>j</code> of the centroid at index <code>i</code>, where <code>i</code> corresponds to the index of <code>X</code>. This means the closest centroid to pair <code>X(i, :)</code> is at <code>idx(i)</code>.</p>
  
  <p>Can I possibly simplify this via vectorization? I struggle with just vectorizing the inner loop.</p>