5
$\begingroup$

How do I use relational operators on vectors?

{1, 2, 3} > {0, 1, 2}
(*outputs {1, 2, 3} > {0, 1, 2}*)

More generally, I want {a,b}>{c,d} to be equivalent to a>c && b>d. Or, I would want to say vars>0 where vars is a vector of my variables and that one constraint forces them all to be strictly positive. How might I achieve that?

$\endgroup$
8
$\begingroup$
And @@ Thread[{a, b} > {c, d}]

(* a > c && b > d *)
| improve this answer | |
$\endgroup$
  • $\begingroup$ Great! And copying that for the vars>0 example: And @@ Thread[vars > Flatten[ConstantArray[0, {Length[vars], 1}]]] works. $\endgroup$ – Shane Mar 22 '16 at 20:11
5
$\begingroup$

Here is a new operator ( ,alias \[NestedGreaterGreater] ) that is a generalisation of the built-in > :

NestedGreaterGreater[x___] := And @@ Thread[Greater[x]]

This permits interesting operations :

  • {a, b} ⪢ {c, d}

(a > c) && (b > d)

  • {a, b} ⪢ {c, d} ⪢ {e, f}

(a > c > e) && (b > d > f)

  • {a, b} ⪢ c ⪢ {d, e}

(a > c > d) && (b > c > e)

For clearity some parenthesis have been added in the previous results.

| improve this answer | |
$\endgroup$
  • $\begingroup$ by the way, I'm discovering that 1>x>2 gives False (with x symbolic) $\endgroup$ – andre314 Mar 22 '16 at 21:25
  • $\begingroup$ I have tried this operator on a lot of special cases : it seems to be robust. If someone find a problem, I'm interested. Thanks. $\endgroup$ – andre314 Mar 22 '16 at 21:47
  • $\begingroup$ I have not studied the precedence of the operator. Don't hesitate to use parenthesis. $\endgroup$ – andre314 Mar 22 '16 at 21:50
3
$\begingroup$

You can also use the BoolEval package. You'd use it like this:

Needs["BoolEval`"]
FreeQ[BoolEval[{1, 2, 3} > {0, 1, 2}], 0]
(* True *)

Or

Times @@ BoolEval[{1, 2, 3} > {0, 1, 2}] == 1

The point being that BoolEval returns a 1 or a 0 for each comparison, representing true or false. If there are no zeroes that means that all comparisons were true.

How do I use relational operators on vectors?

BoolEval is a general answer to this question.

If you want a more compact syntax you could implement BoolEvalAnd, BoolEvalOr etc. along the lines of the solution above.

| improve this answer | |
$\endgroup$

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.