Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top