# alternative approaches to selecting elements from two vectors conditional on a third

The following will convey the idea: build a new vector based on an existing condition (boolean) vector. For simplicity, I'll build the conditioning vector (cond) in a known fashion.

(* setup: 3 vectors, one of which is boolean *)
init = RandomInteger[10, 10]
subs = RandomInteger[{11, 20}, 10]


Here is one approach to building the desired vector:

MapThread[If, {cond, init, subs}]


Is this a good approach, speedwise? Am I overlooking a builtin?

• try also init + UnitStep[5 - init] (subs - init)?
– kglr
May 18 at 23:08

Clear["Global*"]

\$Version

(* "12.2.0 for Mac OS X x86 (64-bit) (December 12, 2020)" *)


kglr's solution is fast. The performance differences are very dramatic for larger lists

Manipulate[
SeedRandom[1234];
init = RandomInteger[10, n];
subs = RandomInteger[{11, 20}, n];
t1 = RepeatedTiming[sol1 = (* Alan *)
MapThread[If[#1, #2, #3] &, {cond, init, subs}];][[1]];
t2 = RepeatedTiming[sol2 = (* Hanlon *)
`