Question: I have 2 matrices with equal number of rows and columns. A(4x3) and B(4x3).

I would like to match rows of A with rows of B so that when subtracting I get minimum sum. Example of how inside of A and B look like:

```
A=  -0.3612   -0.1911   -15.3818
     0.0376    0.0206    0.3498
     0.0418    0.0229    0.3887
     0.0188    0.0103    0.1749

```

I'm doing this:

```
for j=1:size(B,1)
    [vv, inds]=min(sum(abs(bsxfun(@minus,A,B(j,:))),2));
    minJJ(j,:)=vv;  
    indsMatch(j,:)=inds;
    MM=min( minJJ);

    [A,ps] = removerows(A,'ind',inds);
    [B,ps] = removerows(B,'ind',j); 
end

```

I get the error:

> 
> Improper assignment with rectangular empty matrix.
> 
> 
> 

What I'm trying to get with this is `indsMatch`. I want 'order of rows indexes' of matrix A that are paired with rows of B (based on min difference). Indexes of B is kept 1 2 3 4.

Answer: 
Here's another vectorized approach. It tries all permutations of rows of `B`, and produces the optimal row-permuted `B` in matrix `Bresult`.

```
[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

```
Brute-Force, but vectoriced.

```
%// data
A = [ -0.3612   -0.1911   -15.3818
     0.0376    0.0206    0.3498
     0.0418    0.0229    0.3887
     0.0188    0.0103    0.1749 ]
B = flipud(A) + 0.2

%// number of rows and columns
[n,m] = size(A);
allcombs = perms(1:n).';  %'
%// all sortings of A
AA = A(allcombs(:),:)
%// repeat whole matrix B n! times
BB = repmat(B,factorial(n),1)
%// differences
D = bsxfun(@minus, AA, BB)
%// sum(abs( ... ))
E = blockproc(D,[n,m],@(x) sum(abs( x.data(:) )))
%// idx of minimum set
[~,idx] = min(E)

%// output
Aout = AA(idx:idx+n-1,:)
Bout = BB(idx:idx+n-1,:)

```

**This method will probably fail for n > 11 or even less.**

`blockproc` requires the **Image Processing toolbox.**