Home > Blockchain >  Arranging diagonal matrix in ascending order
Arranging diagonal matrix in ascending order

Time:09-21

I have a diagonal matrix and a matrix of same dimensions. How do I arrange the diagonal matrix in ascending order and then do the same steps on the other matrix ? For example if my matrix is 3 x 3, and I have to swap the 1st and 2nd column entries in diagonal to make it ascending, how do I apply this same set of steps to the other matrix but here I swap the whole 1st and 2nd column?

I thought about using some kind of merge sort but then it will not arrange the values on the diagonals. How do I do that ?

CodePudding user response:

To sort a set of values, you usually have to reorder them. You can do so by sorting the directly, but you can also sort them indirectly, by first computing a sequence of indices which tells you how you would reorder the sequence. In Python, this sequence can be obtained by the numpy.argsort method. Once you have the sequence, you can apply it to sort your set of numbers, but you can also use it to rearrange any array of values in the same way. Here is an example:

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)

Note, in Matlab the index sequence that sorts a sequence is given in the second return value of the sort function.

  • Related