1

Given an array A of shape (n,d). n is the number of points (or vectors) and d the dimension of each point.

I want to select points from A that are between two vectors mins and maxes. mins and maxes are of dimension d. mins and maxes have for each dimension the minimum value and the maximum value.

A=array([[ 4,  3, 12,  7],
   [ 3,  2, 10,  5],
   [ 6, 10, 14,  8],
   [ 7, 11, 13, 14],
   [10, 16, 20, 14],
   [12, 19, 22, 16],
   [ 7, 10, 25, 18]])
mins = np.array( [5,9,12,6])
maxes = np.array( [10,17,20,15] )

the results expected are:

[ 6, 10, 14,  8],

[ 7, 11, 13, 14],

[10, 16, 20, 14]

1 Answer 1

1

You can filter these by the following line:

x = np.logical_and((A >= mins).sum(axis=1) == len(mins), (A <= maxes).sum(axis=1) == len(mins))
result = A[x]

result:

array([[ 6, 10, 14,  8],
       [ 7, 11, 13, 14],
       [10, 16, 20, 14]])

Edit: The above can be simplified as:

A[(A <= maxes).sum(axis=1) & (A >= mins).sum(axis=1) == len(mins)]

In depth explanation:

(A >= mins).sum(axis=1) == len(mins)

returns an boolean array where all the True are indexes where each array element within A[index] is larger or equal to each element in the mins array:

array([False, False,  True,  True,  True,  True,  True], dtype=bool)

We join it with (A <= maxes).sum(axis=1) == len(mins), which represent all element smaller than maxes, x comes out to be

array([False, False,  True,  True,  True, False, False], dtype=bool)

And we simply have to apply that to A

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. You response is good. Is there another alternative that is faster if we have points of high dimensions (say 1000 for example) or your method is the fastest.
I don't think so, this only compares your mins and maxes with each row of A just once. Which is the least amount of comparison you'll have to make. You can use A[(A <= maxes).sum(axis=1) & (A >= mins).sum(axis=1) == len(mins)] to make it syntactically easier, but the underlying mechanism is the same. You also benefit from vectorization with numpy operations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.