Is there any efficient easy way to compare two lists with the same length with Mathematica?

前端 未结 5 882
感情败类
感情败类 2021-02-13 23:41

Given two lists A={a1,a2,a3,...an} and B={b1,b2,b3,...bn}, I would say A>=B if and only if all ai>=bi.

There is

5条回答
  •  离开以前
    2021-02-14 00:27

    Comparison functions like Greater, GreaterEqual, Equal, Less, LessEqual can be made to apply to lists in a number of ways (they are all variations of the approach in your question).

    With two lists:

     a={a1,a2,a3};
     b={b1,b2,b3};
    

    and two instances with numeric entries

    na={2,3,4}; nb={1,3,2}; 
    

    you can use

    And@@NonNegative[na-nb]
    

    With lists with symoblic entries

    And@@NonNegative[na-nb]
    

    gives

    NonNegative[a1 - b1] && NonNegative[a2 - b2] && NonNegative[a3 - b3]
    

    For general comparisons, one can create a general comparison function like

    listCompare[comp_ (_Greater | _GreaterEqual | _Equal | _Less | _LessEqual), 
             list1_List, list2_List] := And @@ MapThread[comp, {list1, list2}]
    

    Using as

    listCompare[GreaterEqual,na,nb]
    

    gives True. With symbolic entries

    listCompare[GreaterEqual,a,b]
    

    gives the logially equivalent expression a1 <= b1 && a2 <= b2 && a3 <= b3.

提交回复
热议问题