按升序排列对角矩阵
Arranging diagonal matrix in ascending order
我有一个对角矩阵和一个相同维度的矩阵。如何按升序排列对角矩阵,然后对另一个矩阵执行相同的步骤?例如,如果我的矩阵是 3 x 3,并且我必须交换对角线上的第 1 列和第 2 列条目以使其升序,我如何将这组相同的步骤应用于另一个矩阵,但在这里我交换了整个第 1 列和第 2 列列?
我考虑过使用某种合并排序,但它不会将值排列在对角线上。我该怎么做?
要对一组值进行排序,您通常必须对它们重新排序。您可以通过直接排序来做到这一点,但您也可以通过首先计算一个索引序列来间接对它们进行排序,该索引告诉您如何重新排序该序列。在Python中,这个序列可以通过numpy.argsort
方法得到。一旦你有了这个序列,你就可以用它来对你的数字集进行排序,但你也可以用它来以相同的方式重新排列任何值数组。这是一个例子:
import numpy as np
# construct example matrices
n = 4
D = np.diag(np.random.rand(n))
A = np.random.rand(n,n)
# obtain a sequence of indices that would sort the array.
idx = np.argsort(np.diag(D))
# order the diagonal entries according to the sequence
Dp = np.diag(np.diag(D)[idx])
# order the columns according to the sequence
Ap = A[:,idx]
print('idx')
print(idx)
print('D:')
print(D)
print('Dp:')
print(Dp)
print('A:')
print(A)
print('Ap:')
print(Ap)
注意,在 Matlab 中,排序序列的索引序列在 sort
函数的第二个 return 值中给出。
我有一个对角矩阵和一个相同维度的矩阵。如何按升序排列对角矩阵,然后对另一个矩阵执行相同的步骤?例如,如果我的矩阵是 3 x 3,并且我必须交换对角线上的第 1 列和第 2 列条目以使其升序,我如何将这组相同的步骤应用于另一个矩阵,但在这里我交换了整个第 1 列和第 2 列列?
我考虑过使用某种合并排序,但它不会将值排列在对角线上。我该怎么做?
要对一组值进行排序,您通常必须对它们重新排序。您可以通过直接排序来做到这一点,但您也可以通过首先计算一个索引序列来间接对它们进行排序,该索引告诉您如何重新排序该序列。在Python中,这个序列可以通过numpy.argsort
方法得到。一旦你有了这个序列,你就可以用它来对你的数字集进行排序,但你也可以用它来以相同的方式重新排列任何值数组。这是一个例子:
import numpy as np
# construct example matrices
n = 4
D = np.diag(np.random.rand(n))
A = np.random.rand(n,n)
# obtain a sequence of indices that would sort the array.
idx = np.argsort(np.diag(D))
# order the diagonal entries according to the sequence
Dp = np.diag(np.diag(D)[idx])
# order the columns according to the sequence
Ap = A[:,idx]
print('idx')
print(idx)
print('D:')
print(D)
print('Dp:')
print(Dp)
print('A:')
print(A)
print('Ap:')
print(Ap)
注意,在 Matlab 中,排序序列的索引序列在 sort
函数的第二个 return 值中给出。