# Comparing and Modifying two Matrices (list of list)

I need to compare two matrices with the same number of columns but a different number of rows (please see an example of Matrices A and B). I would like to know how I can compare the second column of the first matrix with the second column of the second matrix and if there were any equal value substitute the associated array in the first column of the first matrix with the associated array in the first column of the second matrix and restore the first Matrix. For example

A = {{1, 2, 3, 5}, {4, 5, 6, 8}, {7, 8, 9, 3}, {3, 56, 8, 2}, {4, 5, 6,
8}}

B = {{6, 7, 9, 1}, {2, 5, 0, 8}, {1, 2, 3, 7}, {34, 56, 78, 56}}


Considering that A[[2,2]]=B[[2,2]]=5 and A[[4,2]]=B[[4,2]]=56, after applying the above condition, the Matrix A should change to:

ANew= {{1, 2, 3, 5}, {2, 5, 6, 8}, {7, 8, 9, 3}, {34, 56, 8, 2}, {4, 5, 6,
8}}



General case:

What if the same elements were located in different rows (for example):

A = {{1, 2, 3, 5}, {4, 5, 6, 8}, {7, 8, 9, 3}, {3, 56, 8, 2}, {4, 5,
6, 8}};


B = {{6, 7, 9, 1}, {2, 5, 0, 8}, {1, 56, 3, 7}, {34, 42, 78, 56}};


In this case, considering that A[[2,2]]=B[[2,2]]=5 and A[[4,2]]=B[[3,2]]=56, after applying the above condition, the Matrix A should change to:

ANew= {{1, 2, 3, 5}, {2, 5, 6, 8}, {7, 8, 9, 3}, {1, 56, 8, 2}, {4, 5, 6,
8}}

• The question is unclear to me. You mentioned you want to "compare the second column of the first matrix with the second column of the second matrix", but then in the example you compare A[[2,4]]=B[[2,4]]=8, which are the elements in 2nd row and 4th column. – xzczd Jul 19 '20 at 7:20
• My apologies! Modified. – Mehdi Ebadi Jul 19 '20 at 14:51
• Again, the question becomes unclear. How should the A be modified if there multiple equivalent elements e.g. A[[2,2]]=A[[3,2]]=B[[1,2]]=B[[4,2]]=5? Also, the question looks like a XY problem, what exactly are you trying to do? – xzczd Jul 21 '20 at 2:13
• Thank you! I believe you are right! I can not use this procedure. This will make it impossible to solve if there are multiple equal values. Thanks again for your guidance. – Mehdi Ebadi Jul 21 '20 at 3:21

## 1 Answer

This script can be applied when the same elements are in the same row.

A = {{1, 2, 3, 5}, {4, 5, 6, 8}, {7, 8, 9, 3}, {3, 56, 8, 2}, {4, 5, 6, 8}};
B = {{6, 7, 9, 1}, {2, 5, 0, 8}, {1, 2, 3, 7}, {34, 56, 78, 56}};

l = Length /@ {A, B} // Min
(* 4 *)
truefalse = MapThread[Equal, {A[[;; l, 2]], B[[;; l, 2]]}]
(* {False, True, False, True} *)
index = Pick[Range[l], truefalse]
(* {2, 4} *)
Anew = A;
Anew[[index, 1]] = Pick[B[[;; l, 1]], truefalse]; Anew

• Thank you xzczd! – Mehdi Ebadi Jul 19 '20 at 19:36
• Thank you xzczd! I learned that in some cases the same elements are located in different rows (I modified the question for that case). How can I solve that issue? – Mehdi Ebadi Jul 20 '20 at 18:18