Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given two vectors, get a matrix of boolean values indicating where elements of vectors are equal

I have two vectors: A of length m, and B of length n. I would like to get an m by n matrix whose element (x,y) is equal to A[x] == B[y].

What's the fastest way to construct this matrix in numpy?

like image 580
Laizer Avatar asked Dec 05 '25 11:12

Laizer


1 Answers

Use NumPy's broadcasting feature by extending the A to a 2D version with None/np.newaxis and then compare against 1D array B resulting in the desired 2D boolean array -

A[:,None] == B

An alternative to creating that 2D version of A would be with reshaping such that the second axis is of length = 1 . So, an alternative solution would be -

A.reshape(-1,1) == B

Sample run -

In [89]: A
Out[89]: array([0, 1, 2, 3])

In [90]: B
Out[90]: array([4, 3, 2, 1, 0])

In [91]: A[:,None] == B
Out[91]: 
array([[False, False, False, False,  True],
       [False, False, False,  True, False],
       [False, False,  True, False, False],
       [False,  True, False, False, False]], dtype=bool)
like image 115
Divakar Avatar answered Dec 07 '25 12:12

Divakar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!