سؤال

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.

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top