0
votes

Suppose I have some diagonal matrix whose nonzero elements I would like to sort from smallest to largest, so that the top left element is the largest diagonal and the bottom left element is the smallest. Is there an efficient way to find the permutation matrix that corresponds to whatever operation results?

This can be simplified further by seeking a permutation matrix to permute the rows of a column vector in such a way that they are sorted by magnitude, but I still don't know of a good solution.

2
Do you want a matrix with sorted diagonal as the result or do you want a sorted column vector as the result? If you want a matrix, I assume you meant "top left element is the largest diagonal and the bottom right element is the smallest"? - Doug Lipinski
Yes, that was a mistake. Bottom right should be smallest diagonal. - Scott

2 Answers

2
votes

Extract the diagonal entries, find the indices corresponding to sorting those, and use those indices to rearrange an identity matrix into a permutation matrix.

%matrix size
N = 5;

%random diagonal matrix
d=rand(N,1);
D = diag(d);

%extract the diagonal entries of D and sort them
[~,I]=sort(diag(D));

%generate the permutation matrix
P = eye(size(D));
P = P(I,:)

%Verify answer P*D gives the sorted matrix
P*D
1
votes

Use the two outputs of sort:

>> A = diag([8 3 4])
A =
     8     0     0
     0     3     0
     0     0     4

>> [sorted, sorting] = sort(diag(A))
sorted =
     3
     4
     8

sorting =
     2
     3
     1