5
$\begingroup$

Given a list of values

list1 = {2.4, 3.4, 5.9, 1.2, 9.5, 7.5}

and a another list containing theoretical maximum values

list2 = {3, 4, 6, 2, 9, 7}

I wish to select those values from list1 which are less than the corresponding maximum value. So from my example I would get the values

{2.4, 3.4, 5.9, 1.2}

Something like this (which doesn't work)

Select[list1, # < list2] &
$\endgroup$
  • 1
    $\begingroup$ Pick[list1, Thread[Less[list1, list2]]]... $\endgroup$ – ciao Oct 2 '15 at 0:52
  • $\begingroup$ @ciao ); I was about to post exactly the same !!! $\endgroup$ – SquareOne Oct 2 '15 at 0:53
  • 1
    $\begingroup$ @SquareOne: That's probably the canonical way, and Pick[list1, UnitStep[Subtract[list1, list2]], 0] if speed matters for huge lists... $\endgroup$ – ciao Oct 2 '15 at 0:57
  • $\begingroup$ Thank you ciao. I didn't know Pick existed. $\endgroup$ – Steven Anderson Oct 2 '15 at 0:58
  • 1
    $\begingroup$ @SquareOne: Ah, these are really not "answer" material IMO, feel free to if you'd like. Second is faster for a couple of reasons: most times if you can do things arithmetically, you gain speed (intrinsic speed of simple math ops in MMA, under-the-covers parallelization/divide-n-conquer/etc.), and some operations (like Pick) use optimized strategies when they "know" things about the data structures - like a target has been Unitized or UnitSteped - so second form can be orders of magnitude faster on large lists - try it! $\endgroup$ – ciao Oct 2 '15 at 1:05
9
$\begingroup$

ciao's method is good.

Pick[list1, Thread[Less[list1, list2]]]
{2.4, 3.4, 5.9, 1.2}

Another -- perhaps more direct -- way to do it is

MapThread[If[#1 <= #2, #1, Nothing] &, {list1, list2}]
{2.4, 3.4, 5.9, 1.2}
$\endgroup$
1
$\begingroup$
Cases[Transpose[{list1, list2}], {a_, b_} /; a < b :> a]

{2.4, 3.4, 5.9, 1.2}

$\endgroup$
  • $\begingroup$ what does the a <b:>a do in your logic? I see that it works I just don't understand how. $\endgroup$ – Steven Anderson Oct 14 '15 at 14:28

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.