Obtain a result by comparing the last column of two matrices?

123.png

Hi, everyone

I have a question to ask your help. I want to compare matrix A and B to derive the result {{1,2,3},{3,4,10},{5,7,9},{3,3,8}}. That is, I compare the last column of the two matrices to decide which row should be selected. For example, 3>2.5, so I choose {1,2,3}. I tried realize the result with MapThread and MaximalBy, but failed. Could you please tell me how to realize it? Thank you very much!

There may be other commands or ways to do this, but with the “If”, “Table” and “Part” commands you can also do this:

A = {{1, 2, 3}, {5, 6, 7}, {5, 7, 9}, {3, 3, 8}};
B = {{2.3, 2.8, 2.5}, {3, 4, 10}, {4, 2, 3}, {9, 6.3, 3}};

A // MatrixForm
B // MatrixForm

AB = Table[
   If[Last@A[[i]] > Last@B[[i]], A[[i]], B[[i]]], {i, 1, Length@A}];

AB // MatrixForm

If the last terms are the same and you want the row to come from A, change to >= , because with only > and the last terms are the same, the row will come from B.

If you wanted to learn a bit about MapThread then you could study this

A = {{1, 2, 3}, {5, 6, 7}, {5, 7, 9}, {3, 3, 8}};
B = {{2.3, 2.8, 2.5}, {3, 4, 10}, {4, 2, 3}, {9, 6.3, 3}};
f[u_,v_]:=If[Last[u] > Last[v],u,v];
MapThread[f,{A,B}]

or if you prefer this style

MapThread[If[Last[#1] > Last[#2],#1,#2]&,{A,B}]

Very good, Chaib, thank you for your answer!

Nelson, thank you very much for offering me other solutions?

If you would like your solution to generalise to more than two matrices as well, something like this could work:

MapThread[List /* MaximalBy[Last] /* First, {A, B}]

/* there is the RightComposition function.

Good, Jõgeva, thank you for your answer!