How to quickly determine if a square logical matrix is a permutation matrix? For instance,
is not a permutation matrix since the 3rd row have 2 entries 1.
PS: A permutation matrix is a square binary matrix that has exactly one entry 1 in each row and each column and 0s elsewhere.
I define a logical matrix like
numpy.array([(0,1,0,0), (0,0,1,0), (0,1,1,0), (1,0,0,1)])
Here is my source code:
#!/usr/bin/env python
import numpy as np
### two test cases
M1 = np.array([
(0, 1, 0, 0),
(0, 0, 1, 0),
(0, 1, 1, 0),
(1, 0, 0, 1)]);
M2 = np.array([
(0, 1, 0, 0),
(0, 0, 1, 0),
(1, 0, 0, 0),
(0, 0, 0, 1)]);
### fuction
def is_perm_matrix(M) :
for sumRow in np.sum(M, axis=1) :
if sumRow != 1 :
return False
for sumCol in np.sum(M, axis=0) :
if sumCol != 1 :
return False
return True
### print the result
print is_perm_matrix(M1) #False
print is_perm_matrix(M2) #True
Is there any better implementation?