3
$\begingroup$

i am trying to find the Maximum difference between two matrices and identify where this maximum occurs.

I illustrate what I mean using an example. Given

X={{3, 1}, {8, 2}, {10, 3}}
Y={{5, 1}, {4, 2}, {5, 3}}

I calculate matrix which has (X-Y) and position as entries, specifically

d={{-2, 1}, {4, 2}, {5, 3}}

As out pout I would like to have

{5,3}

What is the best way to code this?

$\endgroup$
1
  • 1
    $\begingroup$ Ordering[Abs[X[[All, 1]] - X[[All, 2]]], -1][[1]] should give the the position 3. The value of the difference can than be found easily. $\endgroup$ Commented Apr 5, 2019 at 9:18

1 Answer 1

5
$\begingroup$

Depending on your taste,

d = MapThread[{#1[[1]] - #2[[1]], #1[[2]]} &, {X, Y}]

or

d = Transpose@{X[[All, 1]] - Y[[All, 1]], X[[All, 2]]}

define the differences d, if you need them. The symbol D is already in use in Mathematica, don't use it for variables.

Then you can compute

MaximalBy[d, Abs@*Last]

{{5, 3}}

As @HenrikSchumacher comments you don't really need the intermediate d though, and you don't need the second elements in each entry denoting their position: using Ordering is more elegant:

X = {3, 8, 10};
Y = {5, 4, 5};
j = First@Ordering[Abs[X - Y], -1]

3

(X - Y)[[j]]

5

$\endgroup$
1
  • $\begingroup$ Thank you so much $\endgroup$
    – user34047
    Commented Apr 5, 2019 at 18:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.