Message Boards Message Boards

0
|
7494 Views
|
6 Replies
|
1 Total Likes
View groups...
Share
Share this post:

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

Posted 5 years ago

enter image description here

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!

POSTED BY: Shaoyan Robert
6 Replies

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.

POSTED BY: Gerli Jõgeva
Posted 5 years ago

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

POSTED BY: Shaoyan Robert
Posted 5 years ago

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}]
POSTED BY: Bill Nelson
Posted 5 years ago

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

POSTED BY: Shaoyan Robert

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

im1

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.

POSTED BY: Claudio Chaib
Posted 5 years ago

Very good, Chaib, thank you for your answer!

POSTED BY: Shaoyan Robert
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract