Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Numpy comparing vectors of length m and n resulting in boolean matrix of size m,n

I am wondering if there is a more efficient way to run the comparison (or really many other functions) using numpy.

a = np.array([1,2,5,7])
b = np.array([0,4,6])

np.repeat(a, len(b)).reshape(-1, len(b)) > b

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

Basically each output (m, n) is the comparison if A_m > B_n

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use broadcasting to make this operation more efficient. Indeed, repeat creates a new temporary array. Here is the resulting code:

a.reshape(-1, 1) > b
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading