7
$\begingroup$

Suppose I have the following lists:

dat1 = {{43, 12.0541}, {44, 10.789}, {45, 9.505}}; dat2 = {{43, 11.60940}, {44, 10.693}, {45, 9.764}}; 

How can I implement Pick or Select to select from dat1 the elements that have the second array position > than the correspondenting array position of dat1. In this simple explemple, the the element is {45, 9.764}. I tried to use something like that:

Pick[dat1, dat2, dat2[[2]] > dat1[[2]]] 
$\endgroup$
0

4 Answers 4

7
$\begingroup$

You can use my BoolEval package:

<< BoolEval` 

Use an all matrix elements:

BoolPick[dat1, dat1 > dat2] (* {{12.0541}, {10.789}, {}} *) 

Use the second part of each sub-element:

BoolPick[dat1, dat1[[All, 2]] > dat2[[All, 2]]] (* {{43, 12.0541}, {44, 10.789}} *) 

How does it work?

BoolPick[x,y] is just a shorthand for Pick[x, BoolEval[y], 1]. You can see what BoolEval does by evaluating it with symbolic arguments:

BoolEval[a > b] (* 1 - UnitStep[-a + b] *) 

BoolEval is the engine that makes BoolPick so fast.

BoolEval (not BoolPick) is also available as a resource function, but I recommend the package version for slightly better performance and convenience functions such as BoolPick.

$\endgroup$
1
  • $\begingroup$ Amazing! This is exactly what i was looking for. $\endgroup$ Commented Jun 22, 2021 at 22:17
5
$\begingroup$
Pick[dat1, 1 - UnitStep[dat1[[All, 2]] - dat2[[All, 2]]], 1] 
{{45, 9.505}} 

Alternatively,

Pick[dat1, Positive[dat2[[All, 2]] - dat1[[All, 2]]]] 
{{45, 9.505}} 

Pick from dat2 using the same condition:

Pick[dat2, 1 - UnitStep[dat1[[All, 2]] - dat2[[All, 2]]], 1] 
{{45, 9.764}} 
Pick[dat2, Positive[dat2[[All, 2]] - dat1[[All, 2]]]] 
{{45, 9.764}} 
$\endgroup$
2
  • 3
    $\begingroup$ This picks those elements where dat2[[All, 2]] >= dat1[[All, 1]]. Note >= not >. OP asked for >. It is very easy to make small mistakes like this when writing inequalities in terms of UnitStep. This is why BoolEval is so useful: it does it for you automatically. $\endgroup$ Commented Jun 22, 2021 at 20:56
  • $\begingroup$ @Szabolcs, you are right. I don't remember ever getting UnitStep right in first try :) $\endgroup$ Commented Jun 22, 2021 at 22:00
4
$\begingroup$
a = {{43, 12.0541}, {44, 10.789}, {45, 9.505}}; b = {{43, 11.60940}, {44, 10.693}, {45, 9.764}}; 

Using Extract

Extract[b, Position[a - b, {_, _?Negative}]] 

{{45, 9.764}}

$\endgroup$
2
$\begingroup$
a = {{43, 12.0541}, {44, 10.789}, {45, 9.505}}; b = {{43, 11.60940}, {44, 10.693}, {45, 9.764}}; 

Using Select:

Last /@ Select[Thread[{a, b}], ! FreeQ[#[[1]] - #[[2]], _?Negative] &] (*{{45, 9.764}}*) 
$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.