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

前端 未结 5 889
感情败类
感情败类 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:38

    Since you mentioned efficiency as a factor in your question, you may find these functions useful:

    ClearAll[lessEqual, greaterEqual];
    lessEqual[lst1_, lst2_] :=
       SparseArray[1 - UnitStep[lst2 - lst1]]["NonzeroPositions"] === {};
    
    greaterEqual[lst1_, lst2_] :=
       SparseArray[1 - UnitStep[lst1 - lst2]]["NonzeroPositions"] === {};
    

    These functions will be reasonably efficient. The solution of @David is still two-four times faster, and if you want extreme speed and your lists are numerical (made of Integer or Real numbers), you should probably use compilation to C (the solution of @acl and similarly for other operators).

    You can use the same techniques (using Unitize instead of UnitStep to implement equal and unequal), to implement other comparison operators (>, <, ==, !=). Keep in mind that UnitStep[0]==1.

提交回复
热议问题