title: Subtracting a row vector from every Row in a matrix
body: <p>I was trying out something in an assignment I had. I wanted to subtract a row vector from every row of matrix(and then do further computations on it).
  I have a matrix "X" of dimensions m X n and another one centroid of dimension K x n. I tried two varients,</p>
  
  <pre><code>function idx = findClosestCentroids(X, centroids)
  K = size(centroids, 1);
  m=size(X,1);
  n=size(X,2);
  idx = zeros(size(X,1), 1);
  
  % ====================== CODE ======================
  % Instructions: Go over every example, find its closest centroid, and store
  %               the index inside idx at the appropriate location.
  %               Concretely, idx(i) should contain the index of the centroid
  %               closest to example i. Hence, it should be a value in the 
  %               range 1..K
  
  
  %This Doesnt Work
  % for i=1:m
          % temp=ones(size(centroids))*diag(X(i))-centroids;
          % temp=temp.^2;
          % [x,y]=min(sum(temp,2));
          % idx(i)=y;
  % endfor
  
  
  %This works!
  for i=1:m
      mini=1e10;
      minin=-1;
      for j=1:K
          temp=X(i,:)-centroids(j,:);
          temp=temp.^2;
          sumx=sum(temp);
          if (sumx&lt;mini)
              mini=sumx;
              minin=j;
          endif
      endfor
      idx(i)=minin;
  endfor
  
  % =============================================================
  
  end
  </code></pre>
  
  <p>The first one works while the second one doesn't even though acc. to what I tried, second is just the vectorized version of the first one. Please guide me through the vectorization.</p>