How do I create a boolean mask of length n from two breakpoints without a for loop?

Viewed 115

I am trying to create an array of boolean masks from an array of breakpoint-pairs. So the result should be boolean masks of length n with true values in between the two breakpoints. I could solve the problem iteratively by writing a for loop but I want to find out the vectorized numpy equivalent for it.

mask = np.array([[False, False, False, False, False],
                 [False, False, False, False, False]])
breakpoints = np.array([[1, 3],
                        [2, 4]])
for i, bp in enumerate(breakpoints):
    mask[i, bp[0]:bp[1]] = True

Output:

array([[False,  True,  True, False, False],
       [False, False,  True,  True, False]])

Optimally, I would like to solve this with indexing and array operations in numpy but I can't get my head around the correct way of doing it.

I hope this example is clear and thank you for any help!

1 Answers

You can use the following trick:

>>> breakpoints = np.array([[1, 3],
...                         [2, 4]])
>>> output_width = 5
>>> idx = np.arange(output_width)
>>> (breakpoints[:,[0]] <= idx) & (idx < breakpoints[:,[1]])
array([[False,  True,  True, False, False],
       [False, False,  True,  True, False]])
Related