Home > Net >  The logic behind any() and if-statement
The logic behind any() and if-statement

Time:03-30

I have a code trying to realize a part of that:

I have matrix A as:

0.241 0.095 0.695
0.002 0.774 0.590
0.991 0.406 0.997
0.435 0.217 0.087
0.729 0.898 0.343

I dont understand the logic behind this statement:

if ((any(0.250 <= A[ ,3] & A[ ,3] <= 0.375)) == FALSE) {
   print("Done")
}

A[ ,3] gives 0.695 0.590 0.997 0.087 0.343

0.250 <= A[ ,3] gives TRUE TRUE TRUE FALSE TRUE

A[ ,3] <= 0.375 gives FALSE FALSE FALSE TRUE TRUE

and the if statement returns nothing, however, when I change 0.250 to 0.4:

0.4 <= A[ ,3] gives TRUE TRUE TRUE FALSE FALSE

A[ ,3] <= 0.375 gives FALSE FALSE FALSE TRUE TRUE

This time the if statement print "Done"

is that about the number of FALSE or TRUE?

CodePudding user response:

In the first case, 0.250 <= A[ ,3] & A[ ,3] <= 0.375 returns FALSE FALSE FALSE FALSE TRUE, the logical & returning TRUE only when both the statements are TRUE. The any() function then checks if any of the values passed to it evaluate to TRUE. Thus, it returns TRUE in this case, doesn't satisfy the conditon and doesn't enter the loop.

In the second case, 0.4 <= A[ ,3] & A[ ,3] <= 0.375 returns FALSE FALSE FALSE FALSE FALSE so any() function returns FALSE and satisfies the condition to enter the loop.

CodePudding user response:

This is very ugly logic, equivalent and simpler code if (all(A[ ,3] < 0.250 | A[ ,3] > 0.375)).

  • Related