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

标签 python numpy matrix linear-algebra

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

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/

相关文章:

python - 如何从数据帧中但从每个标签中随机删除行?

python - 计算非空值 Pandas

python - 比较数组时,为什么 "in1d"比 "a==b"慢得多

r - R 函数 eigen() 返回的特征向量是否错误?

string - 如何在matlab中制作相同字符串的矩阵?

python - 使用 Pandas 从文件中读取分层 ascii 表

python - Django 文件上传

当仅更新一个索引时,Python numpy Zeros 数组为每个值分配 1

wpf - 数学(在 WPF 中): Getting new x, 平移后的 y 坐标

python - 具有可变边界的 Tensorflow Adam