4
$\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
6
$\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$ Jun 22 at 22:17
3
$\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$
    – Szabolcs
    Jun 22 at 20:56
  • $\begingroup$ @Szabolcs, you are right. I don't remember ever getting UnitStep right in first try :) $\endgroup$
    – kglr
    Jun 22 at 22:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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