2
$\begingroup$

I have the list,

listx = {{0., -0.6}, {0.08, -1.}, {0.16, -0.9}, {0.24, 1.}, {0.32, 0.6}}

And I want to check if every second element satisfies both conditions ($ >= -1$ && $<= 1$).

I have tried my luck with AllTrue but I can't seem to make it work, this is what I have until now,

If[Do[AllTrue[listx, listx[[k, 2]] >= -1 && listx[[k, 2]] <= 1], {k, 1, 5, 1}], Print["a"]]

Care to help me out?

$\endgroup$
0

4 Answers 4

6
$\begingroup$

Since you were on the right track, we can keep the code pretty similar to what you had and basically just remove the do loop:

If[AllTrue[listx, -1 <= #[[2]] <= 1 &], Print["a"]]

The #[[2]] specifies that it should test the second part of each element of listx. You could just use # there and replace listx with listx[[All,2]] as well.

$\endgroup$
1
$\begingroup$

Your Do loop does not return a True, so the clause in your If statement never evaluates.

hasValidSecondElement[{_, x_}] := x >= -1 && x <= 1
hasValidSecondElement[___] := False

AllTrue[listx, hasValidSecondElement]
(* True *)

I defined a helper function for readability. When you go back to this code, it is clear what the intention was for a line like AllTrue[listx, hasValidSecondElement].

$\endgroup$
1
$\begingroup$

Edit:

  If[SameQ @@ (-1 <= #2 <= 1 & @@@ listx), Print["true"],Print["false"]]

Original Answer:

 n = Length@listx; 
If[Total@Boole@Table[-1 <= listx[[k, 2]] <= 1, {k, n}] == n, Print["a"]]

Or

n = Length@listx; 
If[Total@Boole[-1 <= #2 <= 1 & @@@ listx] == n, Print["a"]] 

n = Length@listx;
If[Count[-1 <= #2 <= 1 & @@@ listx, True] == n, Print["a"]]
$\endgroup$
1
  • $\begingroup$ Thank you very much, I'm gonna check it a little more and wait before marking it as solved, but I think you solved it!! $\endgroup$ Commented Dec 3, 2018 at 17:40
0
$\begingroup$

I think Thread allows for a really nice syntax here:

If[And @@ Thread[-1 <= listx[[All,2]] <= 1], Print["a"]]
$\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.