简体   繁体   中英

Python-equivalent of MATLAB logical matrix from element-wise logical comparison

I am making the transition from MATLAB to Python, and am looking for a quick way to implement MATLAB's array logical comparisons. Here is an example of what I mean:

% Generate row vector, a, counting from 1 to 5.
>> a = 1:5;
% Generate row vector, b.
>> b = [1, 5, 4, 4, 7, 8, 1, 3,2, 10];
% Generate a 10x5 matrix which has the logical 1 (True) where the values of the two arrays are equal, and logical 0 (False) otherwise.
>> a == b'

ans = 

  10×5 logical array

   1   0   0   0   0
   0   0   0   0   1
   0   0   0   1   0
   0   0   0   1   0
   0   0   0   0   0
   0   0   0   0   0
   1   0   0   0   0
   0   0   1   0   0
   0   1   0   0   0
   0   0   0   0   0

I have tried using np.where and other direct forms of indexing, but I cannot seem to properly imitate the MATLAB behaviour. In particular, I would like to avoid using a for loop (or any list comprehension) and any use of pandas in order to optimise performance.

Does anyone know how this is done optimally?

So, I did get a solution, I'm not sure if it really is the best one, but anyways.

a = np.arange(1,6)
b = np.array([1, 5, 4, 4, 7, 8, 1, 3, 2, 10]).reshape(1, 10)
% or b = np.array([[1, 5, 4, 4, 7, 8, 1, 3, 2, 10]])
print(a==b.T)

[[ True False False False False]
 [False False False False  True]
 [False False False  True False]
 [False False False  True False]
 [False False False False False]
 [False False False False False]
 [ True False False False False]
 [False False  True False False]
 [False  True False False False]
 [False False False False False]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM