对于二元域上的矩阵运算,矩阵内的乘法就是模2相乘,矩阵内的加法就是异或操作。
1.矩阵乘法
矩阵乘法的python代码如下:
def square(A):
A_2 = np.zeros((A.shape[0], A.shape[1]), dtype=int)
for i in range(A.shape[0]):
for j in range(A.shape[1]):
A_2[i][j] = np.logical_xor.reduce(np.logical_and(A[i], A[:, j]))
return A_2
上述的函数为乘方运算函数,接下来展示的是更加普遍的乘法运算函数:
def Multipul(A, B): # 二元域上的矩阵乘法
A_B = np.zeros((A.shape[0], B.shape[1]), dtype=int)
for i in range(A.shape[0]):
for j in range(B.shape[1]):
A_B[i][j] = np.logical_xor.reduce(np.logical_and(A[i], B[:, j]))
return A_B
2.矩阵的逆
当然,不仅仅只有矩阵的乘法可以在二元域上操作,矩阵的逆同样可以。
比如下面的这个函数:
def inverse(A):
A_inverse = np.linalg.inv(A)
A_inverse = np.abs(A_inverse)
A_inverse = A_inverse.astype(int)
return A_inverse
对于二元域上求矩阵的逆,就是将正常情况下的求的结果中的负数变为整数,且保证矩阵内的元素只有0和1即可。
更进一步,若是想求矩阵的4次方,矩阵的逆的4次方,就上将上述两个函数简单结合即可。
L0_in = inverse(L0)
L_4 = Multipul(Multipul(L0, L0), Multipul(L0, L0))#4次方
L_4_in = Multipul(Multipul(L0_in, L0_in), Multipul(L0_in, L0_in))#-4次方
这是一个简单的例子:
import numpy as np
def square(A):
A_2 = np.zeros((A.shape[0], A.shape[1]), dtype=int)
for i in range(A.shape[0]):
for j in range(A.shape[1]):
A_2[i][j] = np.logical_xor.reduce(np.logical_and(A[i], A[:, j]))
return A_2
A0 = np.array([[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],dtype=int)
A1 = np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]],dtype=int)
L = np.array([[0, 1, 1, 0], [0, 0, 1, 0], [0, 0, 0, 1],[1, 0, 0, 0]], dtype=int)
A = np.block([[A0,A1,A0,A0],[A0,A0,A1,A0],[A0,A0,A0,A1],[L,A1,A1,L]])#A是一个16*16的矩阵
A_2 = square(A)
print(A_2)
结果如下:
[[0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1]
[0 1 1 0 1 0 0 0 1 0 0 0 0 1 1 0]
[0 0 1 0 0 1 0 0 0 1 0 0 0 0 1 0]
[0 0 0 1 0 0 1 0 0 0 1 0 0 0 0 1]
[1 0 0 0 0 0 0 1 0 0 0 1 1 0 0 0]
[0 0 1 1 0 0 0 0 1 1 1 0 1 0 1 1]
[0 0 0 1 0 0 0 0 0 1 1 0 0 1 0 1]
[1 0 0 0 0 0 0 0 0 0 1 1 1 0 1 0]
[0 1 1 0 0 0 0 0 1 0 0 1 0 1 1 1]]