Home > OS >  Matlab Equivalent of sortrows for columns
Matlab Equivalent of sortrows for columns

Time:11-09

To sort a matrix according to all columns except the first, I used the following code. I do not want sortrows to consider the first column because that is meant to keep track of the row numbers.

B = [1     1     0     0     0     0     0     0     0     1
     2     0     1     0     0     0     0     1     0     0
     3     0     0     1     0     1     0     0     1     0
     4     0     1     0     0     0     1     1     0     0
     5     0     0     1     0     0     0     0     1     0
     6     0     0     0     0     0     1     1     0     0
     7     1     0     0     1     0     0     0     0     0
     8     0     0     1     0     1     0     0     0     0]; 

D = -sortrows(-B,[2:size(B,2)])

What if you want to sort the matrix according to all rows except the first, so the first element of each column would be ignored when sorting them in descending order? Is there any similar function to sortrows?

To clarify, the desired output is

 1     0     0     0     0     0     0     1     0     1
 2     1     1     0     0     0     0     0     0     0
 3     0     0     1     1     1     0     0     0     0
 4     1     1     0     0     0     1     0     0     0
 5     0     0     1     1     0     0     0     0     0
 6     1     0     0     0     0     1     0     0     0
 7     0     0     0     0     0     0     1     1     0
 8     0     0     1     0     1     0     0     0     0

CodePudding user response:

You can do this via

  • transposing the input and output
  • keeping column 1 separate
  • you can use negative sort indices to avoid what you've done making the input and output negative
A = [B(:,1) sortrows( B(:,2:end).', -(2:size(B,1)) ).'];

>> A 
A =
     1     0     0     0     0     0     0     1     0     1
     2     1     1     0     0     0     0     0     0     0
     3     0     0     1     1     1     0     0     0     0
     4     1     1     0     0     0     1     0     0     0
     5     0     0     1     1     0     0     0     0     0
     6     1     0     0     0     0     1     0     0     0
     7     0     0     0     0     0     0     1     1     0
     8     0     0     1     0     1     0     0     0     0
  • Related