6
$\begingroup$

I have two lists

a = {{3,1,2},{5,1,3},{4,1,1}}
b = {{4,0,3},{4,2,2},{5,0,2}}

And would like to compare each element within

If{a>b,1,0}

expecting the result

{{0,1,0},{1,0,1},{0,1,0}}

but it doesn't work, how can I get this type of comparison?

$\endgroup$
4
  • 1
    $\begingroup$ Strongly related $\endgroup$ Commented May 18, 2019 at 18:57
  • $\begingroup$ you could use 1-UnitStep[b-a]? $\endgroup$
    – kglr
    Commented May 18, 2019 at 19:02
  • $\begingroup$ Of course, fixed. $\endgroup$
    – Three Diag
    Commented May 18, 2019 at 19:02
  • $\begingroup$ @kglr yep, that achieves the result, thanks $\endgroup$
    – Three Diag
    Commented May 18, 2019 at 19:05

3 Answers 3

11
$\begingroup$
Boole@Positive[a-b]

{{0, 1, 0}, {1, 0, 1}, {0, 1, 0}}

1-UnitStep[b-a]

{{0, 1, 0}, {1, 0, 1}, {0, 1, 0}}

$\endgroup$
3
$\begingroup$

kglr took the fast, vectorized operations. Here are some less optimal ones that you can have a look at for fun or for learning:

Boole@MapThread[Greater, {a, b}, 2]

{{0, 1, 0}, {1, 0, 1}, {0, 1, 0}}

Boole@Apply[Greater, Transpose[{a, b}, {3, 2, 1}], {2}]

{{0, 1, 0}, {1, 0, 1}, {0, 1, 0}}

$\endgroup$
2
$\begingroup$
a = {{3, 1, 2}, {5, 1, 3}, {4, 1, 1}};

b = {{4, 0, 3}, {4, 2, 2}, {5, 0, 2}};

Using Ramp (new in 11.0)

Ramp[a - b]

{{0, 1, 0}, {1, 0, 1}, {0, 1, 0}}

$\endgroup$

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.