对所有矩阵进行排序

问题描述 投票:0回答:1

我正在尝试对矩阵进行排序 如果我有

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

但是这段代码根本不起作用

python sorting matrix
1个回答
0
投票

您的代码旨在以特定方式对矩阵进行排序,但它有几个问题:

  1. i
    j
    的嵌套循环不是必需的。您可以删除它们,因为它们不会在排序过程中使用。
  2. 您似乎打算分多个步骤对矩阵进行排序,但排序步骤的组织方式可能会导致意外结果。

这是正确对矩阵进行排序的代码的简化版本:

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)

此代码对原始矩阵进行正确排序,并按预期打印排序后的矩阵。

© www.soinside.com 2019 - 2024. All rights reserved.