Matlab Equivalent of sortrows for columns

2 views (last 30 days)
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
Stephen23
Stephen23 on 8 Nov 2021
Edited: Stephen23 on 8 Nov 2021
"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).
Image Analyst
Image Analyst on 8 Nov 2021
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

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Tags

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!