3 回答

TA貢獻1777條經驗 獲得超10個贊
置換矩陣是一個很好的數學概念,但它們不是您以編程方式處理向量中元素重新排序的方式(除非您嘗試使用 numpy 做一些特殊的事情)。
從重新排序的索引的向量 (K) 創(chuàng)建置換矩陣 (P) 可以這樣完成:
def pMatBuild(A):
return [ [int(a==b) for b in range(len(A))] for a in A ]
K = [0,3,1,4,2]
P = pMatBuild(K)
輸出:
for line in P: print(line)
[1, 0, 0, 0, 0]
[0, 0, 0, 1, 0]
[0, 1, 0, 0, 0]
[0, 0, 0, 0, 1]
[0, 0, 1, 0, 0]
將此置換矩陣應用于另一個向量(即相乘)可以這樣完成:
def pMatApply(P,V):
return [ V[row.index(1)] for row in P ] # inefficient lookup of 1 on each row
輸出:
V = "ABCDE"
print(pMatApply(P,V))
['A', 'D', 'B', 'E', 'C']
但是,在代碼中,比置換矩陣更有效的是使用原始索引向量 K:
V = "ABCDE"
print([V[i] for i in K])
['A', 'D', 'B', 'E', 'C']

TA貢獻1811條經驗 獲得超6個贊
迄今為止我取得的最好成績...
def permmult(a, b):
"""Multiply two permutation matrices.
a,b: lists of positive integers and zero."""
c = []
for row in a:
c.append(b[-row])
return c
添加回答
舉報