1
$\begingroup$

I would like to simplify a set of tests (meant to be applied on a random set of parameters), written for now as nested If:

Tableinit = {{"a", "b"}};
c = {1.8, 1.3, 2.5};
Do[Print[set = {RandomReal[{0, 3}], RandomReal[{0, 2}]}]; 
 testP = {a -> set[[1]], b -> set[[2]]};
 If[a > c[[1]] /. testP, 
  If[a > c[[2]] /. testP, 
   If[a > c[[3]] /. testP, Print["yaha"], Continue[]], Continue[]], 
  Continue[]], {3}]

So that I get for example:

{1.89136,0.143095}
{2.98853,1.98695}
yaha
{1.93,0.424178}

into a loop. The closest I got was:

Tableinit = {{"a", "b"}};
c = {1.8, 1.3, 2.5};
Do[Print[set = {RandomReal[{0, 3}], RandomReal[{0, 2}]}]; 
 testP = {a -> set[[1]], b -> set[[2]]};
 Do[If[a > c[[i]] /. testP, Print["yaha"], Break[]], {i, 3}], {3}]

But as expected I get:

{1.89136,0.143095}
{2.98853,1.98695}
yaha
yaha
yaha
{1.93,0.424178}
yaha

Instead of getting "yaha" only when the 3 conditions are fulfilled.

How could I write it? Any help will be greatly appreciated. Thanks.

$\endgroup$
  • 1
    $\begingroup$ Did you know that && does short-circuit evaluation? Use that to convert to a single If[]. $\endgroup$ – J. M. is away Sep 28 '17 at 2:16
  • $\begingroup$ Welcome to Mathematica Stack Exchange, and thanks for taking the time to format your question properly. $\endgroup$ – Mr.Wizard Sep 28 '17 at 5:47
  • $\begingroup$ Yes but the good thing about If [.. , .. , Continue[]] is that it will stop the calculations from the 1st condition that is not fulfilled. Won't it calculate all of them within the unique If with &&? $\endgroup$ – Elsa Sep 28 '17 at 7:13
  • $\begingroup$ "Won't it calculate all of them" - I suggest then that you look up what short-circuit evaluation means. $\endgroup$ – J. M. is away Sep 28 '17 at 7:55
  • $\begingroup$ Haha ok thanks! $\endgroup$ – Elsa Sep 28 '17 at 15:22
2
$\begingroup$
If[And @@ Thread[a > c /. testP], Print["yaha"]]
$\endgroup$
  • $\begingroup$ Equivalently: And @@ Thread[a > c /. testP] && Print["yaha"]; $\endgroup$ – Mr.Wizard Sep 28 '17 at 5:42
  • $\begingroup$ This will evaluate all three conditions as opposed to stopping at the first condition that fails. $\endgroup$ – J. M. is away Sep 28 '17 at 7:57

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.