-1

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?

LegendofPedro
  • 1,393
  • 2
  • 11
  • 23
  • 1
    Please explain what you mean by "approximate". Do you mean the numbers which round/ceil/floor to the same number? If yes then upto how many decimal places? Or do you mean the numbers which are in some +- range ? If yes then how do you define that range? – Sardar Usama Nov 02 '19 at 21:14
  • Do you want to return the value from A or B? Or the index/indeces? – LegendofPedro Nov 02 '19 at 23:54

1 Answers1

1

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
Mike Scannell
  • 378
  • 1
  • 12