I have given a list of indices, e.g. i = [3 5] and a vector v = 1:6. I need a function f which returns the logical map for the vector v given the indices i, e.g.:
f(i, length(v)) = [0 0 1 0 1 0]
Since I will call this function several million times, I would like to make it as fast as possible. Is there a builtin function which performs this task?
I know I’m late in the game, but I really wanted to find a faster solution which is just as elegant as
ismember. And indeed there is one, that employs the undocumentedismembcfunction:Benchmark
Here’s what I got:
Amazingly,
ismembcis indeed the fastest!Edit:
For very large values of
N(i.e. whenvis a large array), the faster solution is actually slayton’s (and HebeleHododo’s, for that matter). You have quite a variety of strategies to choose from, pick carefully 🙂Edit by H.Muster:
Here’s are benchmark results including
_ismemberoneoutput:Interestingly, Jonas’ solution does not run for me, as I get an
Index exceeds matrix dimensions.error…Edit by hoogamaphone:
It’s worth noting that
ismembcrequires both inputs to be numerical, sorted, non-sparse, non-NaN values, which is a detail that could be easily missed in the source documentation.