BoolEval


Fast vectorized evaluation of conditional expressions over arrays, with a simple notation. Inspired by MATLAB's advanced logical matrix indexing.


BoolEval is designed for vectorized evaluations of boolean expressions of equalities and inequalities over arrays. It is designed with performance in mind. The same functionality is already accessible in Mathematica through builtin functions such as Map, Select, etc., but using these precludes vectorization. Instead we can often implement the same using UnitStep instead of inequalities, and addition and multiplication instead of the || and && logical operators. This will be very fast, but hard to read and error-prone to write, especially when the distinction between < and <= is important for the application. BoolEval automates the translation from logical expressions of equalities and inequalities to equivalent vectorizable (thus fast) arithmetic operations.


The workhorse function is BoolEval:

arr = Range[10];
(* {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} *)

BoolEval[3 < arr < 8]
(* {0, 0, 0, 1, 1, 1, 1, 0, 0, 0} *)

Results are returned in terms of 1 and 0 instead of True and False to facilitate the use of packed arrays. This output could now be used with Pick to extract the elements for which the expression was true. BoolPick does this in one go:

BoolPick[arr, 3 < arr < 8]
(* {4, 5, 6, 7} *)

Of course we could have use Select for the very same thing, but BoolPick is much faster when working with packed arrays:

arr = N@Range[10^6];
Timing@Select[arr, #^2 < 100 &]
(* {0.891261, {1., 2., 3., 4., 5., 6., 7., 8., 9.}} *)

Timing@BoolPick[arr, arr^2 < 100]
(* {0.133221, {1., 2., 3., 4., 5., 6., 7., 8., 9.}} *)

Furthermore, BoolEval also supports multidimensional arrays.

Finally BoolCount simply counts the number of elements in the array satisfying the condition, e.g.

BoolCount[Range[50]^2 > 50]
(* 43 *)