matlabapproximate

How to find the approximate numbers in two matrix?


How to find the approximate numbers in two matrix? For example, There are two matrixes

A=[1.567 1.679 1.366 ;
      2.467 3.587 6.134 ;
      3.497 5.877 9.465]

B=[3.134 5.100 7.555 ;
      7.465 4.715 4.267 ;
      2.347 4.111 4.503]

So in A matrix 2.467 is close to 2.347 in B matrix. How can I find them by coding?


Solution

  • Create a meshgrid of all the values in A and all the values in B so we can compare them:

    [Amesh,Bmesh] = meshgrid(A(:),B(:))
    

    Now find the absolute value of the difference:

    absdiff = abs(Amesh-Bmesh)
    

    This is a matrix of the absolute difference between every value in A vs. every value in B. So the minimum value in this table is your closest match between a value in A and B. To programatically find that value:

    [x,y] = find(absdiff == min(absdiff(:)))
    x =
         3
    y =
         2
    

    This calculates the minimum value of that matrix, and then finds the x/y position of that value. In this case x is the index into matrix B and y is the index into matrix A.

    >> A(y)
    ans =
        2.4670
    >> B(x)
    ans =
        2.3470