 <p>Here's another vectorized approach. It tries all permutations of rows of <code>B</code>, and produces the optimal row-permuted <code>B</code> in matrix <code>Bresult</code>.</p> <pre><code>[m, n] = size(A); ind = perms(1:m); % // all permutations of row indices BB = permute(reshape(B(ind.',:),m,[],n),[1 3 2]); %'// all row-permuted B matrices C = sum(sum(abs(bsxfun(@minus, A, BB)),2),1); % // compute the sum for each [minsum, imin] = min(C); % // minimize Bresult = B(ind(imin,:),:); % // output result </code></pre>