Using mean square error to create matlab index matrix

Mean Square Error

(MSE) is a method used to determine the difference between two blocks and can be calculated as follows: a

and b

two blocks of equal size

MSE = sqrt(sum(sum((a-b).^2)))/size(a or b)

      

If MSE

less than a predetermined threshold value, then the two blocks do not differ from each other.

Given two matrices a

and b

, the goal is to divide the two matrices into blocks of a given size, then extract the first block from A and let it be a

, then search for a block b

from b

where Mean Square Error

between a

and is b

less than a given threshold, then return the position of the block b

from the matrix b

. etc. and here's an example:

For two matrices a

and b

where:

A= [1 1   4 4   2 2 
    1 1   4 4   2 2

    2 2   9 9   5 5
    2 2   9 9   5 5

    3 3   4 4   9 9
    3 3   4 4   9 9];

B = [ 2 2   4 4   9 9
      2 2   4 4   9 9];

      

the threshold is 2

The first block a

obtained from the matrix a

is:

1 1
1 1

      

Block b

derived from the matrix b

that the MSR is between a

and b

less than the threshold:

2 2
2 2

      

Therefore, we return the position of the block b

in the matrix b

, which is 1

The second block a

obtained from the matrix a

is:

4 4
4 4

      

A block b

derived from a matrix b

where the MSR is between a

and b

less than the threshold:

4 4
4 4

      

Therefore, we return the position of the block b

in the matrix b

, which is 2. and so on.

The end result should be as follows:

RES= [1 2 1
      1 3 2
      1 2 3];

      

Is there a faster way?

+3


source to share


1 answer


Here's a vector approach with bsxfun

.

First define the data:

A = [1 1   4 4   2 2 
     1 1   4 4   2 2
     2 2   9 9   5 5
     2 2   9 9   5 5
     3 3   4 4   9 9
     3 3   4 4   9 9];  %// data: A
B = [2 2   4 4   9 9
     2 2   4 4   9 9];  %// data: B
m = 2;                  %// number of rows per block
n = 2;                  %// number of cols per block

      

Then apply the following steps:



  • Modify matrices so that each block is a row (inspired by this great answer ).
  • Calculate MSE for all block pairs.
  • Find argmin MSE relative to blocks B

    (for each block A

    ). Note that if B

    there are multiple minimizing blocks in, this finds the first one.
  • Output the result to a matrix.

code:

A2 = reshape(permute(reshape(A, size(A, 1), n, []), [2 1 3]), n*m, []);  %// step 1
B2 = reshape(permute(reshape(B, size(B, 1), n, []), [2 1 3]), n*m, []);
mse = squeeze(sum(bsxfun(@minus, A2, permute(B2,[1 3 2])).^2, 1));       %// step 2
[~, result] = min(mse, [], 2);                                           %// step 3
result = reshape(result, size(A,1)/m, size(A,2)/n);                      %// step 4

      

+1


source







All Articles