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

 Akzeptierte Antwort

Stephen23
Stephen23 am 25 Jan. 2019

1 Stimme

>> 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 Kommentare

Viktor Edlund
Viktor Edlund am 25 Jan. 2019
Hi!
Thank you for your answer. Could you please walk me through your resoning in that code.
Im very new to matlab, so walkthroughs are appreciated!
Kind regards, Viktor
Stephen23
Stephen23 am 26 Jan. 2019
Bearbeitet: Stephen23 am 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:
  1. create a copy of your matrix, change zero to Inf or NaN, then sort.
  2. 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
Viktor Edlund
Viktor Edlund am 14 Feb. 2019
Thanks alot! Good explaining for a newbie ;)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by