gpt4 book ai didi

python - 如何快速判断一个矩阵是否为置换矩阵

转载 作者:太空宇宙 更新时间:2023-11-03 11:02:28 25 4
gpt4 key购买 nike

如何快速判断逻辑方阵是否为置换矩阵?例如,

enter image description here

不是置换矩阵,因为第 3 行有 2 个条目 1。

附言:一个permutation matrix是一个方阵二进制矩阵,每一行和每一列只有一个条目 1,其他地方只有一个条目 0。

我定义了一个逻辑矩阵,如

numpy.array([(0,1,0,0), (0,0,1,0), (0,1,1,0), (1,0,0,1)])

这是我的源代码:

#!/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

有没有更好的实现方式?

最佳答案

这个怎么样:

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())

快速测试:

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

关于python - 如何快速判断一个矩阵是否为置换矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28895894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com