Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
    
Related question – Leonid Shifrin Mar 23 at 11:34
up vote 8 down vote accepted
And @@ Thread[{a, b} > {c, d}]

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

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.

share|improve this answer
    
by the way, I'm discovering that 1>x>2 gives False (with x symbolic) – andre Mar 22 at 21:25
    
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. – andre Mar 22 at 21:47
    
I have not studied the precedence of the operator. Don't hesitate to use parenthesis. – andre Mar 22 at 21:50

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.