2
$\begingroup$

I have the following problem that is giving me headaches: I have a list with the elements in the following form:

{x,{{a1,b1},{a2,b2},{a3,b3}}}

I would like to select all the elements in this list that satisfy the following rules simultaneously:

  1. x<0
  2. ai x bi <0, where i is 1,2 or 3

I tried to use Select but I am having trouble getting it to apply the second condition.

$\endgroup$

2 Answers 2

3
$\begingroup$

Generating some toy data and testing:

ab = RandomInteger[{-10, 10}, {10, 3, 2}];
xs = RandomInteger[{-10, 10}, 10];
dat = Thread[{xs, ab}]
Select[dat, And[#[[1]] < 0, AnyTrue[#[[2]], Times @@ # < 0 &]] &]

enter image description here

$\endgroup$
6
  • $\begingroup$ Sorry but maybe I didn't explain it properly: the result I am looking for is: if a2 x b2 <0 then the result of Select should be {x,{a2,b2}}. Does it make sense? $\endgroup$
    – lucian
    Commented Nov 8, 2019 at 11:31
  • $\begingroup$ @lucian it would be helpful if you provided a toy example. Otherwise you can modify code and assess response. Starting with small test case is useful. I suggest also looking at AllTrue, AnyTrue etc in the documentation. $\endgroup$
    – ubpdqn
    Commented Nov 8, 2019 at 11:35
  • $\begingroup$ your toy data is exactly like my data. What I need to do is turn the list with elements in the form {x,{{a1,b1},{a2,b2},{a3,b3}} into a list (it can be smaller than the original list!) with elements {x,{a,b}} where the pair {a,b} is one of the three pairs in the original list such that a b<0 $\endgroup$
    – lucian
    Commented Nov 8, 2019 at 11:40
  • $\begingroup$ @lucian with respect that is somewhat different to OP. I encourage you to try, provide an example, esp given there may be more than one pair that meets your criteria and therefore require some mechanism for choosing be it something well defined or random. $\endgroup$
    – ubpdqn
    Commented Nov 8, 2019 at 11:43
  • $\begingroup$ you are probably right! I need to rethink my problem. Thank you! $\endgroup$
    – lucian
    Commented Nov 8, 2019 at 11:45
1
$\begingroup$

Using data setup from @ubpdqn 's answer:

SeedRandom[1];
ab = RandomInteger[{-10, 10}, {10, 3, 2}];
xs = RandomInteger[{-10, 10}, 10];
(dat = Thread[{xs, ab}]) // Grid[#, Alignment -> Right] &

f1 = Negative@*First;
f2 = ContainsAny[{-1}]@*Sign@*Map[Apply[Times]]@*Last;

(res = Fold[Select, dat, {f1, f2}]) // Grid[#, Alignment -> Right] &

enter image description here

$\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.