2
votes

I have a square symmetric matrix A of dimension n in Matlab and I want to reorder the elements in each row in ascending order but preserving the symmetry and without touching the diagonal elements.

E.g.

 n=4;
 A=[10 9 8 7; 9 6 5 4; 8 5 3 2; 7 4 2 1];
 %reorder A in order to obtain
 B=[10 7 8 9; 7 6 4 5; 8 4 3 2; 9 5 2 1];

Could you provide some help?

2

2 Answers

2
votes

you can use triu to sort only the upper triangle and then add the transpose to keep the symmetry. finally just set the diagonal as in the original matrix:

n=4;
A=[10 9 8 7; 9 6 5 4; 8 5 3 2; 7 4 2 1];
% upper triangle indexes
UI = triu(true(size(A)),1);
% upper triangle of A
B = triu(A,1);
% assign inf to diagonal and below - important if there are any negative values in A
B(~UI) = -inf;
% sort rows descending order
B = sort(B,2,'ascend');
% set infs to 0
B(isinf(B)) = 0;
% add lower triangle matrix
B = B + B.';
% set diagonal as original A
B(1:n+1:n^2) = diag(A)
1
votes
A = [10 9 8 7; 
      9 6 5 4; 
      8 5 3 2; 
      7 4 2 1];    
B = sort(triu(A,1),2) + diag(diag(A)) + sort(triu(A,1),2)';

Explain

triu(A,1) gets the upper triangular matrix above the main diagonal, that is

ans0 =

     0     9     8     7
     0     0     5     4
     0     0     0     2
     0     0     0     0

sort(triu(A,1),2) sorts the elements in each row of the above result in an ascending order, that is

ans1 =

     0     7     8     9
     0     0     4     5
     0     0     0     2
     0     0     0     0

diag(diag(A)) gets the diagonal of A, that is

ans2 =

    10     0     0     0
     0     6     0     0
     0     0     3     0
     0     0     0     1

sort(triu(A,1),2)' gets the transpose of the sorted upper triangular matrix, that is

ans =

     0     0     0     0
     7     0     0     0
     8     4     0     0
     9     5     2     0

Add ans1, ans2 and ans3 up, you will get B.