Row Sorting of Matrices
10 views (last 30 days)
Show older comments
Hi!
Im trying to sort the rows of this matrix in decreacing order with all rows with entries containing zeros (in the first nonzero coloum) gathered at the bottom. By using sortrows(A) im able to sort the rows in decreacing order but have no success in gathering the zero rows in the bottom of the matrix.
I hope this clarifies what i mean.
A =
0 2 4
0 1 6
0 0 5
>> sortrows(A)
ans =
0 0 5
0 1 6
0 2 4
But i want the matrix to be sorted in this way. Shown below.
A=
0 1 6
0 2 4
0 0 5
Im Seeking a generall solution, this matrix is just an example
0 Comments
Accepted Answer
Stephen23
on 25 Jan 2019
>> A = [0,2,4;0,1,6;0,0,5]
A =
0 2 4
0 1 6
0 0 5
>> [~,idx] = sortrows([sum(A==0,2),A]);
>> B = A(idx,:)
B =
0 1 6
0 2 4
0 0 5
3 Comments
Stephen23
on 26 Jan 2019
Edited: Stephen23
on 15 Feb 2019
@Viktor Edlund: What I noticed is that you basically want to treat zero as being larger than all other numbers. This leads to two obvious possible solutions:
- create a copy of your matrix, change zero to Inf or NaN, then sort.
- add a leading column with a count of how many zeros per row, then sort.
For your simple example they will return the same output, but for more complex matrices with zeros distributed throughout, they could return different results. It is up to you to know/decide what algorithm is suitable for your data.
In any case, I picked 2. because it is simple to implement on one line. Here it is broken down into the main operations:
>> A = [0,2,4;0,1,6;0,0,5] % your data matrix.
A =
0 2 4
0 1 6
0 0 5
>> cnt = sum(A==0,2) % count the zeros in each row.
cnt =
1
1
2
>> mat = [cnt,A] % new matrix, first column is zeros count.
mat =
1 0 2 4
1 0 1 6
2 0 0 5
>> [~,idx] = sortrows(mat) % sort rows of new matrix, get sort index.
idx =
2
1
3
>> B = A(idx,:) % use index to sort original data matrix.
B =
0 1 6
0 2 4
0 0 5
Solution 1. could be implemented like this:
>> idx = A==0;
>> B = A;
>> B(idx) = Inf;
>> [B,idy] = sortrows(B);
>> B(idx(idy,:)) = 0
B =
0 1 6
0 2 4
0 0 5
More Answers (0)
See Also
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!