# Is there an easy way to index by a binary vector / mask?

I would like to be able to extract elements from a list where indices are specified by a binary mask.

To provide an example, I would like to have a function BinaryIndex doing the following:

foo = {a, b, c}
mask = {True, False, True}
(* expected output *) {a, c}


Is there such a function built-in? I would be able to come up with some implementation, but I would like to have this performance-optimized. If there is no such built-in function, what would be a good approach to make this fast?

Try

Pick[foo, mask]
(* {a, c}*)


Since this question is about performance, I'd like to add that often it's better to work with lists of integers than lists of booleans since lists of integers can be packed. For example, if you want to pick the positive elements from an array using Pick, you can either use Positive to make a boolean selector list or UnitStep to make an integer selector list:

list = RandomReal[{-1, 1}, 100000];
With[{sel = Positive[list]}, Pick[list, sel]; // RepeatedTiming]
With[{sel = UnitStep[list]}, Pick[list, sel, 1]; // RepeatedTiming]


{0.0065, Null}

{0.00099, Null}

As you can see, UnitStep is significantly faster in the Picking step because UnitStep[list] is a packed array:

DeveloperPackedArrayQ[list] (* True *)
DeveloperPackedArrayQ[Positive[list]] (* False *)
Developer$$$$PackedArrayQ[UnitStep[list]] (* True*)


The problem with Booleans in Mathematica is that they cannot be stored in packed arrays, reducing the efficiency of their processing. Suppose that b is already a packed vector of integers, e.g., b = DeveloperToPackedArray[Boole[mask]]. Then you should be able to obtain your result faster with

result = Pick[foo, b, 1];


You may also try the undocumented function RandomPrivatePositionsOf which can be used to determine the actual list idx of indices of 1-entries in the array b; this may be useful if you can reuse idx multiple times.

idx = RandomPrivatePositionsOf[b,1];
result = foo[[idx]];