Spa*_*ine 6 python numpy matrix linear-algebra
如何快速判断一个方阵逻辑矩阵是否为置换矩阵?例如,

是不置换矩阵由于第三行具有2个条目1。
PS:置换矩阵是一个二元方阵,每行每列只有一个条目 1,其他地方只有一个条目 0。
我定义了一个逻辑矩阵,如
numpy.array([(0,1,0,0), (0,0,1,0), (0,1,1,0), (1,0,0,1)])
Run Code Online (Sandbox Code Playgroud)
这是我的源代码:
numpy.array([(0,1,0,0), (0,0,1,0), (0,1,1,0), (1,0,0,1)])
Run Code Online (Sandbox Code Playgroud)
有没有更好的实现?
那这个呢:
def is_permuation_matrix(x):
x = np.asanyarray(x)
return (x.ndim == 2 and x.shape[0] == x.shape[1] and
(x.sum(axis=0) == 1).all() and
(x.sum(axis=1) == 1).all() and
((x == 1) | (x == 0)).all())
Run Code Online (Sandbox Code Playgroud)
快速测试:
In [37]: is_permuation_matrix(np.eye(3))
Out[37]: True
In [38]: is_permuation_matrix([[0,1],[2,0]])
Out[38]: False
In [39]: is_permuation_matrix([[0,1],[1,0]])
Out[39]: True
In [41]: is_permuation_matrix([[0,1,0],[0,0,1],[1,0,0]])
Out[41]: True
In [42]: is_permuation_matrix([[0,1,0],[0,0,1],[1,0,1]])
Out[42]: False
In [43]: is_permuation_matrix([[0,1,0],[0,0,1]])
Out[43]: False
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2611 次 |
| 最近记录: |