Matlab Equivalent of sortrows for columns

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

2 Comments

"I do not want sortrows to consider the first column because that is meant to keep track of the row numbers."
A much better approach is to just use the second output from SORTROWS:
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]
B = 8×10
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)]) % your complex approach
D = 8×10
7 1 0 0 1 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 4 0 1 0 0 0 1 1 0 0 2 0 1 0 0 0 0 1 0 0 3 0 0 1 0 1 0 0 1 0 8 0 0 1 0 1 0 0 0 0 5 0 0 1 0 0 0 0 1 0 6 0 0 0 0 0 1 1 0 0
C = B(:,2:end); % this is your actual data matrix
[D,X] = sortrows(C,'descend') % simpler MATLAB approach
D = 8×9
1 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 1 0 0 0 1 1 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 1 0 0 1 0 0 0 1 0 1 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0
X = 8×1
7 1 4 2 3 8 5 6
Do not mix data and indices together. Once you give up on that, then your task is probably a lot easier (hint: transpose).
Can you explain in more details how you got the first two rows of your desired output?
Normally sortrows() expects you to put the column(s) that sorting is done by. Rows are rearranged according to the sorting order of the column you gave it. I'm not even sure what sorting means when you have a matrix of just 1s and 0s. Does it have anything to do with a binary image (image segmentation)?

Sign in to comment.

Answers (0)

Categories

Products

Release

R2019b

Tags

Asked:

on 8 Nov 2021

Commented:

on 8 Nov 2021

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!