# How to find the rows of a floating point matrix that match another?

Posted 9 years ago
3323 Views
|
2 Replies
|
1 Total Likes
|
 Hey there, community!I have two matrices of floating point numbers, I'll call them simply A and B. Now, A is of size 700x5, and B is of size 300x2. I know that the 300 pairs of numbers that B represents are a subset of the 700 pairs of numbers given by the second and third column of A (i.e. A[[;;,2;;3]]).I need to do the following: for each row in B, find a row in A where the second and third element match the ones in B, and create a new matrix where the rows of matrix B have been replaced by the corresponding rows of A. So, say that the matrices A and B are as follows: A= {{0, 0.5, 1, 1.5, 2}, {1, 1.5, 2, 2.5, 3}, {3, 4.5, 6, 5, 2}}; B = {{4.5, 6}, {1.5, 2}}; Then the output should be the following: Out: {{3, 4.5, 6, 5, 2}, {1, 1.5, 2, 2.5, 3}} Some additional details: B may contain the same pair several times, and so can A. However, if A has the same pair twice, then their respective rows are equal, so it doesn't matter which of these rows is "found". Since I am working with floating points, I cannot guarantee that the numbers will match exactly -- I expect they will, but I'd rather avoid any bugs caused by rounding errors. However, any numbers that differ from each other by less than 10^-8, say, can be treated as equal. This is actually the main reason I'm asking this question, because I could probably work out how to do the rest but I'm unsure about what kind of issues the floating point numbers may cause. As can be seen from the example above, the output matrix should have the same order as the matrix B; in other words, if we call the output C, then the matrix C[[;;,2;;3]] should be the same as B. Thanks in advance for any help!-Jonatan
2 Replies
Sort By:
Posted 9 years ago
 To being with, I'm renaming A to matA and B to matB. User defined expressions and objects usually being with a lower case letter to separate them from the ones that come pre-defined. Also this gives us more information about what the objects are. matA = {{0, 0.5, 1, 1.5, 2}, {1, 1.5, 2, 2.5, 3}, {3, 4.5, 6, 5, 2}}; matB = {{4.5, 6}, {1.5, 2}}; Given a row of B how can I find a corresponding row in A?The function (#[[{2, 3}]] == row &) returns True with the 2nd and 3rd element of the input are equal (==) to row. Note that Equal (==) is not exact. Two floating point numbers that are very close for example will be considered equal when using Equal (==). findReplacementInA[row_] := SelectFirst[matA, #[[{2, 3}]] == row &] findReplacementInA[{4.5, 6}] {3, 4.5, 6, 5, 2} How can I apply this operation on every row of B?Map[findReplacementInA, matB] or findReplacementInA /@ matB
Posted 9 years ago
 Thank you very much, that's exactly what I needed!