我正在尝试对矩阵进行排序 如果我有
[[5 7 1 2]
[4 8 1 4]
[4 0 1 9]
[2 7 5 0]]
我想要这个结果
[[9 8 7 7]
[5 5 4 4]
[4 2 2 1]
[1 1 0 0]]
这是我的代码,我使用随机数
import numpy as np
MatriX = np.random.randint(10, size=(4,4))
print(MatriX)
for i in range(10):
for j in range(10):
a=np.sort(-MatriX,axis=1)*-1
b=np.sort(-a,axis=0)*-1
c=np.transpose(b)
d=np.sort(-c,axis=1)*-1
e=np.sort(-d,axis=0)*-1
print(e)
但是这段代码根本不起作用
您的代码旨在以特定方式对矩阵进行排序,但它有几个问题:
i
和 j
的嵌套循环不是必需的。您可以删除它们,因为它们不会在排序过程中使用。这是正确对矩阵进行排序的代码的简化版本:
import numpy as np
MatriX = np.random.randint(10, size=(4,4))
print("Original Matrix:")
print(MatriX)
a = np.sort(-MatriX, axis=1) * -1
b = np.sort(-a, axis=0) * -1
result = np.sort(-b, axis=1) * -1
print("Sorted Matrix:")
print(result)
此代码对原始矩阵进行正确排序,并按预期打印排序后的矩阵。